1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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 <txmempool.h> // For CTxMemPool::cs
22 #include <txdb.h>
23 #include <versionbits.h>
24 #include <serialize.h>
25 
26 #include <atomic>
27 #include <map>
28 #include <memory>
29 #include <set>
30 #include <stdint.h>
31 #include <utility>
32 #include <vector>
33 
34 #include <consensus/consensus.h>
35 
36 /////////////////////////////////////////// qtum
37 class CWalletTx;
38 
39 #include <qtum/qtumstate.h>
40 #include <qtum/qtumDGP.h>
41 #include <libethereum/ChainParams.h>
42 #include <libethereum/LastBlockHashesFace.h>
43 #include <libethashseal/GenesisInfo.h>
44 #include <script/standard.h>
45 #include <qtum/storageresults.h>
46 
47 
48 extern std::unique_ptr<QtumState> globalState;
49 extern std::shared_ptr<dev::eth::SealEngineFace> globalSealEngine;
50 extern bool fRecordLogOpcodes;
51 extern bool fIsVMlogFile;
52 extern bool fGettingValuesDGP;
53 
54 struct EthTransactionParams;
55 using valtype = std::vector<unsigned char>;
56 using ExtractQtumTX = std::pair<std::vector<QtumTransaction>, std::vector<EthTransactionParams>>;
57 ///////////////////////////////////////////
58 
59 class CChainState;
60 class BlockValidationState;
61 class CBlockIndex;
62 class CBlockTreeDB;
63 class CBlockUndo;
64 class CChainParams;
65 class CInv;
66 class CConnman;
67 class CScriptCheck;
68 class CBlockPolicyEstimator;
69 class CTxMemPool;
70 class TxValidationState;
71 struct CDiskTxPos;
72 class CWallet;
73 struct ChainTxData;
74 
75 struct DisconnectedBlockTransactions;
76 struct PrecomputedTransactionData;
77 struct LockPoints;
78 
79 /** Minimum gas limit that is allowed in a transaction within a block - prevent various types of tx and mempool spam **/
80 static const uint64_t MINIMUM_GAS_LIMIT = 10000;
81 
82 static const uint64_t MEMPOOL_MIN_GAS_LIMIT = 22000;
83 
84 static const uint64_t ADD_DELEGATION_MIN_GAS_LIMIT = 2200000;
85 
86 /** Default for -minrelaytxfee, minimum relay fee for transactions */
87 static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 400000;
88 /** Default for -limitancestorcount, max number of in-mempool ancestors */
89 static const unsigned int DEFAULT_ANCESTOR_LIMIT = 25;
90 /** Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors */
91 static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT = 101;
92 /** Default for -limitdescendantcount, max number of in-mempool descendants */
93 static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25;
94 /** Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants */
95 static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101;
96 /**
97  * An extra transaction can be added to a package, as long as it only has one
98  * ancestor and is no larger than this. Not really any reason to make this
99  * configurable as it doesn't materially change DoS parameters.
100  */
101 static const unsigned int EXTRA_DESCENDANT_TX_SIZE_LIMIT = 10000;
102 /** Default for -mempoolexpiry, expiration time for mempool transactions in hours */
103 static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 336;
104 /** Maximum kilobytes for transactions to store for processing during reorg */
105 static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000;
106 /** The maximum size of a blk?????.dat file (since 0.8) */
107 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
108 /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
109 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
110 /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
111 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
112 
113 /** Maximum number of dedicated script-checking threads allowed */
114 static const int MAX_SCRIPTCHECK_THREADS = 15;
115 /** -par default (number of script-checking threads, 0 = auto) */
116 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
117 /** Number of blocks that can be requested at any given time from a single peer. */
118 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
119 /** Timeout in seconds during which a peer must stall block download progress before being disconnected. */
120 static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
121 /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
122  *  less than this number, we reached its tip. Changing this value is a protocol upgrade. */
123 static const unsigned int MAX_HEADERS_RESULTS = 2000; //limit to COINBASE_MATURITY-1
124 /** Maximum depth of blocks we're willing to serve as compact blocks to peers
125  *  when requested. For older blocks, a regular BLOCK response will be sent. */
126 static const int MAX_CMPCTBLOCK_DEPTH = 5;
127 /** Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for. */
128 static const int MAX_BLOCKTXN_DEPTH = 10;
129 /** Size of the "block download window": how far ahead of our current height do we fetch?
130  *  Larger windows tolerate larger download speed differences between peer, but increase the potential
131  *  degree of disordering of blocks on disk (which make reindexing and pruning harder). We'll probably
132  *  want to make this a per-peer adaptive value at some point. */
133 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
134 /** Time to wait (in seconds) between writing blocks/block index to disk. */
135 static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
136 /** Time to wait (in seconds) between flushing chainstate to disk. */
137 static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
138 /** Block download timeout base, expressed in millionths of the block interval (i.e. 10 min) */
139 static const int64_t BLOCK_DOWNLOAD_TIMEOUT_BASE = 1000000;
140 /** Additional block download timeout per parallel downloading peer (i.e. 5 min) */
141 static const int64_t BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 500000;
142 
143 static const int64_t DEFAULT_MAX_TIP_AGE = 12 * 60 * 60; //Changed to 12 hours so that isInitialBlockDownload() is more accurate
144 /** Maximum age of our tip in seconds for us to be considered current for fee estimation */
145 static const int64_t MAX_FEE_ESTIMATION_TIP_AGE = 3 * 60 * 60;
146 
147 static const bool DEFAULT_CHECKPOINTS_ENABLED = true;
148 static const bool DEFAULT_TXINDEX = false;
149 static const bool DEFAULT_ADDRINDEX = false;
150 static const bool DEFAULT_LOGEVENTS = false;
151 static const char* const DEFAULT_BLOCKFILTERINDEX = "0";
152 static const unsigned int DEFAULT_BANSCORE_THRESHOLD = 100;
153 /** Default for -persistmempool */
154 static const bool DEFAULT_PERSIST_MEMPOOL = true;
155 /** Default for using fee filter */
156 static const bool DEFAULT_FEEFILTER = true;
157 
158 /** Maximum number of headers to announce when relaying blocks with headers message.*/
159 static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;
160 
161 /** Maximum number of unconnecting headers announcements before DoS score */
162 static const int MAX_UNCONNECTING_HEADERS = 10;
163 
164 /** Default for -stopatheight */
165 static const int DEFAULT_STOPATHEIGHT = 0;
166 
167 static const uint64_t DEFAULT_GAS_LIMIT_OP_CREATE=2500000;
168 static const uint64_t DEFAULT_GAS_LIMIT_OP_SEND=250000;
169 static const CAmount DEFAULT_GAS_PRICE=0.00000040*COIN;
170 static const CAmount MAX_RPC_GAS_PRICE=0.00000100*COIN;
171 
172 static const size_t MAX_CONTRACT_VOUTS = 1000; // qtum
173 
174 //! -stakingminutxovalue default
175 static const CAmount DEFAULT_STAKING_MIN_UTXO_VALUE = 100 * COIN;
176 
177 //! -forceinitialblocksdownloadmode default
178 static const bool DEFAULT_FORCE_INITIAL_BLOCKS_DOWNLOAD_MODE = false;
179 
180 struct BlockHasher
181 {
182     // this used to call `GetCheapHash()` in uint256, which was later moved; the
183     // cheap hash function simply calls ReadLE64() however, so the end result is
184     // identical
operatorBlockHasher185     size_t operator()(const uint256& hash) const { return ReadLE64(hash.begin()); }
186 };
187 
188 extern RecursiveMutex cs_main;
189 extern CBlockPolicyEstimator feeEstimator;
190 extern CTxMemPool mempool;
191 typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
192 extern Mutex g_best_block_mutex;
193 extern std::condition_variable g_best_block_cv;
194 extern uint256 g_best_block;
195 extern std::atomic_bool fImporting;
196 extern std::atomic_bool fReindex;
197 /** Whether there are dedicated script-checking threads running.
198  * False indicates all script checking is done on the main threadMessageHandler thread.
199  */
200 extern bool g_parallel_script_checks;
201 extern bool fAddressIndex;
202 extern bool fLogEvents;
203 extern bool fRequireStandard;
204 extern bool fCheckBlockIndex;
205 extern bool fCheckpointsEnabled;
206 extern size_t nCoinCacheUsage;
207 /** A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) */
208 extern CFeeRate minRelayTxFee;
209 /** If the tip is older than this (in seconds), the node is considered to be in initial block download. */
210 extern int64_t nMaxTipAge;
211 
212 /** Block hash whose ancestors we will assume to have valid scripts without checking them. */
213 extern uint256 hashAssumeValid;
214 
215 /** Minimum work we will assume exists on some valid chain. */
216 extern arith_uint256 nMinimumChainWork;
217 
218 /** Best header we've seen so far (used for getheaders queries' starting points). */
219 extern CBlockIndex *pindexBestHeader;
220 
221 /** Pruning-related variables and constants */
222 /** True if any block files have ever been pruned. */
223 extern bool fHavePruned;
224 /** True if we're running in -prune mode. */
225 extern bool fPruneMode;
226 /** Number of MiB of block files that we're trying to stay below. */
227 extern uint64_t nPruneTarget;
228 /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ::ChainActive().Tip() will not be pruned. */
229 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
230 /** Minimum blocks required to signal NODE_NETWORK_LIMITED */
231 static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288;
232 
233 static const signed int DEFAULT_CHECKBLOCKS = 6;
234 static const unsigned int DEFAULT_CHECKLEVEL = 3;
235 
236 // Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
237 // At 1MB per block, 288 blocks = 288MB.
238 // Add 15% for Undo data = 331MB
239 // Add 20% for Orphan block rate = 397MB
240 // We want the low water mark after pruning to be at least 397 MB and since we prune in
241 // full block file chunks, we need the high water mark which triggers the prune to be
242 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
243 // Setting the target to >= 550 MiB will make it likely we can respect the target.
244 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
245 
246 int64_t FutureDrift(uint32_t nTime, int nHeight, const Consensus::Params& consensusParams);
247 
248 /**
249  * Process an incoming block. This only returns after the best known valid
250  * block is made active. Note that it does not, however, guarantee that the
251  * specific block passed to it has been checked for validity!
252  *
253  * If you want to *possibly* get feedback on whether pblock is valid, you must
254  * install a CValidationInterface (see validationinterface.h) - this will have
255  * its BlockChecked method called whenever *any* block completes validation.
256  *
257  * Note that we guarantee that either the proof-of-work is valid on pblock, or
258  * (and possibly also) BlockChecked will have been called.
259  *
260  * May not be called in a
261  * validationinterface callback.
262  *
263  * @param[in]   pblock  The block we want to process.
264  * @param[in]   fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers.
265  * @param[out]  fNewBlock A boolean which is set to indicate if the block was first received via this call
266  * @returns     If the block was processed, independently of block validity
267  */
268 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool* fNewBlock) LOCKS_EXCLUDED(cs_main);
269 
270 /**
271  * Process incoming block headers.
272  *
273  * May not be called in a
274  * validationinterface callback.
275  *
276  * @param[in]  block The block headers themselves
277  * @param[out] state This may be set to an Error state if any error occurred processing them
278  * @param[in]  chainparams The params for the chain we want to connect to
279  * @param[out] ppindex If set, the pointer will be set to point to the last new block index object for the given headers
280  */
281 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, BlockValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex = nullptr,  const CBlockIndex** pindexFirst=nullptr) LOCKS_EXCLUDED(cs_main);
282 
283 /** Open a block file (blk?????.dat) */
284 FILE* OpenBlockFile(const FlatFilePos &pos, bool fReadOnly = false);
285 /** Translation to a filesystem path */
286 fs::path GetBlockPosFilename(const FlatFilePos &pos);
287 /** Import blocks from an external file */
288 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, FlatFilePos *dbp = nullptr);
289 /** Ensures we have a genesis block in the block tree, possibly writing one to disk. */
290 bool LoadGenesisBlock(const CChainParams& chainparams);
291 /** Load the block tree and coins database from disk,
292  * initializing state if we're running with -reindex. */
293 bool LoadBlockIndex(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
294 /** Unload database information */
295 void UnloadBlockIndex();
296 /** Run an instance of the script checking thread */
297 void ThreadScriptCheck(int worker_num);
298 /** Retrieve a transaction (from memory pool, or from disk, if possible) */
299 bool GetTransaction(const uint256& hash, CTransactionRef& tx, const Consensus::Params& params, uint256& hashBlock, const CBlockIndex* const blockIndex = nullptr, bool fAllowSlow = false);
300 /**
301  * Find the best known block, and make it the tip of the block chain
302  *
303  * May not be called with cs_main held. May not be called in a
304  * validationinterface callback.
305  */
306 bool ActivateBestChain(BlockValidationState& state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock = std::shared_ptr<const CBlock>());
307 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
308 
309 /** Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip). */
310 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
311 
312 /** Calculate the amount of disk space the block & undo files currently use */
313 uint64_t CalculateCurrentUsage();
314 
315 /**
316  *  Mark one block file as pruned.
317  */
318 void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
319 
320 /**
321  *  Actually unlink the specified files
322  */
323 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune);
324 
325 /** Prune block files up to a given height */
326 void PruneBlockFilesManual(int nManualPruneHeight);
327 /** Check if the transaction is confirmed in N previous blocks */
328 bool IsConfirmedInNPrevBlocks(const CDiskTxPos& txindex, const CBlockIndex* pindexFrom, int nMaxDepth, int& nActualDepth);
329 
330 
331 /** (try to) add transaction to memory pool
332  * plTxnReplaced will be appended to with all transactions replaced from mempool **/
333 bool AcceptToMemoryPool(CTxMemPool& pool, TxValidationState &state, const CTransactionRef &tx,
334                         std::list<CTransactionRef>* plTxnReplaced,
335                         bool bypass_limits, const CAmount nAbsurdFee, bool test_accept=false, bool rawTx = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
336 
337 /** Get the BIP9 state for a given deployment at the current tip. */
338 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos);
339 
340 /** Get the numerical statistics for the BIP9 state for a given deployment at the current tip. */
341 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos);
342 
343 /** Get the block height at which the BIP9 deployment switched into the state for the block building on the current tip. */
344 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos);
345 
346 
347 /** Apply the effects of this transaction on the UTXO set represented by view */
348 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
349 
350 /** Transaction validation functions */
351 
352 /**
353  * Check if transaction will be final in the next block to be created.
354  *
355  * Calls IsFinalTx() with current block height and appropriate block time.
356  *
357  * See consensus/consensus.h for flag definitions.
358  */
359 bool CheckFinalTx(const CTransaction &tx, int flags = -1) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
360 
361 /**
362  * Test whether the LockPoints height and time are still valid on the current chain
363  */
364 bool TestLockPointValidity(const LockPoints* lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
365 
366 /**
367  * Check if transaction will be BIP 68 final in the next block to be created.
368  *
369  * Simulates calling SequenceLocks() with data from the tip of the current active chain.
370  * Optionally stores in LockPoints the resulting height and time calculated and the hash
371  * of the block needed for calculation or skips the calculation and uses the LockPoints
372  * passed in for evaluation.
373  * The LockPoints should not be considered valid if CheckSequenceLocks returns false.
374  *
375  * See consensus/consensus.h for flag definitions.
376  */
377 bool CheckSequenceLocks(const CTxMemPool& pool, const CTransaction& tx, int flags, LockPoints* lp = nullptr, bool useExistingLockPoints = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
378 
379 /**
380  * Closure representing one script verification
381  * Note that this stores references to the spending transaction
382  */
383 class CScriptCheck
384 {
385 private:
386     CTxOut m_tx_out;
387     const CTransaction *ptxTo;
388     unsigned int nIn;
389     unsigned int nFlags;
390     bool cacheStore;
391     ScriptError error;
392     PrecomputedTransactionData *txdata;
393     int nOut;
394 
395 public:
CScriptCheck()396     CScriptCheck(): ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR), nOut(-1) {}
CScriptCheck(const CTxOut & outIn,const CTransaction & txToIn,unsigned int nInIn,unsigned int nFlagsIn,bool cacheIn,PrecomputedTransactionData * txdataIn)397     CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
398         m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn), nOut(-1) { }
CScriptCheck(const CTransaction & txToIn,int nOutIn,unsigned int nFlagsIn,bool cacheIn,PrecomputedTransactionData * txdataIn)399     CScriptCheck(const CTransaction& txToIn, int nOutIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
400         ptxTo(&txToIn), nIn(0), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn), nOut(nOutIn){ }
401 
402     bool operator()();
403 
swap(CScriptCheck & check)404     void swap(CScriptCheck &check) {
405         std::swap(ptxTo, check.ptxTo);
406         std::swap(m_tx_out, check.m_tx_out);
407         std::swap(nIn, check.nIn);
408         std::swap(nFlags, check.nFlags);
409         std::swap(cacheStore, check.cacheStore);
410         std::swap(error, check.error);
411         std::swap(txdata, check.txdata);
412         std::swap(nOut, check.nOut);
413     }
414 
GetScriptError()415     ScriptError GetScriptError() const { return error; }
416 
checkOutput()417     bool checkOutput() const { return nOut > -1; }
418 };
419 
420 /** Initializes the script-execution cache */
421 void InitScriptExecutionCache();
422 
423 ///////////////////////////////////////////////////////////////// // qtum
424 bool GetAddressIndex(uint256 addressHash, int type,
425                      std::vector<std::pair<CAddressIndexKey, CAmount> > &addressIndex,
426                      int start = 0, int end = 0);
427 
428 bool GetSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value);
429 
430 bool GetAddressUnspent(uint256 addressHash, int type,
431                        std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > &unspentOutputs);
432 
433 bool GetTimestampIndex(const unsigned int &high, const unsigned int &low, const bool fActiveOnly, std::vector<std::pair<uint256, unsigned int> > &hashes);
434 
435 bool GetAddressWeight(uint256 addressHash, int type, const std::map<COutPoint, uint32_t>& immatureStakes, int32_t nHeight, uint64_t& nWeight);
436 
437 std::map<COutPoint, uint32_t> GetImmatureStakes();
438 /////////////////////////////////////////////////////////////////
439 
440 /** Functions for disk access for blocks */
441 //Template function that read the whole block or the header only depending on the type (CBlock or CBlockHeader)
442 template <typename Block>
443 bool ReadBlockFromDisk(Block& block, const FlatFilePos& pos, const Consensus::Params& consensusParams);
444 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams);
445 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatFilePos& pos, const CMessageHeader::MessageStartChars& message_start);
446 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CBlockIndex* pindex, const CMessageHeader::MessageStartChars& message_start);
447 
448 bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex* pindex);
449 
450 bool CheckIndexProof(const CBlockIndex& block, const Consensus::Params& consensusParams);
451 
452 /** Functions for validating blocks and updating the block tree */
453 
454 /** Context-independent validity checks */
455 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true, bool fCheckSig=true);
456 bool GetBlockPublicKey(const CBlock& block, std::vector<unsigned char>& vchPubKey);
457 bool GetBlockDelegation(const CBlock& block, const uint160& staker, uint160& address, uint8_t& fee, CCoinsViewCache& view);
458 bool SignBlock(std::shared_ptr<CBlock> pblock, CWallet& wallet, const CAmount& nTotalFees, uint32_t nTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoins, std::vector<COutPoint>& setSelectedCoins, std::vector<COutPoint>& setDelegateCoins, bool selectedOnly = false, bool tryOnly = false);
459 bool CheckCanonicalBlockSignature(const CBlockHeader* pblock);
460 
461 /** Check a block is completely valid from start to finish (only works on top of our current best block) */
462 bool TestBlockValidity(BlockValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
463 
464 /** Check whether witness commitments are required for a block, and whether to enforce NULLDUMMY (BIP 147) rules.
465  *  Note that transaction witness validation rules are always enforced when P2SH is enforced. */
466 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params);
467 
468 /** When there are blocks in the active chain with missing data, rewind the chainstate and remove them from the block index */
469 bool RewindBlockIndex(const CChainParams& params) LOCKS_EXCLUDED(cs_main);
470 
471 /** Compute at which vout of the block's coinbase transaction the witness commitment occurs, or -1 if not found */
472 int GetWitnessCommitmentIndex(const CBlock& block);
473 
474 /** Update uncommitted block structures (currently: only the witness reserved value). This is safe for submitted blocks. */
475 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
476 
477 /** Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks). */
478 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams, bool fProofOfStake=false);
479 
480 /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
481 class CVerifyDB {
482 public:
483     CVerifyDB();
484     ~CVerifyDB();
485     bool VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
486 };
487 
488 CBlockIndex* LookupBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
489 
490 extern std::unique_ptr<StorageResults> pstorageresult;
491 
492 bool CheckReward(const CBlock& block, BlockValidationState& state, int nHeight, const Consensus::Params& consensusParams, CAmount nFees, CAmount gasRefunds, CAmount nActualStakeReward, const std::vector<CTxOut>& vouts, CAmount nValueCoinPrev, bool delegateOutputExist);
493 
494 bool RemoveStateBlockIndex(CBlockIndex *pindex);
495 
496 //////////////////////////////////////////////////////// qtum
497 bool GetSpentCoinFromBlock(const CBlockIndex* pindex, COutPoint prevout, Coin* coin);
498 
499 bool GetSpentCoinFromMainChain(const CBlockIndex* pforkPrev, COutPoint prevoutStake, Coin* coin);
500 
501 unsigned int GetContractScriptFlags(int nHeight, const Consensus::Params& consensusparams);
502 
503 std::vector<ResultExecute> CallContract(const dev::Address& addrContract, std::vector<unsigned char> opcode, const dev::Address& sender = dev::Address(), uint64_t gasLimit=0, CAmount nAmount=0);
504 
505 bool CheckOpSender(const CTransaction& tx, const CChainParams& chainparams, int nHeight);
506 
507 bool CheckSenderScript(const CCoinsViewCache& view, const CTransaction& tx);
508 
509 bool CheckMinGasPrice(std::vector<EthTransactionParams>& etps, const uint64_t& minGasPrice);
510 
511 void writeVMlog(const std::vector<ResultExecute>& res, const CTransaction& tx = CTransaction(), const CBlock& block = CBlock());
512 
513 std::string exceptedMessage(const dev::eth::TransactionException& excepted, const dev::bytes& output);
514 
515 struct EthTransactionParams{
516     VersionVM version;
517     dev::u256 gasLimit;
518     dev::u256 gasPrice;
519     valtype code;
520     dev::Address receiveAddress;
521 
522     bool operator!=(EthTransactionParams etp){
523         if(this->version.toRaw() != etp.version.toRaw() || this->gasLimit != etp.gasLimit ||
524         this->gasPrice != etp.gasPrice || this->code != etp.code ||
525         this->receiveAddress != etp.receiveAddress)
526             return true;
527         return false;
528     }
529 };
530 
531 struct ByteCodeExecResult{
532     uint64_t usedGas = 0;
533     CAmount refundSender = 0;
534     std::vector<CTxOut> refundOutputs;
535     std::vector<CTransaction> valueTransfers;
536 };
537 
538 class QtumTxConverter{
539 
540 public:
541 
txBit(tx)542     QtumTxConverter(CTransaction tx, CCoinsViewCache* v = NULL, const std::vector<CTransactionRef>* blockTxs = NULL, unsigned int flags = SCRIPT_EXEC_BYTE_CODE) : txBit(tx), view(v), blockTransactions(blockTxs), sender(false), nFlags(flags){}
543 
544     bool extractionQtumTransactions(ExtractQtumTX& qtumTx);
545 
546 private:
547 
548     bool receiveStack(const CScript& scriptPubKey);
549 
550     bool parseEthTXParams(EthTransactionParams& params);
551 
552     QtumTransaction createEthTX(const EthTransactionParams& etp, const uint32_t nOut);
553 
554     size_t correctedStackSize(size_t size);
555 
556     const CTransaction txBit;
557     const CCoinsViewCache* view;
558     std::vector<valtype> stack;
559     opcodetype opcode;
560     const std::vector<CTransactionRef> *blockTransactions;
561     bool sender;
562     dev::Address refundSender;
563     unsigned int nFlags;
564 };
565 
566 class LastHashes: public dev::eth::LastBlockHashesFace
567 {
568 public:
569     explicit LastHashes();
570 
571     void set(CBlockIndex const* tip);
572 
573     dev::h256s precedingHashes(dev::h256 const&) const;
574 
575     void clear();
576 
577 private:
578     dev::h256s m_lastHashes;
579 };
580 
581 class ByteCodeExec {
582 
583 public:
584 
ByteCodeExec(const CBlock & _block,std::vector<QtumTransaction> _txs,const uint64_t _blockGasLimit,CBlockIndex * _pindex)585     ByteCodeExec(const CBlock& _block, std::vector<QtumTransaction> _txs, const uint64_t _blockGasLimit, CBlockIndex* _pindex) : txs(_txs), block(_block), blockGasLimit(_blockGasLimit), pindex(_pindex) {}
586 
587     bool performByteCode(dev::eth::Permanence type = dev::eth::Permanence::Committed);
588 
589     bool processingResults(ByteCodeExecResult& result);
590 
getResult()591     std::vector<ResultExecute>& getResult(){ return result; }
592 
593 private:
594 
595     dev::eth::EnvInfo BuildEVMEnvironment();
596 
597     dev::Address EthAddrFromScript(const CScript& scriptIn);
598 
599     std::vector<QtumTransaction> txs;
600 
601     std::vector<ResultExecute> result;
602 
603     const CBlock& block;
604 
605     const uint64_t blockGasLimit;
606 
607     CBlockIndex* pindex;
608 
609     LastHashes lastHashes;
610 };
611 
612 /** Find the last common block between the parameter chain and a locator. */
613 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
614 
615 enum DisconnectResult
616 {
617     DISCONNECT_OK,      // All good.
618     DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
619     DISCONNECT_FAILED   // Something else went wrong.
620 };
621 
622 class ConnectTrace;
623 
624 /** @see CChainState::FlushStateToDisk */
625 enum class FlushStateMode {
626     NONE,
627     IF_NEEDED,
628     PERIODIC,
629     ALWAYS
630 };
631 
632 struct CBlockIndexWorkComparator
633 {
634     bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const;
635 };
636 
637 /**
638  * Maintains a tree of blocks (stored in `m_block_index`) which is consulted
639  * to determine where the most-work tip is.
640  *
641  * This data is used mostly in `CChainState` - information about, e.g.,
642  * candidate tips is not maintained here.
643  */
644 class BlockManager {
645 public:
646     BlockMap m_block_index GUARDED_BY(cs_main);
647 
648     /** In order to efficiently track invalidity of headers, we keep the set of
649       * blocks which we tried to connect and found to be invalid here (ie which
650       * were set to BLOCK_FAILED_VALID since the last restart). We can then
651       * walk this set and check if a new header is a descendant of something in
652       * this set, preventing us from having to walk m_block_index when we try
653       * to connect a bad block and fail.
654       *
655       * While this is more complicated than marking everything which descends
656       * from an invalid block as invalid at the time we discover it to be
657       * invalid, doing so would require walking all of m_block_index to find all
658       * descendants. Since this case should be very rare, keeping track of all
659       * BLOCK_FAILED_VALID blocks in a set should be just fine and work just as
660       * well.
661       *
662       * Because we already walk m_block_index in height-order at startup, we go
663       * ahead and mark descendants of invalid blocks as FAILED_CHILD at that time,
664       * instead of putting things in this set.
665       */
666     std::set<CBlockIndex*> m_failed_blocks;
667 
668     /**
669      * All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
670      * Pruned nodes may have entries where B is missing data.
671      */
672     std::multimap<CBlockIndex*, CBlockIndex*> m_blocks_unlinked;
673 
674     /**
675      * Load the blocktree off disk and into memory. Populate certain metadata
676      * per index entry (nStatus, nChainWork, nTimeMax, etc.) as well as peripheral
677      * collections like setDirtyBlockIndex.
678      *
679      * @param[out] block_index_candidates  Fill this set with any valid blocks for
680      *                                     which we've downloaded all transactions.
681      */
682     bool LoadBlockIndex(
683         const Consensus::Params& consensus_params,
684         CBlockTreeDB& blocktree,
685         std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
686         EXCLUSIVE_LOCKS_REQUIRED(cs_main);
687 
688     /** Clear all data members. */
689     void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
690 
691     CBlockIndex* AddToBlockIndex(const CBlockHeader& block) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
692     /** Create a new block index entry for a given block hash */
693     CBlockIndex* InsertBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
694 
695     /**
696      * If a block header hasn't already been seen, call CheckBlockHeader on it, ensure
697      * that it doesn't descend from an invalid block, and then add it to m_block_index.
698      */
699     bool AcceptBlockHeader(
700         const CBlockHeader& block,
701         BlockValidationState& state,
702         const CChainParams& chainparams,
703         CBlockIndex** ppindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
704 };
705 
706 /**
707  * A convenience class for constructing the CCoinsView* hierarchy used
708  * to facilitate access to the UTXO set.
709  *
710  * This class consists of an arrangement of layered CCoinsView objects,
711  * preferring to store and retrieve coins in memory via `m_cacheview` but
712  * ultimately falling back on cache misses to the canonical store of UTXOs on
713  * disk, `m_dbview`.
714  */
715 class CoinsViews {
716 
717 public:
718     //! The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
719     //! All unspent coins reside in this store.
720     CCoinsViewDB m_dbview GUARDED_BY(cs_main);
721 
722     //! This view wraps access to the leveldb instance and handles read errors gracefully.
723     CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main);
724 
725     //! This is the top layer of the cache hierarchy - it keeps as many coins in memory as
726     //! can fit per the dbcache setting.
727     std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
728 
729     //! This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it
730     //! *does not* create a CCoinsViewCache instance by default. This is done separately because the
731     //! presence of the cache has implications on whether or not we're allowed to flush the cache's
732     //! state to disk, which should not be done until the health of the database is verified.
733     //!
734     //! All arguments forwarded onto CCoinsViewDB.
735     CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe);
736 
737     //! Initialize the CCoinsViewCache member.
738     void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
739 };
740 
741 enum class CoinsCacheSizeState
742 {
743     //! The coins cache is in immediate need of a flush.
744     CRITICAL = 2,
745     //! The cache is at >= 90% capacity.
746     LARGE = 1,
747     OK = 0
748 };
749 
750 /**
751  * CChainState stores and provides an API to update our local knowledge of the
752  * current best chain.
753  *
754  * Eventually, the API here is targeted at being exposed externally as a
755  * consumable libconsensus library, so any functions added must only call
756  * other class member functions, pure functions in other parts of the consensus
757  * library, callbacks via the validation interface, or read/write-to-disk
758  * functions (eventually this will also be via callbacks).
759  *
760  * Anything that is contingent on the current tip of the chain is stored here,
761  * whereas block information and metadata independent of the current tip is
762  * kept in `BlockMetadataManager`.
763  */
764 class CChainState {
765 private:
766 
767     /**
768      * Every received block is assigned a unique and increasing identifier, so we
769      * know which one to give priority in case of a fork.
770      */
771     RecursiveMutex cs_nBlockSequenceId;
772     /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
773     int32_t nBlockSequenceId = 1;
774     /** Decreasing counter (used by subsequent preciousblock calls). */
775     int32_t nBlockReverseSequenceId = -1;
776     /** chainwork for the last block that preciousblock has been applied to. */
777     arith_uint256 nLastPreciousChainwork = 0;
778 
779     /**
780      * the ChainState CriticalSection
781      * A lock that must be held when modifying this ChainState - held in ActivateBestChain()
782      */
783     RecursiveMutex m_cs_chainstate;
784 
785     /**
786      * Whether this chainstate is undergoing initial block download.
787      *
788      * Mutable because we need to be able to mark IsInitialBlockDownload()
789      * const, which latches this for caching purposes.
790      */
791     mutable std::atomic<bool> m_cached_finished_ibd{false};
792 
793     //! Reference to a BlockManager instance which itself is shared across all
794     //! CChainState instances. Keeping a local reference allows us to test more
795     //! easily as opposed to referencing a global.
796     BlockManager& m_blockman;
797 
798     //! Manages the UTXO set, which is a reflection of the contents of `m_chain`.
799     std::unique_ptr<CoinsViews> m_coins_views;
800 
801 public:
CChainState(BlockManager & blockman)802     CChainState(BlockManager& blockman) : m_blockman(blockman) {}
803     CChainState();
804 
805     /**
806      * Initialize the CoinsViews UTXO set database management data structures. The in-memory
807      * cache is initialized separately.
808      *
809      * All parameters forwarded to CoinsViews.
810      */
811     void InitCoinsDB(
812         size_t cache_size_bytes,
813         bool in_memory,
814         bool should_wipe,
815         std::string leveldb_name = "chainstate");
816 
817     //! Initialize the in-memory coins cache (to be done after the health of the on-disk database
818     //! is verified).
819     void InitCoinsCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
820 
821     //! @returns whether or not the CoinsViews object has been fully initialized and we can
822     //!          safely flush this object to disk.
CanFlushToDisk()823     bool CanFlushToDisk() EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
824         return m_coins_views && m_coins_views->m_cacheview;
825     }
826 
827     //! The current chain of blockheaders we consult and build on.
828     //! @see CChain, CBlockIndex.
829     CChain m_chain;
830 
831     /**
832      * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
833      * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
834      * missing the data for the block.
835      */
836     std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
837 
838     /**
839      * The set of all seen COutPoint entries for proof of stake.
840      */
841     std::set<std::pair<COutPoint, unsigned int>> setStakeSeen;
842 
843     //! @returns A reference to the in-memory cache of the UTXO set.
CoinsTip()844     CCoinsViewCache& CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
845     {
846         assert(m_coins_views->m_cacheview);
847         return *m_coins_views->m_cacheview.get();
848     }
849 
850     //! @returns A reference to the on-disk UTXO set database.
CoinsDB()851     CCoinsViewDB& CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
852     {
853         return m_coins_views->m_dbview;
854     }
855 
856     //! @returns A reference to a wrapped view of the in-memory UTXO set that
857     //!     handles disk read errors gracefully.
CoinsErrorCatcher()858     CCoinsViewErrorCatcher& CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
859     {
860         return m_coins_views->m_catcherview;
861     }
862 
863     //! Destructs all objects related to accessing the UTXO set.
ResetCoinsViews()864     void ResetCoinsViews() { m_coins_views.reset(); }
865 
866     /**
867      * Update the on-disk chain state.
868      * The caches and indexes are flushed depending on the mode we're called with
869      * if they're too large, if it's been a while since the last write,
870      * or always and in all cases if we're in prune mode and are deleting files.
871      *
872      * If FlushStateMode::NONE is used, then FlushStateToDisk(...) won't do anything
873      * besides checking if we need to prune.
874      *
875      * @returns true unless a system error occurred
876      */
877     bool FlushStateToDisk(
878         const CChainParams& chainparams,
879         BlockValidationState &state,
880         FlushStateMode mode,
881         int nManualPruneHeight = 0);
882 
883     //! Unconditionally flush all changes to disk.
884     void ForceFlushStateToDisk();
885 
886     //! Prune blockfiles from the disk if necessary and then flush chainstate changes
887     //! if we pruned.
888     void PruneAndFlush();
889 
890     /**
891      * Make the best chain active, in multiple steps. The result is either failure
892      * or an activated best chain. pblock is either nullptr or a pointer to a block
893      * that is already loaded (to avoid loading it again from disk).
894      *
895      * ActivateBestChain is split into steps (see ActivateBestChainStep) so that
896      * we avoid holding cs_main for an extended period of time; the length of this
897      * call may be quite long during reindexing or a substantial reorg.
898      *
899      * May not be called with cs_main held. May not be called in a
900      * validationinterface callback.
901      *
902      * @returns true unless a system error occurred
903      */
904     bool ActivateBestChain(
905         BlockValidationState& state,
906         const CChainParams& chainparams,
907         std::shared_ptr<const CBlock> pblock) LOCKS_EXCLUDED(cs_main);
908 
909     bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
910 
911     // Block (dis)connection on a given view:
912     DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean);
913     bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
914                       CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
915     bool UpdateHashProof(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, CBlockIndex* pindex, CCoinsViewCache& view);
916 
917     // Apply the effects of a block disconnection on the UTXO set.
918     bool DisconnectTip(BlockValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, ::mempool.cs);
919 
920     // Manual block validity manipulation:
921     bool PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
922     bool InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
923     void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
924 
925     /** Replay blocks that aren't fully applied to the database. */
926     bool ReplayBlocks(const CChainParams& params);
927     bool RewindBlockIndex(const CChainParams& params) LOCKS_EXCLUDED(cs_main);
928     bool LoadGenesisBlock(const CChainParams& chainparams);
929 
930     void PruneBlockIndexCandidates();
931 
932     void UnloadBlockIndex();
933 
934     bool RemoveBlockIndex(CBlockIndex *pindex);
935 
936     /** Check whether we are doing an initial block download (synchronizing from disk or network) */
937     bool IsInitialBlockDownload() const;
938 
939     /**
940      * Make various assertions about the state of the block index.
941      *
942      * By default this only executes fully when using the Regtest chain; see: fCheckBlockIndex.
943      */
944     void CheckBlockIndex(const Consensus::Params& consensusParams);
945 
946     /** Update the chain tip based on database information, i.e. CoinsTip()'s best block. */
947     bool LoadChainTip(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
948 
949     //! Dictates whether we need to flush the cache to disk or not.
950     //!
951     //! @return the state of the size of the coins cache.
952     CoinsCacheSizeState GetCoinsCacheSizeState(const CTxMemPool& tx_pool)
953         EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
954 
955     CoinsCacheSizeState GetCoinsCacheSizeState(
956         const CTxMemPool& tx_pool,
957         size_t max_coins_cache_size_bytes,
958         size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
959 
960 private:
961     bool ActivateBestChainStep(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main, ::mempool.cs);
962     bool ConnectTip(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions& disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, ::mempool.cs);
963 
964     void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
965     CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
966     void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos, const Consensus::Params& consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
967 
968     bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
969 
970     //! Mark a block as not having block data
971     void EraseBlockData(CBlockIndex* index) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
972 };
973 
974 /** Mark a block as precious and reorganize.
975  *
976  * May not be called in a
977  * validationinterface callback.
978  */
979 bool PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main);
980 
981 /** Mark a block as invalid. */
982 bool InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
983 
984 /** Remove invalidity status from a block and its descendants. */
985 void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
986 
987 /** @returns the most-work valid chainstate. */
988 CChainState& ChainstateActive();
989 
990 /** @returns the most-work chain. */
991 CChain& ChainActive();
992 
993 /** @returns the global block index map. */
994 BlockMap& BlockIndex();
995 
996 // Most often ::ChainstateActive() should be used instead of this, but some code
997 // may not be able to assume that this has been initialized yet and so must use it
998 // directly, e.g. init.cpp.
999 extern std::unique_ptr<CChainState> g_chainstate;
1000 
1001 /** Global variable that points to the active block tree (protected by cs_main) */
1002 extern std::unique_ptr<CBlockTreeDB> pblocktree;
1003 
1004 /**
1005  * Return the spend height, which is one more than the inputs.GetBestBlock().
1006  * While checking, GetBestBlock() refers to the parent block. (protected by cs_main)
1007  * This is also true for mempool checks.
1008  */
1009 int GetSpendHeight(const CCoinsViewCache& inputs);
1010 
1011 extern VersionBitsCache versionbitscache;
1012 
1013 /**
1014  * Determine what nVersion a new block should use.
1015  */
1016 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params);
1017 
1018 /** Get block file info entry for one block file */
1019 CBlockFileInfo* GetBlockFileInfo(size_t n);
1020 
1021 /** Dump the mempool to disk. */
1022 bool DumpMempool(const CTxMemPool& pool);
1023 
1024 /** Load the mempool from disk. */
1025 bool LoadMempool(CTxMemPool& pool);
1026 
1027 //! Check whether the block associated with this index entry is pruned or not.
IsBlockPruned(const CBlockIndex * pblockindex)1028 inline bool IsBlockPruned(const CBlockIndex* pblockindex)
1029 {
1030     return (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0);
1031 }
1032 
1033 //! Get transaction gas fee
1034 CAmount GetTxGasFee(const CMutableTransaction& tx);
1035 
1036 #endif // BITCOIN_VALIDATION_H
1037