1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #ifndef BITCOIN_VALIDATION_H
7 #define BITCOIN_VALIDATION_H
8 
9 #if defined(HAVE_CONFIG_H)
10 #include <config/bitcoin-config.h>
11 #endif
12 
13 #include <amount.h>
14 #include <coins.h>
15 #include <crypto/common.h> // for ReadLE64
16 #include <fs.h>
17 #include <policy/feerate.h>
18 #include <protocol.h> // For CMessageHeader::MessageStartChars
19 #include <script/script_error.h>
20 #include <sync.h>
21 #include <versionbits.h>
22 
23 #include <algorithm>
24 #include <exception>
25 #include <map>
26 #include <memory>
27 #include <set>
28 #include <stdint.h>
29 #include <string>
30 #include <utility>
31 #include <vector>
32 
33 #include <atomic>
34 
35 class CBlockIndex;
36 class CBlockTreeDB;
37 class CChainParams;
38 class CCoinsViewDB;
39 class CInv;
40 class CConnman;
41 class CScriptCheck;
42 class CBlockPolicyEstimator;
43 class CTxMemPool;
44 class CValidationState;
45 struct ChainTxData;
46 
47 struct PrecomputedTransactionData;
48 struct LockPoints;
49 
50 /** Default for -whitelistrelay. */
51 static const bool DEFAULT_WHITELISTRELAY = true;
52 /** Default for -whitelistforcerelay. */
53 static const bool DEFAULT_WHITELISTFORCERELAY = false;
54 /** Default for -minrelaytxfee, minimum relay fee for transactions */
55 static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 1000;
56 //! -maxtxfee default
57 static const CAmount DEFAULT_TRANSACTION_MAXFEE = COIN / 10;
58 //! Discourage users to set fees higher than this amount (in satoshis) per kB
59 static const CAmount HIGH_TX_FEE_PER_KB = COIN / 100;
60 //! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
61 static const CAmount HIGH_MAX_TX_FEE = 100 * HIGH_TX_FEE_PER_KB;
62 /** Default for -limitancestorcount, max number of in-mempool ancestors */
63 static const unsigned int DEFAULT_ANCESTOR_LIMIT = 25;
64 /** Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors */
65 static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT = 101;
66 /** Default for -limitdescendantcount, max number of in-mempool descendants */
67 static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25;
68 /** Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants */
69 static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101;
70 /** Default for -mempoolexpiry, expiration time for mempool transactions in hours */
71 static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 336;
72 /** Maximum kilobytes for transactions to store for processing during reorg */
73 static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000;
74 /** The maximum size of a blk?????.dat file (since 0.8) */
75 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
76 /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
77 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
78 /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
79 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
80 
81 /** Maximum number of script-checking threads allowed */
82 static const int MAX_SCRIPTCHECK_THREADS = 16;
83 /** -par default (number of script-checking threads, 0 = auto) */
84 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
85 /** Number of blocks that can be requested at any given time from a single peer. */
86 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
87 /** Timeout in seconds during which a peer must stall block download progress before being disconnected. */
88 static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
89 /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
90  *  less than this number, we reached its tip. Changing this value is a protocol upgrade. */
91 static const unsigned int MAX_HEADERS_RESULTS = 2000;
92 /** Maximum depth of blocks we're willing to serve as compact blocks to peers
93  *  when requested. For older blocks, a regular BLOCK response will be sent. */
94 static const int MAX_CMPCTBLOCK_DEPTH = 5;
95 /** Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for. */
96 static const int MAX_BLOCKTXN_DEPTH = 10;
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 pruning harder). We'll probably
100  *  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 /** Maximum length of reject messages. */
107 static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
108 /** Block download timeout base, expressed in millionths of the block interval (i.e. 10 min) */
109 static const int64_t BLOCK_DOWNLOAD_TIMEOUT_BASE = 1000000;
110 /** Additional block download timeout per parallel downloading peer (i.e. 5 min) */
111 static const int64_t BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 500000;
112 
113 static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
114 /** Maximum age of our tip in seconds for us to be considered current for fee estimation */
115 static const int64_t MAX_FEE_ESTIMATION_TIP_AGE = 3 * 60 * 60;
116 
117 /** Default for -permitbaremultisig */
118 static const bool DEFAULT_PERMIT_BAREMULTISIG = true;
119 static const bool DEFAULT_CHECKPOINTS_ENABLED = true;
120 static const bool DEFAULT_TXINDEX = false;
121 static const unsigned int DEFAULT_BANSCORE_THRESHOLD = 100;
122 /** Default for -persistmempool */
123 static const bool DEFAULT_PERSIST_MEMPOOL = true;
124 /** Default for -mempoolreplacement */
125 static const bool DEFAULT_ENABLE_REPLACEMENT = false;
126 /** Default for using fee filter */
127 static const bool DEFAULT_FEEFILTER = true;
128 
129 /** Maximum number of headers to announce when relaying blocks with headers message.*/
130 static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;
131 
132 /** Maximum number of unconnecting headers announcements before DoS score */
133 static const int MAX_UNCONNECTING_HEADERS = 10;
134 
135 static const bool DEFAULT_PEERBLOOMFILTERS = true;
136 
137 /** Default for -stopatheight */
138 static const int DEFAULT_STOPATHEIGHT = 0;
139 
140 struct BlockHasher
141 {
142     // this used to call `GetCheapHash()` in uint256, which was later moved; the
143     // cheap hash function simply calls ReadLE64() however, so the end result is
144     // identical
operatorBlockHasher145     size_t operator()(const uint256& hash) const { return ReadLE64(hash.begin()); }
146 };
147 
148 extern CScript COINBASE_FLAGS;
149 extern CCriticalSection cs_main;
150 extern CBlockPolicyEstimator feeEstimator;
151 extern CTxMemPool mempool;
152 extern std::atomic_bool g_is_mempool_loaded;
153 typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
154 extern BlockMap& mapBlockIndex GUARDED_BY(cs_main);
155 extern const std::string strMessageMagic;
156 extern Mutex g_best_block_mutex;
157 extern std::condition_variable g_best_block_cv;
158 extern uint256 g_best_block;
159 extern std::atomic_bool fImporting;
160 extern std::atomic_bool fReindex;
161 extern int nScriptCheckThreads;
162 extern bool fIsBareMultisigStd;
163 extern bool fRequireStandard;
164 extern bool fCheckBlockIndex;
165 extern bool fCheckpointsEnabled;
166 extern size_t nCoinCacheUsage;
167 /** A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) */
168 extern CFeeRate minRelayTxFee;
169 /** Absolute maximum transaction fee (in satoshis) used by wallet and mempool (rejects high fee in sendrawtransaction) */
170 extern CAmount maxTxFee;
171 /** If the tip is older than this (in seconds), the node is considered to be in initial block download. */
172 extern int64_t nMaxTipAge;
173 extern bool fEnableReplacement;
174 
175 /** Block hash whose ancestors we will assume to have valid scripts without checking them. */
176 extern uint256 hashAssumeValid;
177 
178 /** Minimum work we will assume exists on some valid chain. */
179 extern arith_uint256 nMinimumChainWork;
180 
181 /** Best header we've seen so far (used for getheaders queries' starting points). */
182 extern CBlockIndex *pindexBestHeader;
183 
184 /** Minimum disk space required - used in CheckDiskSpace() */
185 static const uint64_t nMinDiskSpace = 52428800;
186 
187 /** Pruning-related variables and constants */
188 /** True if any block files have ever been pruned. */
189 extern bool fHavePruned;
190 /** True if we're running in -prune mode. */
191 extern bool fPruneMode;
192 /** Number of MiB of block files that we're trying to stay below. */
193 extern uint64_t nPruneTarget;
194 /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */
195 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
196 /** Minimum blocks required to signal NODE_NETWORK_LIMITED */
197 static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288;
198 
199 static const signed int DEFAULT_CHECKBLOCKS = 6 * 4;
200 static const unsigned int DEFAULT_CHECKLEVEL = 3;
201 
202 // Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
203 // At 1MB per block, 288 blocks = 288MB.
204 // Add 15% for Undo data = 331MB
205 // Add 20% for Orphan block rate = 397MB
206 // We want the low water mark after pruning to be at least 397 MB and since we prune in
207 // full block file chunks, we need the high water mark which triggers the prune to be
208 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
209 // Setting the target to >= 550 MiB will make it likely we can respect the target.
210 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
211 
212 /**
213  * Process an incoming block. This only returns after the best known valid
214  * block is made active. Note that it does not, however, guarantee that the
215  * specific block passed to it has been checked for validity!
216  *
217  * If you want to *possibly* get feedback on whether pblock is valid, you must
218  * install a CValidationInterface (see validationinterface.h) - this will have
219  * its BlockChecked method called whenever *any* block completes validation.
220  *
221  * Note that we guarantee that either the proof-of-work is valid on pblock, or
222  * (and possibly also) BlockChecked will have been called.
223  *
224  * May not be called in a
225  * validationinterface callback.
226  *
227  * @param[in]   pblock  The block we want to process.
228  * @param[in]   fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers.
229  * @param[out]  fNewBlock A boolean which is set to indicate if the block was first received via this call
230  * @return True if state.IsValid()
231  */
232 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool* fNewBlock) LOCKS_EXCLUDED(cs_main);
233 
234 /**
235  * Process incoming block headers.
236  *
237  * May not be called in a
238  * validationinterface callback.
239  *
240  * @param[in]  block The block headers themselves
241  * @param[out] state This may be set to an Error state if any error occurred processing them
242  * @param[in]  chainparams The params for the chain we want to connect to
243  * @param[out] ppindex If set, the pointer will be set to point to the last new block index object for the given headers
244  * @param[out] first_invalid First header that fails validation, if one exists
245  */
246 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex = nullptr, CBlockHeader* first_invalid = nullptr) LOCKS_EXCLUDED(cs_main);
247 
248 /** Check whether enough disk space is available for an incoming block */
249 bool CheckDiskSpace(uint64_t nAdditionalBytes = 0, bool blocks_dir = false);
250 /** Open a block file (blk?????.dat) */
251 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
252 /** Translation to a filesystem path */
253 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix);
254 /** Import blocks from an external file */
255 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp = nullptr);
256 /** Ensures we have a genesis block in the block tree, possibly writing one to disk. */
257 bool LoadGenesisBlock(const CChainParams& chainparams);
258 /** Load the block tree and coins database from disk,
259  * initializing state if we're running with -reindex. */
260 bool LoadBlockIndex(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
261 /** Update the chain tip based on database information. */
262 bool LoadChainTip(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
263 /** Unload database information */
264 void UnloadBlockIndex();
265 /** Run an instance of the script checking thread */
266 void ThreadScriptCheck();
267 /** Check whether we are doing an initial block download (synchronizing from disk or network) */
268 bool IsInitialBlockDownload();
269 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
270 bool GetTransaction(const uint256& hash, CTransactionRef& tx, const Consensus::Params& params, uint256& hashBlock, const CBlockIndex* const blockIndex = nullptr);
271 /**
272  * Find the best known block, and make it the tip of the block chain
273  *
274  * May not be called with cs_main held. May not be called in a
275  * validationinterface callback.
276  */
277 bool ActivateBestChain(CValidationState& state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock = std::shared_ptr<const CBlock>());
278 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
279 
280 /** Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip). */
281 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
282 
283 /** Calculate the amount of disk space the block & undo files currently use */
284 uint64_t CalculateCurrentUsage();
285 
286 /**
287  *  Mark one block file as pruned.
288  */
289 void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
290 
291 /**
292  *  Actually unlink the specified files
293  */
294 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune);
295 
296 /** Flush all state, indexes and buffers to disk. */
297 void FlushStateToDisk();
298 /** Prune block files and flush state to disk. */
299 void PruneAndFlush();
300 /** Prune block files up to a given height */
301 void PruneBlockFilesManual(int nManualPruneHeight);
302 
303 /** (try to) add transaction to memory pool
304  * plTxnReplaced will be appended to with all transactions replaced from mempool **/
305 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
306                         bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
307                         bool bypass_limits, const CAmount nAbsurdFee, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
308 
309 /** Convert CValidationState to a human-readable message for logging */
310 std::string FormatStateMessage(const CValidationState &state);
311 
312 /** Get the BIP9 state for a given deployment at the current tip. */
313 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos);
314 
315 /** Get the numerical statistics for the BIP9 state for a given deployment at the current tip. */
316 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos);
317 
318 /** Get the block height at which the BIP9 deployment switched into the state for the block building on the current tip. */
319 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos);
320 
321 
322 /** Apply the effects of this transaction on the UTXO set represented by view */
323 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
324 
325 /** Transaction validation functions */
326 
327 /**
328  * Check if transaction will be final in the next block to be created.
329  *
330  * Calls IsFinalTx() with current block height and appropriate block time.
331  *
332  * See consensus/consensus.h for flag definitions.
333  */
334 bool CheckFinalTx(const CTransaction &tx, int flags = -1) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
335 
336 /**
337  * Test whether the LockPoints height and time are still valid on the current chain
338  */
339 bool TestLockPointValidity(const LockPoints* lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
340 
341 /**
342  * Check if transaction will be BIP 68 final in the next block to be created.
343  *
344  * Simulates calling SequenceLocks() with data from the tip of the current active chain.
345  * Optionally stores in LockPoints the resulting height and time calculated and the hash
346  * of the block needed for calculation or skips the calculation and uses the LockPoints
347  * passed in for evaluation.
348  * The LockPoints should not be considered valid if CheckSequenceLocks returns false.
349  *
350  * See consensus/consensus.h for flag definitions.
351  */
352 bool CheckSequenceLocks(const CTxMemPool& pool, const CTransaction& tx, int flags, LockPoints* lp = nullptr, bool useExistingLockPoints = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
353 
354 /**
355  * Closure representing one script verification
356  * Note that this stores references to the spending transaction
357  */
358 class CScriptCheck
359 {
360 private:
361     CTxOut m_tx_out;
362     const CTransaction *ptxTo;
363     unsigned int nIn;
364     unsigned int nFlags;
365     bool cacheStore;
366     ScriptError error;
367     PrecomputedTransactionData *txdata;
368 
369 public:
CScriptCheck()370     CScriptCheck(): ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
CScriptCheck(const CTxOut & outIn,const CTransaction & txToIn,unsigned int nInIn,unsigned int nFlagsIn,bool cacheIn,PrecomputedTransactionData * txdataIn)371     CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
372         m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
373 
374     bool operator()();
375 
swap(CScriptCheck & check)376     void swap(CScriptCheck &check) {
377         std::swap(ptxTo, check.ptxTo);
378         std::swap(m_tx_out, check.m_tx_out);
379         std::swap(nIn, check.nIn);
380         std::swap(nFlags, check.nFlags);
381         std::swap(cacheStore, check.cacheStore);
382         std::swap(error, check.error);
383         std::swap(txdata, check.txdata);
384     }
385 
GetScriptError()386     ScriptError GetScriptError() const { return error; }
387 };
388 
389 /** Initializes the script-execution cache */
390 void InitScriptExecutionCache();
391 
392 
393 /** Functions for disk access for blocks */
394 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams);
395 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams);
396 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& message_start);
397 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CBlockIndex* pindex, const CMessageHeader::MessageStartChars& message_start);
398 
399 /** Functions for validating blocks and updating the block tree */
400 
401 /** Context-independent validity checks */
402 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
403 
404 /** Check a block is completely valid from start to finish (only works on top of our current best block) */
405 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
406 
407 /** Check whether witness commitments are required for block. */
408 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params);
409 
410 /** Check whether NULLDUMMY (BIP 147) has activated. */
411 bool IsNullDummyEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params);
412 
413 /** When there are blocks in the active chain with missing data, rewind the chainstate and remove them from the block index */
414 bool RewindBlockIndex(const CChainParams& params);
415 
416 /** Update uncommitted block structures (currently: only the witness reserved value). This is safe for submitted blocks. */
417 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
418 
419 /** Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks). */
420 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
421 
422 /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
423 class CVerifyDB {
424 public:
425     CVerifyDB();
426     ~CVerifyDB();
427     bool VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
428 };
429 
430 /** Replay blocks that aren't fully applied to the database. */
431 bool ReplayBlocks(const CChainParams& params, CCoinsView* view);
432 
LookupBlockIndex(const uint256 & hash)433 inline CBlockIndex* LookupBlockIndex(const uint256& hash)
434 {
435     AssertLockHeld(cs_main);
436     BlockMap::const_iterator it = mapBlockIndex.find(hash);
437     return it == mapBlockIndex.end() ? nullptr : it->second;
438 }
439 
440 /** Find the last common block between the parameter chain and a locator. */
441 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
442 
443 /** Mark a block as precious and reorganize.
444  *
445  * May not be called in a
446  * validationinterface callback.
447  */
448 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main);
449 
450 /** Mark a block as invalid. */
451 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindex);
452 
453 /** Remove invalidity status from a block and its descendants. */
454 void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
455 
456 /** The currently-connected chain of blocks (protected by cs_main). */
457 extern CChain& chainActive;
458 
459 /** Global variable that points to the coins database (protected by cs_main) */
460 extern std::unique_ptr<CCoinsViewDB> pcoinsdbview;
461 
462 /** Global variable that points to the active CCoinsView (protected by cs_main) */
463 extern std::unique_ptr<CCoinsViewCache> pcoinsTip;
464 
465 /** Global variable that points to the active block tree (protected by cs_main) */
466 extern std::unique_ptr<CBlockTreeDB> pblocktree;
467 
468 /**
469  * Return the spend height, which is one more than the inputs.GetBestBlock().
470  * While checking, GetBestBlock() refers to the parent block. (protected by cs_main)
471  * This is also true for mempool checks.
472  */
473 int GetSpendHeight(const CCoinsViewCache& inputs);
474 
475 extern VersionBitsCache versionbitscache;
476 
477 /**
478  * Determine what nVersion a new block should use.
479  */
480 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params);
481 
482 /** Reject codes greater or equal to this can be returned by AcceptToMemPool
483  * for transactions, to signal internal conditions. They cannot and should not
484  * be sent over the P2P network.
485  */
486 static const unsigned int REJECT_INTERNAL = 0x100;
487 /** Too high fee. Can not be triggered by P2P transactions */
488 static const unsigned int REJECT_HIGHFEE = 0x100;
489 
490 /** Get block file info entry for one block file */
491 CBlockFileInfo* GetBlockFileInfo(size_t n);
492 
493 /** Dump the mempool to disk. */
494 bool DumpMempool();
495 
496 /** Load the mempool from disk. */
497 bool LoadMempool();
498 
499 //! Check whether the block associated with this index entry is pruned or not.
IsBlockPruned(const CBlockIndex * pblockindex)500 inline bool IsBlockPruned(const CBlockIndex* pblockindex)
501 {
502     return (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0);
503 }
504 
505 #endif // BITCOIN_VALIDATION_H
506