Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2014 The Bitcoin developers
3 : // Copyright (c) 2014-2015 The Dash developers
4 : // Copyright (c) 2011-2013 The PPCoin developers
5 : // Copyright (c) 2013-2014 The NovaCoin Developers
6 : // Copyright (c) 2014-2018 The BlackCoin Developers
7 : // Copyright (c) 2015-2022 The PIVX Core developers
8 : // Distributed under the MIT software license, see the accompanying
9 : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 :
11 : #ifndef PIVX_VALIDATION_H
12 : #define PIVX_VALIDATION_H
13 :
14 : #if defined(HAVE_CONFIG_H)
15 : #include "config/pivx-config.h"
16 : #endif
17 :
18 : #include "amount.h"
19 : #include "chain.h"
20 : #include "coins.h"
21 : #include "consensus/validation.h"
22 : #include "fs.h"
23 : #include "moneysupply.h"
24 : #include "policy/feerate.h"
25 : #include "script/script_error.h"
26 : #include "sync.h"
27 : #include "txmempool.h"
28 :
29 : #include <algorithm>
30 : #include <atomic>
31 : #include <exception>
32 : #include <map>
33 : #include <memory>
34 : #include <set>
35 : #include <stdint.h>
36 : #include <string>
37 : #include <utility>
38 : #include <vector>
39 :
40 : class AccumulatorCache;
41 : class CBlockIndex;
42 : class CBlockTreeDB;
43 : class CBudgetManager;
44 : class CCoinsViewDB;
45 : class CZerocoinDB;
46 : class CSporkDB;
47 : class CBloomFilter;
48 : class CInv;
49 : class CConnman;
50 : class CNode;
51 : class CScriptCheck;
52 :
53 : struct PrecomputedTransactionData;
54 :
55 : /** Default for -limitancestorcount, max number of in-mempool ancestors */
56 : static const unsigned int DEFAULT_ANCESTOR_LIMIT = 25;
57 : /** Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors */
58 : static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT = 101;
59 : /** Default for -banscore */
60 : static const int DEFAULT_BANSCORE_THRESHOLD = 100;
61 : /** Default for -persistmempool */
62 : static const bool DEFAULT_PERSIST_MEMPOOL = true;
63 : /** Default for -limitdescendantcount, max number of in-mempool descendants */
64 : static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25;
65 : /** Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants */
66 : static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101;
67 : /** Default for -mempoolexpiry, expiration time for mempool transactions in hours */
68 : static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 72;
69 : /** Default for -txindex */
70 : static const bool DEFAULT_TXINDEX = true;
71 : static const bool DEFAULT_CHECKPOINTS_ENABLED = true;
72 : /** The maximum size for transactions we're willing to relay/mine */
73 : static const unsigned int MAX_STANDARD_TX_SIZE = 100000;
74 : static const unsigned int MAX_ZEROCOIN_TX_SIZE = 150000;
75 : /** Maximum kilobytes for transactions to store for processing during reorg */
76 : static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000;
77 : /** Default for -checkblocks */
78 : static const signed int DEFAULT_CHECKBLOCKS = 6;
79 : static const unsigned int DEFAULT_CHECKLEVEL = 3;
80 : /** The maximum size of a blk?????.dat file (since 0.8) */
81 : static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
82 : /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
83 : static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
84 : /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
85 : static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
86 : /** Maximum number of script-checking threads allowed */
87 : static const int MAX_SCRIPTCHECK_THREADS = 16;
88 : /** -par default (number of script-checking threads, 0 = auto) */
89 : static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
90 : /** Number of blocks that can be requested at any given time from a single peer. */
91 : static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
92 : /** Timeout in seconds during which a peer must stall block download progress before being disconnected. */
93 : static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
94 : /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
95 : * less than this number, we reached their tip. Changing this value is a protocol upgrade. */
96 : static const unsigned int MAX_HEADERS_RESULTS = 2000;
97 : /** Size of the "block download window": how far ahead of our current height do we fetch?
98 : * Larger windows tolerate larger download speed differences between peer, but increase the potential
99 : * degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
100 : * harder). We'll probably want to make this a per-peer adaptive value at some point. */
101 : static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
102 : /** Time to wait (in seconds) between writing blocks/block index to disk. */
103 : static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
104 : /** Time to wait (in seconds) between flushing chainstate to disk. */
105 : static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
106 : /** Average delay between local address broadcasts */
107 : static constexpr std::chrono::hours AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL{24};
108 : /** Average delay between peer address broadcasts */
109 : static constexpr std::chrono::seconds AVG_ADDRESS_BROADCAST_INTERVAL{30};
110 : /** Default multiplier used in the computation for shielded txes min fee */
111 : static const unsigned int DEFAULT_SHIELDEDTXFEE_K = 100;
112 : /** Enable bloom filter */
113 : static const bool DEFAULT_PEERBLOOMFILTERS = true;
114 : /** If the tip is older than this (in seconds), the node is considered to be in initial block download. */
115 : static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
116 : /** Maximum age of our tip in seconds for us to be considered current for fee estimation */
117 : static const int64_t MAX_FEE_ESTIMATION_TIP_AGE = 3 * 60 * 60;
118 :
119 : struct BlockHasher {
120 12307855 : size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); }
121 : };
122 :
123 : extern CScript COINBASE_FLAGS;
124 : extern RecursiveMutex cs_main;
125 : extern CTxMemPool mempool;
126 : typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
127 : typedef std::unordered_multimap<uint256, CBlockIndex*, BlockHasher> PrevBlockMap;
128 : extern BlockMap mapBlockIndex;
129 : extern PrevBlockMap mapPrevBlockIndex;
130 : extern uint64_t nLastBlockTx;
131 : extern uint64_t nLastBlockSize;
132 :
133 : // Best block section
134 : extern Mutex g_best_block_mutex;
135 : extern std::condition_variable g_best_block_cv;
136 : extern uint256 g_best_block;
137 : extern int64_t g_best_block_time;
138 :
139 : extern std::atomic<bool> fImporting;
140 : extern std::atomic<bool> fReindex;
141 : extern int nScriptCheckThreads;
142 : extern bool fTxIndex;
143 : extern bool fRequireStandard;
144 : extern bool fCheckBlockIndex;
145 : extern size_t nCoinCacheUsage;
146 : extern CFeeRate minRelayTxFee;
147 : extern int64_t nMaxTipAge;
148 :
149 : extern bool fLargeWorkForkFound;
150 : extern bool fLargeWorkInvalidChainFound;
151 :
152 : extern std::map<uint256, int64_t> mapRejectedBlocks;
153 :
154 : extern CMoneySupply MoneySupply;
155 :
156 : /** Best header we've seen so far (used for getheaders queries' starting points). */
157 : extern CBlockIndex* pindexBestHeader;
158 :
159 : /**
160 : * Process an incoming block. This only returns after the best known valid
161 : * block is made active. Note that it does not, however, guarantee that the
162 : * specific block passed to it has been checked for validity!
163 : *
164 : * If you want to *possibly* get feedback on whether pblock is valid, you must
165 : * install a CValidationInterface (see validationinterface.h) - this will have
166 : * its BlockChecked method called whenever *any* block completes validation.
167 : *
168 : * Note that we guarantee that either the proof-of-work is valid on pblock, or
169 : * (and possibly also) BlockChecked will have been called.
170 : *
171 : * @param[in] pblock The block we want to process.
172 : * @param[out] dbp The already known disk position of pblock, or nullptr if not yet stored.
173 : * @return True if state.IsValid()
174 : */
175 : bool ProcessNewBlock(const std::shared_ptr<const CBlock>& pblock, const FlatFilePos* dbp);
176 :
177 : /** Open a block file (blk?????.dat) */
178 : FILE* OpenBlockFile(const FlatFilePos& pos, bool fReadOnly = false);
179 : /** Open an undo file (rev?????.dat) */
180 : FILE* OpenUndoFile(const FlatFilePos& pos, bool fReadOnly = false);
181 : /** Translation to a filesystem path */
182 : fs::path GetBlockPosFilename(const FlatFilePos &pos);
183 : /** Import blocks from an external file */
184 : bool LoadExternalBlockFile(FILE* fileIn, FlatFilePos* dbp = nullptr);
185 : /** Ensures we have a genesis block in the block tree, possibly writing one to disk. */
186 : bool LoadGenesisBlock();
187 : /** Load the block tree and coins database from disk,
188 : * initializing state if we're running with -reindex. */
189 : bool LoadBlockIndex(std::string& strError) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
190 : /** Update the chain tip based on database information. */
191 : bool LoadChainTip(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
192 : /** Unload database information */
193 : void UnloadBlockIndex();
194 : /** See whether the protocol update is enforced for connected nodes */
195 : int ActiveProtocol();
196 : /** Run an instance of the script checking thread */
197 : void ThreadScriptCheck();
198 :
199 : /** Check whether we are doing an initial block download (synchronizing from disk or network) */
200 : bool IsInitialBlockDownload();
201 : /** Retrieve a transaction (from memory pool, or from disk, if possible) */
202 : bool GetTransaction(const uint256& hash, CTransactionRef& tx, uint256& hashBlock, bool fAllowSlow = false, CBlockIndex* blockIndex = nullptr);
203 : /** Retrieve an output (from memory pool, or from disk, if possible) */
204 : bool GetOutput(const uint256& hash, unsigned int index, CValidationState& state, CTxOut& out);
205 :
206 : double ConvertBitsToDouble(unsigned int nBits);
207 : int64_t GetMasternodePayment(int nHeight);
208 :
209 : /** Find the best known block, and make it the tip of the block chain */
210 : bool ActivateBestChain(CValidationState& state, std::shared_ptr<const CBlock> pblock = std::shared_ptr<const CBlock>());
211 : CAmount GetBlockValue(int nHeight);
212 :
213 : /** Create a new block index entry for a given block hash */
214 : CBlockIndex* InsertBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
215 : /** Flush all state, indexes and buffers to disk. */
216 : void FlushStateToDisk();
217 :
218 :
219 : /** (try to) add transaction to memory pool **/
220 : bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState& state, const CTransactionRef& tx, bool fLimitFree,
221 : bool* pfMissingInputs, bool fOverrideMempoolLimit = false,
222 : bool fRejectInsaneFee = false, bool ignoreFees = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
223 :
224 : /** (try to) add transaction to memory pool with a specified acceptance time **/
225 : bool AcceptToMemoryPoolWithTime(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
226 : bool* pfMissingInputs, int64_t nAcceptTime, bool fOverrideMempoolLimit = false,
227 : bool fRejectInsaneFee = false, bool ignoreFees = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
228 :
229 : CAmount GetMinRelayFee(const CTransaction& tx, const CTxMemPool& pool, unsigned int nBytes);
230 : CAmount GetMinRelayFee(unsigned int nBytes);
231 : /**
232 : * Return the minimum fee for a shielded tx.
233 : */
234 : CAmount GetShieldedTxMinFee(const CTransaction& tx);
235 :
236 : /**
237 : * Check transaction inputs, and make sure any
238 : * pay-to-script-hash transactions are evaluating IsStandard scripts
239 : *
240 : * Why bother? To avoid denial-of-service attacks; an attacker
241 : * can submit a standard HASH... OP_EQUAL transaction,
242 : * which will get accepted into blocks. The redemption
243 : * script can be anything; an attacker could use a very
244 : * expensive-to-check-upon-redemption script like:
245 : * DUP CHECKSIG DROP ... repeated 100 times... OP_1
246 : */
247 :
248 : /**
249 : * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
250 : * This does not modify the UTXO set. If pvChecks is not nullptr, script checks are pushed onto it
251 : * instead of being performed inline.
252 : */
253 : bool CheckInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& view, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData& precomTxData, std::vector<CScriptCheck>* pvChecks = nullptr);
254 :
255 : /** Apply the effects of this transaction on the UTXO set represented by view */
256 : void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight, bool fSkipInvalid = false);
257 :
258 : /**
259 : * Check if transaction will be final in the next block to be created.
260 : *
261 : * Calls IsFinalTx() with current block height and appropriate block time.
262 : *
263 : * See consensus/consensus.h for flag definitions.
264 : */
265 : bool CheckFinalTx(const CTransactionRef& tx, int flags = -1);
266 :
267 :
268 : /**
269 : * Closure representing one script verification
270 : * Note that this stores references to the spending transaction
271 : */
272 4688223 : class CScriptCheck
273 : {
274 : private:
275 : CTxOut m_tx_out;
276 : const CTransaction* ptxTo;
277 : unsigned int nIn;
278 : unsigned int nFlags;
279 : bool cacheStore;
280 : ScriptError error;
281 : PrecomputedTransactionData *precomTxData;
282 :
283 : public:
284 2399783 : CScriptCheck() : ptxTo(0), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR), precomTxData(nullptr) {}
285 1456383 : CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* cachedHashesIn) :
286 : m_tx_out(outIn),
287 : ptxTo(&txToIn),
288 : nIn(nInIn),
289 : nFlags(nFlagsIn),
290 : cacheStore(cacheIn),
291 : error(SCRIPT_ERR_UNKNOWN_ERROR),
292 1456383 : precomTxData(cachedHashesIn) {}
293 :
294 : bool operator()();
295 :
296 2399783 : void swap(CScriptCheck& check)
297 : {
298 2399783 : std::swap(ptxTo, check.ptxTo);
299 2399783 : std::swap(m_tx_out, check.m_tx_out);
300 2399783 : std::swap(nIn, check.nIn);
301 2399783 : std::swap(nFlags, check.nFlags);
302 2399783 : std::swap(cacheStore, check.cacheStore);
303 2399783 : std::swap(error, check.error);
304 2399783 : std::swap(precomTxData, check.precomTxData);
305 2399783 : }
306 :
307 3 : ScriptError GetScriptError() const { return error; }
308 : };
309 :
310 :
311 : /** Functions for disk access for blocks */
312 : bool WriteBlockToDisk(const CBlock& block, FlatFilePos& pos);
313 : bool ReadBlockFromDisk(CBlock& block, const FlatFilePos& pos);
314 : bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex);
315 :
316 :
317 : /** Functions for validating blocks and updating the block tree */
318 :
319 : /** Context-independent validity checks */
320 : bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true, bool fCheckSig = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
321 : bool CheckWork(const CBlock& block, const CBlockIndex* const pindexPrev);
322 :
323 : /** Context-dependent validity checks */
324 : bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex* pindexPrev) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
325 : bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindexPrev);
326 :
327 : /** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */
328 : bool TestBlockValidity(CValidationState& state, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true, bool fCheckBlockSig = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
329 :
330 : bool AcceptBlockHeader(const CBlock& block, CValidationState& state, CBlockIndex** ppindex = nullptr, CBlockIndex* pindexPrev = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
331 :
332 :
333 : /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
334 : class CVerifyDB
335 : {
336 : public:
337 : CVerifyDB();
338 : ~CVerifyDB();
339 : bool VerifyDB(CCoinsView* coinsview, int nCheckLevel, int nCheckDepth);
340 : };
341 :
342 : /** Replay blocks that aren't fully applied to the database. */
343 : bool ReplayBlocks(const CChainParams& params, CCoinsView* view);
344 :
345 4653541 : inline CBlockIndex* LookupBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
346 : {
347 4653541 : AssertLockHeld(cs_main);
348 4653541 : BlockMap::const_iterator it = mapBlockIndex.find(hash);
349 4653541 : return it == mapBlockIndex.end() ? nullptr : it->second;
350 : }
351 :
352 : /** Find the last common block between the parameter chain and a locator. */
353 : CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
354 :
355 : /** Mark a block as invalid. */
356 : bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
357 :
358 : /** Remove invalidity status from a block and its descendants. */
359 : bool ReconsiderBlock(CValidationState& state, CBlockIndex* pindex);
360 :
361 : /** The currently-connected chain of blocks (protected by cs_main). */
362 : extern CChain chainActive;
363 :
364 : /** Global variable that points to the coins database (protected by cs_main) */
365 : extern std::unique_ptr<CCoinsViewDB> pcoinsdbview;
366 :
367 : /** Global variable that points to the active CCoinsView (protected by cs_main) */
368 : extern std::unique_ptr<CCoinsViewCache> pcoinsTip;
369 :
370 : /** Global variable that points to the active block tree (protected by cs_main) */
371 : extern std::unique_ptr<CBlockTreeDB> pblocktree;
372 :
373 : /** Global variable that points to the zerocoin database (protected by cs_main) */
374 : extern std::unique_ptr<CZerocoinDB> zerocoinDB;
375 :
376 : /** In-memory cache for the zerocoin accumulators */
377 : extern std::unique_ptr<AccumulatorCache> accumulatorCache;
378 :
379 : /** Global variable that points to the spork database (protected by cs_main) */
380 : extern std::unique_ptr<CSporkDB> pSporkDB;
381 :
382 : /**
383 : * Return a reliable pointer (in mapBlockIndex) to the chain's tip index
384 : */
385 : CBlockIndex* GetChainTip();
386 :
387 : /**
388 : * Return the spend height, which is one more than the inputs.GetBestBlock().
389 : * While checking, GetBestBlock() refers to the parent block. (protected by cs_main)
390 : * This is also true for mempool checks.
391 : */
392 : int GetSpendHeight(const CCoinsViewCache& inputs);
393 :
394 : /** Reject codes greater or equal to this can be returned by AcceptToMemPool
395 : * for transactions, to signal internal conditions. They cannot and should not
396 : * be sent over the P2P network.
397 : */
398 : static const unsigned int REJECT_INTERNAL = 0x100;
399 : /** Too high fee. Can not be triggered by P2P transactions */
400 : static const unsigned int REJECT_HIGHFEE = 0x100;
401 : /** Transaction is already known (either in mempool or blockchain) */
402 : static const unsigned int REJECT_ALREADY_KNOWN = 0x101;
403 : /** Transaction conflicts with a transaction already known */
404 : static const unsigned int REJECT_CONFLICT = 0x102;
405 :
406 : /** Get block file info entry for one block file */
407 : CBlockFileInfo* GetBlockFileInfo(size_t n);
408 :
409 : /** Dump the mempool to disk. */
410 : bool DumpMempool(const CTxMemPool& pool);
411 :
412 : /** Load the mempool from disk. */
413 : bool LoadMempool(CTxMemPool& pool);
414 :
415 : #endif // PIVX_VALIDATION_H
|