LCOV - code coverage report
Current view: top level - src - validation.h (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 50 50 100.0 %
Date: 2021-06-29 14:35:33 Functions: 23 23 100.0 %
Legend: Modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed

Not modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed
Branches: 3 4 75.0 %

           Branch data     Line data    Source code
#       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 <attributes.h>
#      15                 :            : #include <coins.h>
#      16                 :            : #include <consensus/validation.h>
#      17                 :            : #include <crypto/common.h> // for ReadLE64
#      18                 :            : #include <fs.h>
#      19                 :            : #include <node/utxo_snapshot.h>
#      20                 :            : #include <policy/feerate.h>
#      21                 :            : #include <policy/packages.h>
#      22                 :            : #include <protocol.h> // For CMessageHeader::MessageStartChars
#      23                 :            : #include <script/script_error.h>
#      24                 :            : #include <sync.h>
#      25                 :            : #include <txmempool.h> // For CTxMemPool::cs
#      26                 :            : #include <txdb.h>
#      27                 :            : #include <versionbits.h>
#      28                 :            : #include <serialize.h>
#      29                 :            : #include <util/check.h>
#      30                 :            : #include <util/hasher.h>
#      31                 :            : #include <util/translation.h>
#      32                 :            : 
#      33                 :            : #include <atomic>
#      34                 :            : #include <map>
#      35                 :            : #include <memory>
#      36                 :            : #include <optional>
#      37                 :            : #include <set>
#      38                 :            : #include <stdint.h>
#      39                 :            : #include <string>
#      40                 :            : #include <thread>
#      41                 :            : #include <utility>
#      42                 :            : #include <vector>
#      43                 :            : 
#      44                 :            : class CChainState;
#      45                 :            : class BlockValidationState;
#      46                 :            : class CBlockIndex;
#      47                 :            : class CBlockTreeDB;
#      48                 :            : class CBlockUndo;
#      49                 :            : class CChainParams;
#      50                 :            : struct CCheckpointData;
#      51                 :            : class CInv;
#      52                 :            : class CConnman;
#      53                 :            : class CScriptCheck;
#      54                 :            : class CTxMemPool;
#      55                 :            : class ChainstateManager;
#      56                 :            : struct ChainTxData;
#      57                 :            : 
#      58                 :            : struct DisconnectedBlockTransactions;
#      59                 :            : struct PrecomputedTransactionData;
#      60                 :            : struct LockPoints;
#      61                 :            : struct AssumeutxoData;
#      62                 :            : 
#      63                 :            : /** Default for -minrelaytxfee, minimum relay fee for transactions */
#      64                 :            : static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 1000;
#      65                 :            : /** Default for -limitancestorcount, max number of in-mempool ancestors */
#      66                 :            : static const unsigned int DEFAULT_ANCESTOR_LIMIT = 25;
#      67                 :            : /** Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors */
#      68                 :            : static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT = 101;
#      69                 :            : /** Default for -limitdescendantcount, max number of in-mempool descendants */
#      70                 :            : static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25;
#      71                 :            : /** Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants */
#      72                 :            : static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101;
#      73                 :            : /** Default for -mempoolexpiry, expiration time for mempool transactions in hours */
#      74                 :            : static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 336;
#      75                 :            : /** Maximum number of dedicated script-checking threads allowed */
#      76                 :            : static const int MAX_SCRIPTCHECK_THREADS = 15;
#      77                 :            : /** -par default (number of script-checking threads, 0 = auto) */
#      78                 :            : static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
#      79                 :            : static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
#      80                 :            : static const bool DEFAULT_CHECKPOINTS_ENABLED = true;
#      81                 :            : static const bool DEFAULT_TXINDEX = false;
#      82                 :            : static constexpr bool DEFAULT_COINSTATSINDEX{false};
#      83                 :            : static const char* const DEFAULT_BLOCKFILTERINDEX = "0";
#      84                 :            : /** Default for -persistmempool */
#      85                 :            : static const bool DEFAULT_PERSIST_MEMPOOL = true;
#      86                 :            : /** Default for -stopatheight */
#      87                 :            : static const int DEFAULT_STOPATHEIGHT = 0;
#      88                 :            : /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ::ChainActive().Tip() will not be pruned. */
#      89                 :            : static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
#      90                 :            : static const signed int DEFAULT_CHECKBLOCKS = 6;
#      91                 :            : static const unsigned int DEFAULT_CHECKLEVEL = 3;
#      92                 :            : // Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
#      93                 :            : // At 1MB per block, 288 blocks = 288MB.
#      94                 :            : // Add 15% for Undo data = 331MB
#      95                 :            : // Add 20% for Orphan block rate = 397MB
#      96                 :            : // We want the low water mark after pruning to be at least 397 MB and since we prune in
#      97                 :            : // full block file chunks, we need the high water mark which triggers the prune to be
#      98                 :            : // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
#      99                 :            : // Setting the target to >= 550 MiB will make it likely we can respect the target.
#     100                 :            : static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
#     101                 :            : 
#     102                 :            : /** Current sync state passed to tip changed callbacks. */
#     103                 :            : enum class SynchronizationState {
#     104                 :            :     INIT_REINDEX,
#     105                 :            :     INIT_DOWNLOAD,
#     106                 :            :     POST_INIT
#     107                 :            : };
#     108                 :            : 
#     109                 :            : extern RecursiveMutex cs_main;
#     110                 :            : typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
#     111                 :            : extern Mutex g_best_block_mutex;
#     112                 :            : extern std::condition_variable g_best_block_cv;
#     113                 :            : extern uint256 g_best_block;
#     114                 :            : /** Whether there are dedicated script-checking threads running.
#     115                 :            :  * False indicates all script checking is done on the main threadMessageHandler thread.
#     116                 :            :  */
#     117                 :            : extern bool g_parallel_script_checks;
#     118                 :            : extern bool fRequireStandard;
#     119                 :            : extern bool fCheckBlockIndex;
#     120                 :            : extern bool fCheckpointsEnabled;
#     121                 :            : /** A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) */
#     122                 :            : extern CFeeRate minRelayTxFee;
#     123                 :            : /** If the tip is older than this (in seconds), the node is considered to be in initial block download. */
#     124                 :            : extern int64_t nMaxTipAge;
#     125                 :            : 
#     126                 :            : /** Block hash whose ancestors we will assume to have valid scripts without checking them. */
#     127                 :            : extern uint256 hashAssumeValid;
#     128                 :            : 
#     129                 :            : /** Minimum work we will assume exists on some valid chain. */
#     130                 :            : extern arith_uint256 nMinimumChainWork;
#     131                 :            : 
#     132                 :            : /** Best header we've seen so far (used for getheaders queries' starting points). */
#     133                 :            : extern CBlockIndex *pindexBestHeader;
#     134                 :            : 
#     135                 :            : /** Documentation for argument 'checklevel'. */
#     136                 :            : extern const std::vector<std::string> CHECKLEVEL_DOC;
#     137                 :            : 
#     138                 :            : /** Unload database information */
#     139                 :            : void UnloadBlockIndex(CTxMemPool* mempool, ChainstateManager& chainman);
#     140                 :            : /** Run instances of script checking worker threads */
#     141                 :            : void StartScriptCheckWorkerThreads(int threads_num);
#     142                 :            : /** Stop all of the script checking worker threads */
#     143                 :            : void StopScriptCheckWorkerThreads();
#     144                 :            : /**
#     145                 :            :  * Return transaction from the block at block_index.
#     146                 :            :  * If block_index is not provided, fall back to mempool.
#     147                 :            :  * If mempool is not provided or the tx couldn't be found in mempool, fall back to g_txindex.
#     148                 :            :  *
#     149                 :            :  * @param[in]  block_index     The block to read from disk, or nullptr
#     150                 :            :  * @param[in]  mempool         If block_index is not provided, look in the mempool, if provided
#     151                 :            :  * @param[in]  hash            The txid
#     152                 :            :  * @param[in]  consensusParams The params
#     153                 :            :  * @param[out] hashBlock       The hash of block_index, if the tx was found via block_index
#     154                 :            :  * @returns                    The tx if found, otherwise nullptr
#     155                 :            :  */
#     156                 :            : CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const uint256& hash, const Consensus::Params& consensusParams, uint256& hashBlock);
#     157                 :            : CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
#     158                 :            : 
#     159                 :            : bool AbortNode(BlockValidationState& state, const std::string& strMessage, const bilingual_str& userMessage = bilingual_str{});
#     160                 :            : 
#     161                 :            : /** Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip). */
#     162                 :            : double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
#     163                 :            : 
#     164                 :            : /** Prune block files up to a given height */
#     165                 :            : void PruneBlockFilesManual(CChainState& active_chainstate, int nManualPruneHeight);
#     166                 :            : 
#     167                 :            : /**
#     168                 :            : * Validation result for a single transaction mempool acceptance.
#     169                 :            : */
#     170                 :            : struct MempoolAcceptResult {
#     171                 :            :     /** Used to indicate the results of mempool validation. */
#     172                 :            :     enum class ResultType {
#     173                 :            :         VALID, //!> Fully validated, valid.
#     174                 :            :         INVALID, //!> Invalid.
#     175                 :            :     };
#     176                 :            :     const ResultType m_result_type;
#     177                 :            :     const TxValidationState m_state;
#     178                 :            : 
#     179                 :            :     // The following fields are only present when m_result_type = ResultType::VALID
#     180                 :            :     /** Mempool transactions replaced by the tx per BIP 125 rules. */
#     181                 :            :     const std::optional<std::list<CTransactionRef>> m_replaced_transactions;
#     182                 :            :     /** Raw base fees in satoshis. */
#     183                 :            :     const std::optional<CAmount> m_base_fees;
#     184                 :       8276 :     static MempoolAcceptResult Failure(TxValidationState state) {
#     185                 :       8276 :         return MempoolAcceptResult(state);
#     186                 :       8276 :     }
#     187                 :            : 
#     188                 :      23946 :     static MempoolAcceptResult Success(std::list<CTransactionRef>&& replaced_txns, CAmount fees) {
#     189                 :      23946 :         return MempoolAcceptResult(std::move(replaced_txns), fees);
#     190                 :      23946 :     }
#     191                 :            : 
#     192                 :            : // Private constructors. Use static methods MempoolAcceptResult::Success, etc. to construct.
#     193                 :            : private:
#     194                 :            :     /** Constructor for failure case */
#     195                 :            :     explicit MempoolAcceptResult(TxValidationState state)
#     196                 :       8276 :         : m_result_type(ResultType::INVALID), m_state(state) {
#     197                 :       8276 :             Assume(!state.IsValid()); // Can be invalid or error
#     198                 :       8276 :         }
#     199                 :            : 
#     200                 :            :     /** Constructor for success case */
#     201                 :            :     explicit MempoolAcceptResult(std::list<CTransactionRef>&& replaced_txns, CAmount fees)
#     202                 :            :         : m_result_type(ResultType::VALID),
#     203                 :      23946 :         m_replaced_transactions(std::move(replaced_txns)), m_base_fees(fees) {}
#     204                 :            : };
#     205                 :            : 
#     206                 :            : /**
#     207                 :            : * Validation result for package mempool acceptance.
#     208                 :            : */
#     209                 :            : struct PackageMempoolAcceptResult
#     210                 :            : {
#     211                 :            :     const PackageValidationState m_state;
#     212                 :            :     /**
#     213                 :            :     * Map from wtxid to finished MempoolAcceptResults. The client is responsible
#     214                 :            :     * for keeping track of the transaction objects themselves. If a result is not
#     215                 :            :     * present, it means validation was unfinished for that transaction.
#     216                 :            :     */
#     217                 :            :     std::map<const uint256, const MempoolAcceptResult> m_tx_results;
#     218                 :            : 
#     219                 :            :     explicit PackageMempoolAcceptResult(PackageValidationState state,
#     220                 :            :                                         std::map<const uint256, const MempoolAcceptResult>&& results)
#     221                 :         50 :         : m_state{state}, m_tx_results(std::move(results)) {}
#     222                 :            : 
#     223                 :            :     /** Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult */
#     224                 :            :     explicit PackageMempoolAcceptResult(const uint256& wtxid, const MempoolAcceptResult& result)
#     225                 :        430 :         : m_tx_results{ {wtxid, result} } {}
#     226                 :            : };
#     227                 :            : 
#     228                 :            : /**
#     229                 :            :  * (Try to) add a transaction to the memory pool.
#     230                 :            :  * @param[in]  bypass_limits   When true, don't enforce mempool fee limits.
#     231                 :            :  * @param[in]  test_accept     When true, run validation checks but don't submit to mempool.
#     232                 :            :  */
#     233                 :            : MempoolAcceptResult AcceptToMemoryPool(CChainState& active_chainstate, CTxMemPool& pool, const CTransactionRef& tx,
#     234                 :            :                                        bool bypass_limits, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     235                 :            : 
#     236                 :            : /**
#     237                 :            : * Atomically test acceptance of a package. If the package only contains one tx, package rules still apply.
#     238                 :            : * @param[in]    txns                Group of transactions which may be independent or contain
#     239                 :            : *                                   parent-child dependencies. The transactions must not conflict, i.e.
#     240                 :            : *                                   must not spend the same inputs, even if it would be a valid BIP125
#     241                 :            : *                                   replace-by-fee. Parents must appear before children.
#     242                 :            : * @returns a PackageMempoolAcceptResult which includes a MempoolAcceptResult for each transaction.
#     243                 :            : * If a transaction fails, validation will exit early and some results may be missing.
#     244                 :            : */
#     245                 :            : PackageMempoolAcceptResult ProcessNewPackage(CChainState& active_chainstate, CTxMemPool& pool,
#     246                 :            :                                                    const Package& txns, bool test_accept)
#     247                 :            :                                                    EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     248                 :            : 
#     249                 :            : /** Apply the effects of this transaction on the UTXO set represented by view */
#     250                 :            : void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
#     251                 :            : 
#     252                 :            : /** Transaction validation functions */
#     253                 :            : 
#     254                 :            : /**
#     255                 :            :  * Check if transaction will be final in the next block to be created.
#     256                 :            :  *
#     257                 :            :  * Calls IsFinalTx() with current block height and appropriate block time.
#     258                 :            :  *
#     259                 :            :  * See consensus/consensus.h for flag definitions.
#     260                 :            :  */
#     261                 :            : bool CheckFinalTx(const CBlockIndex* active_chain_tip, const CTransaction &tx, int flags = -1) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     262                 :            : 
#     263                 :            : /**
#     264                 :            :  * Test whether the LockPoints height and time are still valid on the current chain
#     265                 :            :  */
#     266                 :            : bool TestLockPointValidity(CChain& active_chain, const LockPoints* lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     267                 :            : 
#     268                 :            : /**
#     269                 :            :  * Check if transaction will be BIP68 final in the next block to be created on top of tip.
#     270                 :            :  * @param[in]   tip             Chain tip to check tx sequence locks against. For example,
#     271                 :            :  *                              the tip of the current active chain.
#     272                 :            :  * @param[in]   coins_view      Any CCoinsView that provides access to the relevant coins
#     273                 :            :  *                              for checking sequence locks. Any CCoinsView can be passed in;
#     274                 :            :  *                              it is assumed to be consistent with the tip.
#     275                 :            :  * Simulates calling SequenceLocks() with data from the tip passed in.
#     276                 :            :  * Optionally stores in LockPoints the resulting height and time calculated and the hash
#     277                 :            :  * of the block needed for calculation or skips the calculation and uses the LockPoints
#     278                 :            :  * passed in for evaluation.
#     279                 :            :  * The LockPoints should not be considered valid if CheckSequenceLocks returns false.
#     280                 :            :  *
#     281                 :            :  * See consensus/consensus.h for flag definitions.
#     282                 :            :  */
#     283                 :            : bool CheckSequenceLocks(CBlockIndex* tip,
#     284                 :            :                         const CCoinsView& coins_view,
#     285                 :            :                         const CTransaction& tx,
#     286                 :            :                         int flags,
#     287                 :            :                         LockPoints* lp = nullptr,
#     288                 :            :                         bool useExistingLockPoints = false);
#     289                 :            : 
#     290                 :            : /**
#     291                 :            :  * Closure representing one script verification
#     292                 :            :  * Note that this stores references to the spending transaction
#     293                 :            :  */
#     294                 :            : class CScriptCheck
#     295                 :            : {
#     296                 :            : private:
#     297                 :            :     CTxOut m_tx_out;
#     298                 :            :     const CTransaction *ptxTo;
#     299                 :            :     unsigned int nIn;
#     300                 :            :     unsigned int nFlags;
#     301                 :            :     bool cacheStore;
#     302                 :            :     ScriptError error;
#     303                 :            :     PrecomputedTransactionData *txdata;
#     304                 :            : 
#     305                 :            : public:
#     306                 :     330001 :     CScriptCheck(): ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
#     307                 :            :     CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
#     308                 :     729617 :         m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
#     309                 :            : 
#     310                 :            :     bool operator()();
#     311                 :            : 
#     312                 :     329869 :     void swap(CScriptCheck &check) {
#     313                 :     329869 :         std::swap(ptxTo, check.ptxTo);
#     314                 :     329869 :         std::swap(m_tx_out, check.m_tx_out);
#     315                 :     329869 :         std::swap(nIn, check.nIn);
#     316                 :     329869 :         std::swap(nFlags, check.nFlags);
#     317                 :     329869 :         std::swap(cacheStore, check.cacheStore);
#     318                 :     329869 :         std::swap(error, check.error);
#     319                 :     329869 :         std::swap(txdata, check.txdata);
#     320                 :     329869 :     }
#     321                 :            : 
#     322                 :     131437 :     ScriptError GetScriptError() const { return error; }
#     323                 :            : };
#     324                 :            : 
#     325                 :            : /** Initializes the script-execution cache */
#     326                 :            : void InitScriptExecutionCache();
#     327                 :            : 
#     328                 :            : /** Functions for validating blocks and updating the block tree */
#     329                 :            : 
#     330                 :            : /** Context-independent validity checks */
#     331                 :            : bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
#     332                 :            : 
#     333                 :            : /** Check a block is completely valid from start to finish (only works on top of our current best block) */
#     334                 :            : bool TestBlockValidity(BlockValidationState& state,
#     335                 :            :                        const CChainParams& chainparams,
#     336                 :            :                        CChainState& chainstate,
#     337                 :            :                        const CBlock& block,
#     338                 :            :                        CBlockIndex* pindexPrev,
#     339                 :            :                        bool fCheckPOW = true,
#     340                 :            :                        bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     341                 :            : 
#     342                 :            : /** Check whether witness commitments are required for a block, and whether to enforce NULLDUMMY (BIP 147) rules.
#     343                 :            :  *  Note that transaction witness validation rules are always enforced when P2SH is enforced. */
#     344                 :            : bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params);
#     345                 :            : 
#     346                 :            : /** Update uncommitted block structures (currently: only the witness reserved value). This is safe for submitted blocks. */
#     347                 :            : void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
#     348                 :            : 
#     349                 :            : /** Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks). */
#     350                 :            : std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
#     351                 :            : 
#     352                 :            : /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
#     353                 :            : class CVerifyDB {
#     354                 :            : public:
#     355                 :            :     CVerifyDB();
#     356                 :            :     ~CVerifyDB();
#     357                 :            :     bool VerifyDB(
#     358                 :            :         CChainState& chainstate,
#     359                 :            :         const CChainParams& chainparams,
#     360                 :            :         CCoinsView& coinsview,
#     361                 :            :         int nCheckLevel,
#     362                 :            :         int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     363                 :            : };
#     364                 :            : 
#     365                 :            : enum DisconnectResult
#     366                 :            : {
#     367                 :            :     DISCONNECT_OK,      // All good.
#     368                 :            :     DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
#     369                 :            :     DISCONNECT_FAILED   // Something else went wrong.
#     370                 :            : };
#     371                 :            : 
#     372                 :            : class ConnectTrace;
#     373                 :            : 
#     374                 :            : /** @see CChainState::FlushStateToDisk */
#     375                 :            : enum class FlushStateMode {
#     376                 :            :     NONE,
#     377                 :            :     IF_NEEDED,
#     378                 :            :     PERIODIC,
#     379                 :            :     ALWAYS
#     380                 :            : };
#     381                 :            : 
#     382                 :            : struct CBlockIndexWorkComparator
#     383                 :            : {
#     384                 :            :     bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const;
#     385                 :            : };
#     386                 :            : 
#     387                 :            : /**
#     388                 :            :  * Maintains a tree of blocks (stored in `m_block_index`) which is consulted
#     389                 :            :  * to determine where the most-work tip is.
#     390                 :            :  *
#     391                 :            :  * This data is used mostly in `CChainState` - information about, e.g.,
#     392                 :            :  * candidate tips is not maintained here.
#     393                 :            :  */
#     394                 :            : class BlockManager
#     395                 :            : {
#     396                 :            :     friend CChainState;
#     397                 :            : 
#     398                 :            : private:
#     399                 :            :     /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
#     400                 :            :     void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight, int chain_tip_height);
#     401                 :            : 
#     402                 :            :     /**
#     403                 :            :      * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
#     404                 :            :      * The user sets the target (in MB) on the command line or in config file.  This will be run on startup and whenever new
#     405                 :            :      * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
#     406                 :            :      * (which in this case means the blockchain must be re-downloaded.)
#     407                 :            :      *
#     408                 :            :      * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
#     409                 :            :      * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
#     410                 :            :      * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
#     411                 :            :      * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
#     412                 :            :      * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
#     413                 :            :      * A db flag records the fact that at least some block files have been pruned.
#     414                 :            :      *
#     415                 :            :      * @param[out]   setFilesToPrune   The set of file indices that can be unlinked will be returned
#     416                 :            :      */
#     417                 :            :     void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, int prune_height, bool is_ibd);
#     418                 :            : 
#     419                 :            : public:
#     420                 :            :     BlockMap m_block_index GUARDED_BY(cs_main);
#     421                 :            : 
#     422                 :            :     /** In order to efficiently track invalidity of headers, we keep the set of
#     423                 :            :       * blocks which we tried to connect and found to be invalid here (ie which
#     424                 :            :       * were set to BLOCK_FAILED_VALID since the last restart). We can then
#     425                 :            :       * walk this set and check if a new header is a descendant of something in
#     426                 :            :       * this set, preventing us from having to walk m_block_index when we try
#     427                 :            :       * to connect a bad block and fail.
#     428                 :            :       *
#     429                 :            :       * While this is more complicated than marking everything which descends
#     430                 :            :       * from an invalid block as invalid at the time we discover it to be
#     431                 :            :       * invalid, doing so would require walking all of m_block_index to find all
#     432                 :            :       * descendants. Since this case should be very rare, keeping track of all
#     433                 :            :       * BLOCK_FAILED_VALID blocks in a set should be just fine and work just as
#     434                 :            :       * well.
#     435                 :            :       *
#     436                 :            :       * Because we already walk m_block_index in height-order at startup, we go
#     437                 :            :       * ahead and mark descendants of invalid blocks as FAILED_CHILD at that time,
#     438                 :            :       * instead of putting things in this set.
#     439                 :            :       */
#     440                 :            :     std::set<CBlockIndex*> m_failed_blocks;
#     441                 :            : 
#     442                 :            :     /**
#     443                 :            :      * All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
#     444                 :            :      * Pruned nodes may have entries where B is missing data.
#     445                 :            :      */
#     446                 :            :     std::multimap<CBlockIndex*, CBlockIndex*> m_blocks_unlinked;
#     447                 :            : 
#     448                 :            :     /**
#     449                 :            :      * Load the blocktree off disk and into memory. Populate certain metadata
#     450                 :            :      * per index entry (nStatus, nChainWork, nTimeMax, etc.) as well as peripheral
#     451                 :            :      * collections like setDirtyBlockIndex.
#     452                 :            :      *
#     453                 :            :      * @param[out] block_index_candidates  Fill this set with any valid blocks for
#     454                 :            :      *                                     which we've downloaded all transactions.
#     455                 :            :      */
#     456                 :            :     bool LoadBlockIndex(
#     457                 :            :         const Consensus::Params& consensus_params,
#     458                 :            :         CBlockTreeDB& blocktree,
#     459                 :            :         std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
#     460                 :            :         EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     461                 :            : 
#     462                 :            :     /** Clear all data members. */
#     463                 :            :     void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     464                 :            : 
#     465                 :            :     CBlockIndex* AddToBlockIndex(const CBlockHeader& block) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     466                 :            :     /** Create a new block index entry for a given block hash */
#     467                 :            :     CBlockIndex* InsertBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     468                 :            : 
#     469                 :            :     //! Mark one block file as pruned (modify associated database entries)
#     470                 :            :     void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     471                 :            : 
#     472                 :            :     /**
#     473                 :            :      * If a block header hasn't already been seen, call CheckBlockHeader on it, ensure
#     474                 :            :      * that it doesn't descend from an invalid block, and then add it to m_block_index.
#     475                 :            :      */
#     476                 :            :     bool AcceptBlockHeader(
#     477                 :            :         const CBlockHeader& block,
#     478                 :            :         BlockValidationState& state,
#     479                 :            :         const CChainParams& chainparams,
#     480                 :            :         CBlockIndex** ppindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     481                 :            : 
#     482                 :            :     CBlockIndex* LookupBlockIndex(const uint256& hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     483                 :            : 
#     484                 :            :     /** Find the last common block between the parameter chain and a locator. */
#     485                 :            :     CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     486                 :            : 
#     487                 :            :     //! Returns last CBlockIndex* that is a checkpoint
#     488                 :            :     CBlockIndex* GetLastCheckpoint(const CCheckpointData& data) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     489                 :            : 
#     490                 :            :     /**
#     491                 :            :      * Return the spend height, which is one more than the inputs.GetBestBlock().
#     492                 :            :      * While checking, GetBestBlock() refers to the parent block. (protected by cs_main)
#     493                 :            :      * This is also true for mempool checks.
#     494                 :            :      */
#     495                 :            :     int GetSpendHeight(const CCoinsViewCache& inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     496                 :            : 
#     497                 :          2 :     ~BlockManager() {
#     498                 :          2 :         Unload();
#     499                 :          2 :     }
#     500                 :            : };
#     501                 :            : 
#     502                 :            : /**
#     503                 :            :  * A convenience class for constructing the CCoinsView* hierarchy used
#     504                 :            :  * to facilitate access to the UTXO set.
#     505                 :            :  *
#     506                 :            :  * This class consists of an arrangement of layered CCoinsView objects,
#     507                 :            :  * preferring to store and retrieve coins in memory via `m_cacheview` but
#     508                 :            :  * ultimately falling back on cache misses to the canonical store of UTXOs on
#     509                 :            :  * disk, `m_dbview`.
#     510                 :            :  */
#     511                 :            : class CoinsViews {
#     512                 :            : 
#     513                 :            : public:
#     514                 :            :     //! The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
#     515                 :            :     //! All unspent coins reside in this store.
#     516                 :            :     CCoinsViewDB m_dbview GUARDED_BY(cs_main);
#     517                 :            : 
#     518                 :            :     //! This view wraps access to the leveldb instance and handles read errors gracefully.
#     519                 :            :     CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main);
#     520                 :            : 
#     521                 :            :     //! This is the top layer of the cache hierarchy - it keeps as many coins in memory as
#     522                 :            :     //! can fit per the dbcache setting.
#     523                 :            :     std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
#     524                 :            : 
#     525                 :            :     //! This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it
#     526                 :            :     //! *does not* create a CCoinsViewCache instance by default. This is done separately because the
#     527                 :            :     //! presence of the cache has implications on whether or not we're allowed to flush the cache's
#     528                 :            :     //! state to disk, which should not be done until the health of the database is verified.
#     529                 :            :     //!
#     530                 :            :     //! All arguments forwarded onto CCoinsViewDB.
#     531                 :            :     CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe);
#     532                 :            : 
#     533                 :            :     //! Initialize the CCoinsViewCache member.
#     534                 :            :     void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
#     535                 :            : };
#     536                 :            : 
#     537                 :            : enum class CoinsCacheSizeState
#     538                 :            : {
#     539                 :            :     //! The coins cache is in immediate need of a flush.
#     540                 :            :     CRITICAL = 2,
#     541                 :            :     //! The cache is at >= 90% capacity.
#     542                 :            :     LARGE = 1,
#     543                 :            :     OK = 0
#     544                 :            : };
#     545                 :            : 
#     546                 :            : /**
#     547                 :            :  * CChainState stores and provides an API to update our local knowledge of the
#     548                 :            :  * current best chain.
#     549                 :            :  *
#     550                 :            :  * Eventually, the API here is targeted at being exposed externally as a
#     551                 :            :  * consumable libconsensus library, so any functions added must only call
#     552                 :            :  * other class member functions, pure functions in other parts of the consensus
#     553                 :            :  * library, callbacks via the validation interface, or read/write-to-disk
#     554                 :            :  * functions (eventually this will also be via callbacks).
#     555                 :            :  *
#     556                 :            :  * Anything that is contingent on the current tip of the chain is stored here,
#     557                 :            :  * whereas block information and metadata independent of the current tip is
#     558                 :            :  * kept in `BlockMetadataManager`.
#     559                 :            :  */
#     560                 :            : class CChainState
#     561                 :            : {
#     562                 :            : protected:
#     563                 :            :     /**
#     564                 :            :      * Every received block is assigned a unique and increasing identifier, so we
#     565                 :            :      * know which one to give priority in case of a fork.
#     566                 :            :      */
#     567                 :            :     RecursiveMutex cs_nBlockSequenceId;
#     568                 :            :     /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
#     569                 :            :     int32_t nBlockSequenceId = 1;
#     570                 :            :     /** Decreasing counter (used by subsequent preciousblock calls). */
#     571                 :            :     int32_t nBlockReverseSequenceId = -1;
#     572                 :            :     /** chainwork for the last block that preciousblock has been applied to. */
#     573                 :            :     arith_uint256 nLastPreciousChainwork = 0;
#     574                 :            : 
#     575                 :            :     /**
#     576                 :            :      * the ChainState CriticalSection
#     577                 :            :      * A lock that must be held when modifying this ChainState - held in ActivateBestChain()
#     578                 :            :      */
#     579                 :            :     RecursiveMutex m_cs_chainstate;
#     580                 :            : 
#     581                 :            :     /**
#     582                 :            :      * Whether this chainstate is undergoing initial block download.
#     583                 :            :      *
#     584                 :            :      * Mutable because we need to be able to mark IsInitialBlockDownload()
#     585                 :            :      * const, which latches this for caching purposes.
#     586                 :            :      */
#     587                 :            :     mutable std::atomic<bool> m_cached_finished_ibd{false};
#     588                 :            : 
#     589                 :            :     //! mempool that is kept in sync with the chain
#     590                 :            :     CTxMemPool& m_mempool;
#     591                 :            : 
#     592                 :            :     //! Manages the UTXO set, which is a reflection of the contents of `m_chain`.
#     593                 :            :     std::unique_ptr<CoinsViews> m_coins_views;
#     594                 :            : 
#     595                 :            : public:
#     596                 :            :     //! Reference to a BlockManager instance which itself is shared across all
#     597                 :            :     //! CChainState instances.
#     598                 :            :     BlockManager& m_blockman;
#     599                 :            : 
#     600                 :            :     explicit CChainState(CTxMemPool& mempool, BlockManager& blockman, std::optional<uint256> from_snapshot_blockhash = std::nullopt);
#     601                 :            : 
#     602                 :            :     /**
#     603                 :            :      * Initialize the CoinsViews UTXO set database management data structures. The in-memory
#     604                 :            :      * cache is initialized separately.
#     605                 :            :      *
#     606                 :            :      * All parameters forwarded to CoinsViews.
#     607                 :            :      */
#     608                 :            :     void InitCoinsDB(
#     609                 :            :         size_t cache_size_bytes,
#     610                 :            :         bool in_memory,
#     611                 :            :         bool should_wipe,
#     612                 :            :         std::string leveldb_name = "chainstate");
#     613                 :            : 
#     614                 :            :     //! Initialize the in-memory coins cache (to be done after the health of the on-disk database
#     615                 :            :     //! is verified).
#     616                 :            :     void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
#     617                 :            : 
#     618                 :            :     //! @returns whether or not the CoinsViews object has been fully initialized and we can
#     619                 :            :     //!          safely flush this object to disk.
#     620                 :     239277 :     bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
#     621 [ +  - ][ +  + ]:     239277 :         return m_coins_views && m_coins_views->m_cacheview;
#     622                 :     239277 :     }
#     623                 :            : 
#     624                 :            :     //! The current chain of blockheaders we consult and build on.
#     625                 :            :     //! @see CChain, CBlockIndex.
#     626                 :            :     CChain m_chain;
#     627                 :            : 
#     628                 :            :     /**
#     629                 :            :      * The blockhash which is the base of the snapshot this chainstate was created from.
#     630                 :            :      *
#     631                 :            :      * std::nullopt if this chainstate was not created from a snapshot.
#     632                 :            :      */
#     633                 :            :     const std::optional<uint256> m_from_snapshot_blockhash;
#     634                 :            : 
#     635                 :            :     /**
#     636                 :            :      * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
#     637                 :            :      * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
#     638                 :            :      * missing the data for the block.
#     639                 :            :      */
#     640                 :            :     std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
#     641                 :            : 
#     642                 :            :     //! @returns A reference to the in-memory cache of the UTXO set.
#     643                 :            :     CCoinsViewCache& CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
#     644                 :    2848678 :     {
#     645                 :    2848678 :         assert(m_coins_views->m_cacheview);
#     646                 :    2848678 :         return *m_coins_views->m_cacheview.get();
#     647                 :    2848678 :     }
#     648                 :            : 
#     649                 :            :     //! @returns A reference to the on-disk UTXO set database.
#     650                 :            :     CCoinsViewDB& CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
#     651                 :       1969 :     {
#     652                 :       1969 :         return m_coins_views->m_dbview;
#     653                 :       1969 :     }
#     654                 :            : 
#     655                 :            :     //! @returns A reference to a wrapped view of the in-memory UTXO set that
#     656                 :            :     //!     handles disk read errors gracefully.
#     657                 :            :     CCoinsViewErrorCatcher& CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
#     658                 :        626 :     {
#     659                 :        626 :         return m_coins_views->m_catcherview;
#     660                 :        626 :     }
#     661                 :            : 
#     662                 :            :     //! Destructs all objects related to accessing the UTXO set.
#     663                 :        626 :     void ResetCoinsViews() { m_coins_views.reset(); }
#     664                 :            : 
#     665                 :            :     //! The cache size of the on-disk coins view.
#     666                 :            :     size_t m_coinsdb_cache_size_bytes{0};
#     667                 :            : 
#     668                 :            :     //! The cache size of the in-memory coins view.
#     669                 :            :     size_t m_coinstip_cache_size_bytes{0};
#     670                 :            : 
#     671                 :            :     //! Resize the CoinsViews caches dynamically and flush state to disk.
#     672                 :            :     //! @returns true unless an error occurred during the flush.
#     673                 :            :     bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
#     674                 :            :         EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
#     675                 :            : 
#     676                 :            :     /** Import blocks from an external file */
#     677                 :            :     void LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, FlatFilePos* dbp = nullptr);
#     678                 :            : 
#     679                 :            :     /**
#     680                 :            :      * Update the on-disk chain state.
#     681                 :            :      * The caches and indexes are flushed depending on the mode we're called with
#     682                 :            :      * if they're too large, if it's been a while since the last write,
#     683                 :            :      * or always and in all cases if we're in prune mode and are deleting files.
#     684                 :            :      *
#     685                 :            :      * If FlushStateMode::NONE is used, then FlushStateToDisk(...) won't do anything
#     686                 :            :      * besides checking if we need to prune.
#     687                 :            :      *
#     688                 :            :      * @returns true unless a system error occurred
#     689                 :            :      */
#     690                 :            :     bool FlushStateToDisk(
#     691                 :            :         const CChainParams& chainparams,
#     692                 :            :         BlockValidationState &state,
#     693                 :            :         FlushStateMode mode,
#     694                 :            :         int nManualPruneHeight = 0);
#     695                 :            : 
#     696                 :            :     //! Unconditionally flush all changes to disk.
#     697                 :            :     void ForceFlushStateToDisk();
#     698                 :            : 
#     699                 :            :     //! Prune blockfiles from the disk if necessary and then flush chainstate changes
#     700                 :            :     //! if we pruned.
#     701                 :            :     void PruneAndFlush();
#     702                 :            : 
#     703                 :            :     /**
#     704                 :            :      * Find the best known block, and make it the tip of the block chain. The
#     705                 :            :      * result is either failure or an activated best chain. pblock is either
#     706                 :            :      * nullptr or a pointer to a block that is already loaded (to avoid loading
#     707                 :            :      * it again from disk).
#     708                 :            :      *
#     709                 :            :      * ActivateBestChain is split into steps (see ActivateBestChainStep) so that
#     710                 :            :      * we avoid holding cs_main for an extended period of time; the length of this
#     711                 :            :      * call may be quite long during reindexing or a substantial reorg.
#     712                 :            :      *
#     713                 :            :      * May not be called with cs_main held. May not be called in a
#     714                 :            :      * validationinterface callback.
#     715                 :            :      *
#     716                 :            :      * @returns true unless a system error occurred
#     717                 :            :      */
#     718                 :            :     bool ActivateBestChain(
#     719                 :            :         BlockValidationState& state,
#     720                 :            :         const CChainParams& chainparams,
#     721                 :            :         std::shared_ptr<const CBlock> pblock = nullptr) LOCKS_EXCLUDED(cs_main);
#     722                 :            : 
#     723                 :            :     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);
#     724                 :            : 
#     725                 :            :     // Block (dis)connection on a given view:
#     726                 :            :     DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view);
#     727                 :            :     bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
#     728                 :            :                       CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     729                 :            : 
#     730                 :            :     // Apply the effects of a block disconnection on the UTXO set.
#     731                 :            :     bool DisconnectTip(BlockValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool.cs);
#     732                 :            : 
#     733                 :            :     // Manual block validity manipulation:
#     734                 :            :     /** Mark a block as precious and reorganize.
#     735                 :            :      *
#     736                 :            :      * May not be called in a validationinterface callback.
#     737                 :            :      */
#     738                 :            :     bool PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
#     739                 :            :     /** Mark a block as invalid. */
#     740                 :            :     bool InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
#     741                 :            :     /** Remove invalidity status from a block and its descendants. */
#     742                 :            :     void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     743                 :            : 
#     744                 :            :     /** Replay blocks that aren't fully applied to the database. */
#     745                 :            :     bool ReplayBlocks(const CChainParams& params);
#     746                 :            : 
#     747                 :            :     /** Whether the chain state needs to be redownloaded due to lack of witness data */
#     748                 :            :     [[nodiscard]] bool NeedsRedownload(const CChainParams& params) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     749                 :            :     /** Ensures we have a genesis block in the block tree, possibly writing one to disk. */
#     750                 :            :     bool LoadGenesisBlock(const CChainParams& chainparams);
#     751                 :            : 
#     752                 :            :     void PruneBlockIndexCandidates();
#     753                 :            : 
#     754                 :            :     void UnloadBlockIndex();
#     755                 :            : 
#     756                 :            :     /** Check whether we are doing an initial block download (synchronizing from disk or network) */
#     757                 :            :     bool IsInitialBlockDownload() const;
#     758                 :            : 
#     759                 :            :     /**
#     760                 :            :      * Make various assertions about the state of the block index.
#     761                 :            :      *
#     762                 :            :      * By default this only executes fully when using the Regtest chain; see: fCheckBlockIndex.
#     763                 :            :      */
#     764                 :            :     void CheckBlockIndex(const Consensus::Params& consensusParams);
#     765                 :            : 
#     766                 :            :     /** Load the persisted mempool from disk */
#     767                 :            :     void LoadMempool(const ArgsManager& args);
#     768                 :            : 
#     769                 :            :     /** Update the chain tip based on database information, i.e. CoinsTip()'s best block. */
#     770                 :            :     bool LoadChainTip(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     771                 :            : 
#     772                 :            :     //! Dictates whether we need to flush the cache to disk or not.
#     773                 :            :     //!
#     774                 :            :     //! @return the state of the size of the coins cache.
#     775                 :            :     CoinsCacheSizeState GetCoinsCacheSizeState(const CTxMemPool* tx_pool)
#     776                 :            :         EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
#     777                 :            : 
#     778                 :            :     CoinsCacheSizeState GetCoinsCacheSizeState(
#     779                 :            :         const CTxMemPool* tx_pool,
#     780                 :            :         size_t max_coins_cache_size_bytes,
#     781                 :            :         size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
#     782                 :            : 
#     783                 :            :     std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
#     784                 :            : 
#     785                 :            : private:
#     786                 :            :     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, m_mempool.cs);
#     787                 :            :     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, m_mempool.cs);
#     788                 :            : 
#     789                 :            :     void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     790                 :            :     CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     791                 :            :     void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos, const Consensus::Params& consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     792                 :            : 
#     793                 :            :     bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     794                 :            : 
#     795                 :            :     void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     796                 :            :     void InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     797                 :            : 
#     798                 :            :     bool LoadBlockIndexDB(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#     799                 :            : 
#     800                 :            :     friend ChainstateManager;
#     801                 :            : };
#     802                 :            : 
#     803                 :            : /**
#     804                 :            :  * Provides an interface for creating and interacting with one or two
#     805                 :            :  * chainstates: an IBD chainstate generated by downloading blocks, and
#     806                 :            :  * an optional snapshot chainstate loaded from a UTXO snapshot. Managed
#     807                 :            :  * chainstates can be maintained at different heights simultaneously.
#     808                 :            :  *
#     809                 :            :  * This class provides abstractions that allow the retrieval of the current
#     810                 :            :  * most-work chainstate ("Active") as well as chainstates which may be in
#     811                 :            :  * background use to validate UTXO snapshots.
#     812                 :            :  *
#     813                 :            :  * Definitions:
#     814                 :            :  *
#     815                 :            :  * *IBD chainstate*: a chainstate whose current state has been "fully"
#     816                 :            :  *   validated by the initial block download process.
#     817                 :            :  *
#     818                 :            :  * *Snapshot chainstate*: a chainstate populated by loading in an
#     819                 :            :  *    assumeutxo UTXO snapshot.
#     820                 :            :  *
#     821                 :            :  * *Active chainstate*: the chainstate containing the current most-work
#     822                 :            :  *    chain. Consulted by most parts of the system (net_processing,
#     823                 :            :  *    wallet) as a reflection of the current chain and UTXO set.
#     824                 :            :  *    This may either be an IBD chainstate or a snapshot chainstate.
#     825                 :            :  *
#     826                 :            :  * *Background IBD chainstate*: an IBD chainstate for which the
#     827                 :            :  *    IBD process is happening in the background while use of the
#     828                 :            :  *    active (snapshot) chainstate allows the rest of the system to function.
#     829                 :            :  *
#     830                 :            :  * *Validated chainstate*: the most-work chainstate which has been validated
#     831                 :            :  *   locally via initial block download. This will be the snapshot chainstate
#     832                 :            :  *   if a snapshot was loaded and all blocks up to the snapshot starting point
#     833                 :            :  *   have been downloaded and validated (via background validation), otherwise
#     834                 :            :  *   it will be the IBD chainstate.
#     835                 :            :  */
#     836                 :            : class ChainstateManager
#     837                 :            : {
#     838                 :            : private:
#     839                 :            :     //! The chainstate used under normal operation (i.e. "regular" IBD) or, if
#     840                 :            :     //! a snapshot is in use, for background validation.
#     841                 :            :     //!
#     842                 :            :     //! Its contents (including on-disk data) will be deleted *upon shutdown*
#     843                 :            :     //! after background validation of the snapshot has completed. We do not
#     844                 :            :     //! free the chainstate contents immediately after it finishes validation
#     845                 :            :     //! to cautiously avoid a case where some other part of the system is still
#     846                 :            :     //! using this pointer (e.g. net_processing).
#     847                 :            :     //!
#     848                 :            :     //! Once this pointer is set to a corresponding chainstate, it will not
#     849                 :            :     //! be reset until init.cpp:Shutdown().
#     850                 :            :     //!
#     851                 :            :     //! This is especially important when, e.g., calling ActivateBestChain()
#     852                 :            :     //! on all chainstates because we are not able to hold ::cs_main going into
#     853                 :            :     //! that call.
#     854                 :            :     std::unique_ptr<CChainState> m_ibd_chainstate GUARDED_BY(::cs_main);
#     855                 :            : 
#     856                 :            :     //! A chainstate initialized on the basis of a UTXO snapshot. If this is
#     857                 :            :     //! non-null, it is always our active chainstate.
#     858                 :            :     //!
#     859                 :            :     //! Once this pointer is set to a corresponding chainstate, it will not
#     860                 :            :     //! be reset until init.cpp:Shutdown().
#     861                 :            :     //!
#     862                 :            :     //! This is especially important when, e.g., calling ActivateBestChain()
#     863                 :            :     //! on all chainstates because we are not able to hold ::cs_main going into
#     864                 :            :     //! that call.
#     865                 :            :     std::unique_ptr<CChainState> m_snapshot_chainstate GUARDED_BY(::cs_main);
#     866                 :            : 
#     867                 :            :     //! Points to either the ibd or snapshot chainstate; indicates our
#     868                 :            :     //! most-work chain.
#     869                 :            :     //!
#     870                 :            :     //! Once this pointer is set to a corresponding chainstate, it will not
#     871                 :            :     //! be reset until init.cpp:Shutdown().
#     872                 :            :     //!
#     873                 :            :     //! This is especially important when, e.g., calling ActivateBestChain()
#     874                 :            :     //! on all chainstates because we are not able to hold ::cs_main going into
#     875                 :            :     //! that call.
#     876                 :            :     CChainState* m_active_chainstate GUARDED_BY(::cs_main) {nullptr};
#     877                 :            : 
#     878                 :            :     //! If true, the assumed-valid chainstate has been fully validated
#     879                 :            :     //! by the background validation chainstate.
#     880                 :            :     bool m_snapshot_validated{false};
#     881                 :            : 
#     882                 :            :     //! Internal helper for ActivateSnapshot().
#     883                 :            :     [[nodiscard]] bool PopulateAndValidateSnapshot(
#     884                 :            :         CChainState& snapshot_chainstate,
#     885                 :            :         CAutoFile& coins_file,
#     886                 :            :         const SnapshotMetadata& metadata);
#     887                 :            : 
#     888                 :            :     // For access to m_active_chainstate.
#     889                 :            :     friend CChainState& ChainstateActive();
#     890                 :            :     friend CChain& ChainActive();
#     891                 :            : 
#     892                 :            : public:
#     893                 :            :     std::thread m_load_block;
#     894                 :            :     //! A single BlockManager instance is shared across each constructed
#     895                 :            :     //! chainstate to avoid duplicating block metadata.
#     896                 :            :     BlockManager m_blockman GUARDED_BY(::cs_main);
#     897                 :            : 
#     898                 :            :     //! The total number of bytes available for us to use across all in-memory
#     899                 :            :     //! coins caches. This will be split somehow across chainstates.
#     900                 :            :     int64_t m_total_coinstip_cache{0};
#     901                 :            :     //
#     902                 :            :     //! The total number of bytes available for us to use across all leveldb
#     903                 :            :     //! coins databases. This will be split somehow across chainstates.
#     904                 :            :     int64_t m_total_coinsdb_cache{0};
#     905                 :            : 
#     906                 :            :     //! Instantiate a new chainstate and assign it based upon whether it is
#     907                 :            :     //! from a snapshot.
#     908                 :            :     //!
#     909                 :            :     //! @param[in] mempool              The mempool to pass to the chainstate
#     910                 :            :     //                                  constructor
#     911                 :            :     //! @param[in] snapshot_blockhash   If given, signify that this chainstate
#     912                 :            :     //!                                 is based on a snapshot.
#     913                 :            :     CChainState& InitializeChainstate(CTxMemPool& mempool, const std::optional<uint256>& snapshot_blockhash = std::nullopt)
#     914                 :            :         EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
#     915                 :            : 
#     916                 :            :     //! Get all chainstates currently being used.
#     917                 :            :     std::vector<CChainState*> GetAll();
#     918                 :            : 
#     919                 :            :     //! Construct and activate a Chainstate on the basis of UTXO snapshot data.
#     920                 :            :     //!
#     921                 :            :     //! Steps:
#     922                 :            :     //!
#     923                 :            :     //! - Initialize an unused CChainState.
#     924                 :            :     //! - Load its `CoinsViews` contents from `coins_file`.
#     925                 :            :     //! - Verify that the hash of the resulting coinsdb matches the expected hash
#     926                 :            :     //!   per assumeutxo chain parameters.
#     927                 :            :     //! - Wait for our headers chain to include the base block of the snapshot.
#     928                 :            :     //! - "Fast forward" the tip of the new chainstate to the base of the snapshot,
#     929                 :            :     //!   faking nTx* block index data along the way.
#     930                 :            :     //! - Move the new chainstate to `m_snapshot_chainstate` and make it our
#     931                 :            :     //!   ChainstateActive().
#     932                 :            :     [[nodiscard]] bool ActivateSnapshot(
#     933                 :            :         CAutoFile& coins_file, const SnapshotMetadata& metadata, bool in_memory);
#     934                 :            : 
#     935                 :            :     //! The most-work chain.
#     936                 :            :     CChainState& ActiveChainstate() const;
#     937                 :    5954606 :     CChain& ActiveChain() const { return ActiveChainstate().m_chain; }
#     938                 :         10 :     int ActiveHeight() const { return ActiveChain().Height(); }
#     939                 :          3 :     CBlockIndex* ActiveTip() const { return ActiveChain().Tip(); }
#     940                 :            : 
#     941                 :            :     BlockMap& BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
#     942                 :     728549 :     {
#     943                 :     728549 :         return m_blockman.m_block_index;
#     944                 :     728549 :     }
#     945                 :            : 
#     946                 :            :     //! @returns true if a snapshot-based chainstate is in use. Also implies
#     947                 :            :     //!          that a background validation chainstate is also in use.
#     948                 :            :     bool IsSnapshotActive() const;
#     949                 :            : 
#     950                 :            :     std::optional<uint256> SnapshotBlockhash() const;
#     951                 :            : 
#     952                 :            :     //! Is there a snapshot in use and has it been fully validated?
#     953                 :       4559 :     bool IsSnapshotValidated() const { return m_snapshot_validated; }
#     954                 :            : 
#     955                 :            :     //! @returns true if this chainstate is being used to validate an active
#     956                 :            :     //!          snapshot in the background.
#     957                 :            :     bool IsBackgroundIBD(CChainState* chainstate) const;
#     958                 :            : 
#     959                 :            :     //! Return the most-work chainstate that has been fully validated.
#     960                 :            :     //!
#     961                 :            :     //! During background validation of a snapshot, this is the IBD chain. After
#     962                 :            :     //! background validation has completed, this is the snapshot chain.
#     963                 :            :     CChainState& ValidatedChainstate() const;
#     964                 :            : 
#     965                 :          2 :     CChain& ValidatedChain() const { return ValidatedChainstate().m_chain; }
#     966                 :          1 :     CBlockIndex* ValidatedTip() const { return ValidatedChain().Tip(); }
#     967                 :            : 
#     968                 :            :     /**
#     969                 :            :      * Process an incoming block. This only returns after the best known valid
#     970                 :            :      * block is made active. Note that it does not, however, guarantee that the
#     971                 :            :      * specific block passed to it has been checked for validity!
#     972                 :            :      *
#     973                 :            :      * If you want to *possibly* get feedback on whether pblock is valid, you must
#     974                 :            :      * install a CValidationInterface (see validationinterface.h) - this will have
#     975                 :            :      * its BlockChecked method called whenever *any* block completes validation.
#     976                 :            :      *
#     977                 :            :      * Note that we guarantee that either the proof-of-work is valid on pblock, or
#     978                 :            :      * (and possibly also) BlockChecked will have been called.
#     979                 :            :      *
#     980                 :            :      * May not be called in a
#     981                 :            :      * validationinterface callback.
#     982                 :            :      *
#     983                 :            :      * @param[in]   pblock  The block we want to process.
#     984                 :            :      * @param[in]   fForceProcessing Process this block even if unrequested; used for non-network block sources.
#     985                 :            :      * @param[out]  fNewBlock A boolean which is set to indicate if the block was first received via this call
#     986                 :            :      * @returns     If the block was processed, independently of block validity
#     987                 :            :      */
#     988                 :            :     bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool* fNewBlock) LOCKS_EXCLUDED(cs_main);
#     989                 :            : 
#     990                 :            :     /**
#     991                 :            :      * Process incoming block headers.
#     992                 :            :      *
#     993                 :            :      * May not be called in a
#     994                 :            :      * validationinterface callback.
#     995                 :            :      *
#     996                 :            :      * @param[in]  block The block headers themselves
#     997                 :            :      * @param[out] state This may be set to an Error state if any error occurred processing them
#     998                 :            :      * @param[in]  chainparams The params for the chain we want to connect to
#     999                 :            :      * @param[out] ppindex If set, the pointer will be set to point to the last new block index object for the given headers
#    1000                 :            :      */
#    1001                 :            :     bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, BlockValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
#    1002                 :            : 
#    1003                 :            :     //! Load the block tree and coins database from disk, initializing state if we're running with -reindex
#    1004                 :            :     bool LoadBlockIndex(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
#    1005                 :            : 
#    1006                 :            :     //! Unload block index and chain data before shutdown.
#    1007                 :            :     void Unload() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
#    1008                 :            : 
#    1009                 :            :     //! Clear (deconstruct) chainstate data.
#    1010                 :            :     void Reset();
#    1011                 :            : 
#    1012                 :            :     //! Check to see if caches are out of balance and if so, call
#    1013                 :            :     //! ResizeCoinsCaches() as needed.
#    1014                 :            :     void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
#    1015                 :            : };
#    1016                 :            : 
#    1017                 :            : /** DEPRECATED! Please use node.chainman instead. May only be used in validation.cpp internally */
#    1018                 :            : extern ChainstateManager g_chainman GUARDED_BY(::cs_main);
#    1019                 :            : 
#    1020                 :            : /** Please prefer the identical ChainstateManager::ActiveChainstate */
#    1021                 :            : CChainState& ChainstateActive();
#    1022                 :            : 
#    1023                 :            : /** Please prefer the identical ChainstateManager::ActiveChain */
#    1024                 :            : CChain& ChainActive();
#    1025                 :            : 
#    1026                 :            : /** Global variable that points to the active block tree (protected by cs_main) */
#    1027                 :            : extern std::unique_ptr<CBlockTreeDB> pblocktree;
#    1028                 :            : 
#    1029                 :            : extern VersionBitsCache versionbitscache;
#    1030                 :            : 
#    1031                 :            : /**
#    1032                 :            :  * Determine what nVersion a new block should use.
#    1033                 :            :  */
#    1034                 :            : int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params);
#    1035                 :            : 
#    1036                 :            : using FopenFn = std::function<FILE*(const fs::path&, const char*)>;
#    1037                 :            : 
#    1038                 :            : /** Dump the mempool to disk. */
#    1039                 :            : bool DumpMempool(const CTxMemPool& pool, FopenFn mockable_fopen_function = fsbridge::fopen, bool skip_file_commit = false);
#    1040                 :            : 
#    1041                 :            : /** Load the mempool from disk. */
#    1042                 :            : bool LoadMempool(CTxMemPool& pool, CChainState& active_chainstate, FopenFn mockable_fopen_function = fsbridge::fopen);
#    1043                 :            : 
#    1044                 :            : /**
#    1045                 :            :  * Return the expected assumeutxo value for a given height, if one exists.
#    1046                 :            :  *
#    1047                 :            :  * @param[in] height Get the assumeutxo value for this height.
#    1048                 :            :  *
#    1049                 :            :  * @returns empty if no assumeutxo configuration exists for the given height.
#    1050                 :            :  */
#    1051                 :            : const AssumeutxoData* ExpectedAssumeutxo(const int height, const CChainParams& params);
#    1052                 :            : 
#    1053                 :            : #endif // BITCOIN_VALIDATION_H

Generated by: LCOV version 1.14