LCOV - code coverage report
Current view: top level - src - validation.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 79 91 86.8 %
Date: 2024-05-24 08:22:33 Functions: 45 51 88.2 %
Branches: 13 32 40.6 %

           Branch data     Line data    Source code
       1                 :            : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :            : // Copyright (c) 2009-2022 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                 :            : #include <arith_uint256.h>
      10                 :            : #include <attributes.h>
      11                 :            : #include <chain.h>
      12                 :            : #include <checkqueue.h>
      13                 :            : #include <kernel/chain.h>
      14                 :            : #include <consensus/amount.h>
      15                 :            : #include <deploymentstatus.h>
      16                 :            : #include <kernel/chainparams.h>
      17                 :            : #include <kernel/chainstatemanager_opts.h>
      18                 :            : #include <kernel/cs_main.h> // IWYU pragma: export
      19                 :            : #include <node/blockstorage.h>
      20                 :            : #include <policy/feerate.h>
      21                 :            : #include <policy/packages.h>
      22                 :            : #include <policy/policy.h>
      23                 :            : #include <script/script_error.h>
      24                 :            : #include <sync.h>
      25                 :            : #include <txdb.h>
      26                 :            : #include <txmempool.h> // For CTxMemPool::cs
      27                 :            : #include <uint256.h>
      28                 :            : #include <util/check.h>
      29                 :            : #include <util/fs.h>
      30                 :            : #include <util/hasher.h>
      31                 :            : #include <util/result.h>
      32                 :            : #include <util/translation.h>
      33                 :            : #include <versionbits.h>
      34                 :            : 
      35                 :            : #include <atomic>
      36                 :            : #include <map>
      37                 :            : #include <memory>
      38                 :            : #include <optional>
      39                 :            : #include <set>
      40                 :            : #include <stdint.h>
      41                 :            : #include <string>
      42                 :            : #include <thread>
      43                 :            : #include <type_traits>
      44                 :            : #include <utility>
      45                 :            : #include <vector>
      46                 :            : 
      47                 :            : class Chainstate;
      48                 :            : class CTxMemPool;
      49                 :            : class ChainstateManager;
      50                 :            : struct ChainTxData;
      51                 :            : class DisconnectedBlockTransactions;
      52                 :            : struct PrecomputedTransactionData;
      53                 :            : struct LockPoints;
      54                 :            : struct AssumeutxoData;
      55                 :            : namespace node {
      56                 :            : class SnapshotMetadata;
      57                 :            : } // namespace node
      58                 :            : namespace Consensus {
      59                 :            : struct Params;
      60                 :            : } // namespace Consensus
      61                 :            : namespace util {
      62                 :            : class SignalInterrupt;
      63                 :            : } // namespace util
      64                 :            : 
      65                 :            : /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pruned. */
      66                 :            : static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
      67                 :            : static const signed int DEFAULT_CHECKBLOCKS = 6;
      68                 :            : static constexpr int DEFAULT_CHECKLEVEL{3};
      69                 :            : // Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
      70                 :            : // At 1MB per block, 288 blocks = 288MB.
      71                 :            : // Add 15% for Undo data = 331MB
      72                 :            : // Add 20% for Orphan block rate = 397MB
      73                 :            : // We want the low water mark after pruning to be at least 397 MB and since we prune in
      74                 :            : // full block file chunks, we need the high water mark which triggers the prune to be
      75                 :            : // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
      76                 :            : // Setting the target to >= 550 MiB will make it likely we can respect the target.
      77                 :            : static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
      78                 :            : 
      79                 :            : /** Current sync state passed to tip changed callbacks. */
      80                 :            : enum class SynchronizationState {
      81                 :            :     INIT_REINDEX,
      82                 :            :     INIT_DOWNLOAD,
      83                 :            :     POST_INIT
      84                 :            : };
      85                 :            : 
      86                 :            : extern GlobalMutex g_best_block_mutex;
      87                 :            : extern std::condition_variable g_best_block_cv;
      88                 :            : /** Used to notify getblocktemplate RPC of new tips. */
      89                 :            : extern uint256 g_best_block;
      90                 :            : 
      91                 :            : /** Documentation for argument 'checklevel'. */
      92                 :            : extern const std::vector<std::string> CHECKLEVEL_DOC;
      93                 :            : 
      94                 :            : CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
      95                 :            : 
      96                 :            : bool FatalError(kernel::Notifications& notifications, BlockValidationState& state, const bilingual_str& message);
      97                 :            : 
      98                 :            : /** Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip). */
      99                 :            : double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
     100                 :            : 
     101                 :            : /** Prune block files up to a given height */
     102                 :            : void PruneBlockFilesManual(Chainstate& active_chainstate, int nManualPruneHeight);
     103                 :            : 
     104                 :            : /**
     105                 :            : * Validation result for a transaction evaluated by MemPoolAccept (single or package).
     106                 :            : * Here are the expected fields and properties of a result depending on its ResultType, applicable to
     107                 :            : * results returned from package evaluation:
     108                 :            : *+---------------------------+----------------+-------------------+------------------+----------------+-------------------+
     109                 :            : *| Field or property         |    VALID       |                 INVALID              |  MEMPOOL_ENTRY | DIFFERENT_WITNESS |
     110                 :            : *|                           |                |--------------------------------------|                |                   |
     111                 :            : *|                           |                | TX_RECONSIDERABLE |     Other        |                |                   |
     112                 :            : *+---------------------------+----------------+-------------------+------------------+----------------+-------------------+
     113                 :            : *| txid in mempool?          | yes            | no                | no*              | yes            | yes               |
     114                 :            : *| wtxid in mempool?         | yes            | no                | no*              | yes            | no                |
     115                 :            : *| m_state                   | yes, IsValid() | yes, IsInvalid()  | yes, IsInvalid() | yes, IsValid() | yes, IsValid()    |
     116                 :            : *| m_vsize                   | yes            | no                | no               | yes            | no                |
     117                 :            : *| m_base_fees               | yes            | no                | no               | yes            | no                |
     118                 :            : *| m_effective_feerate       | yes            | yes               | no               | no             | no                |
     119                 :            : *| m_wtxids_fee_calculations | yes            | yes               | no               | no             | no                |
     120                 :            : *| m_other_wtxid             | no             | no                | no               | no             | yes               |
     121                 :            : *+---------------------------+----------------+-------------------+------------------+----------------+-------------------+
     122                 :            : * (*) Individual transaction acceptance doesn't return MEMPOOL_ENTRY and DIFFERENT_WITNESS. It returns
     123                 :            : * INVALID, with the errors txn-already-in-mempool and txn-same-nonwitness-data-in-mempool
     124                 :            : * respectively. In those cases, the txid or wtxid may be in the mempool for a TX_CONFLICT.
     125                 :            : */
     126   [ -  +  #  # ]:     204128 : struct MempoolAcceptResult {
     127                 :            :     /** Used to indicate the results of mempool validation. */
     128                 :            :     enum class ResultType {
     129                 :            :         VALID, //!> Fully validated, valid.
     130                 :            :         INVALID, //!> Invalid.
     131                 :            :         MEMPOOL_ENTRY, //!> Valid, transaction was already in the mempool.
     132                 :            :         DIFFERENT_WITNESS, //!> Not validated. A same-txid-different-witness tx (see m_other_wtxid) already exists in the mempool and was not replaced.
     133                 :            :     };
     134                 :            :     /** Result type. Present in all MempoolAcceptResults. */
     135                 :            :     const ResultType m_result_type;
     136                 :            : 
     137                 :            :     /** Contains information about why the transaction failed. */
     138                 :            :     const TxValidationState m_state;
     139                 :            : 
     140                 :            :     /** Mempool transactions replaced by the tx. */
     141                 :            :     const std::list<CTransactionRef> m_replaced_transactions;
     142                 :            :     /** Virtual size as used by the mempool, calculated using serialized size and sigops. */
     143                 :            :     const std::optional<int64_t> m_vsize;
     144                 :            :     /** Raw base fees in satoshis. */
     145                 :            :     const std::optional<CAmount> m_base_fees;
     146                 :            :     /** The feerate at which this transaction was considered. This includes any fee delta added
     147                 :            :      * using prioritisetransaction (i.e. modified fees). If this transaction was submitted as a
     148                 :            :      * package, this is the package feerate, which may also include its descendants and/or
     149                 :            :      * ancestors (see m_wtxids_fee_calculations below).
     150                 :            :      */
     151                 :            :     const std::optional<CFeeRate> m_effective_feerate;
     152                 :            :     /** Contains the wtxids of the transactions used for fee-related checks. Includes this
     153                 :            :      * transaction's wtxid and may include others if this transaction was validated as part of a
     154                 :            :      * package. This is not necessarily equivalent to the list of transactions passed to
     155                 :            :      * ProcessNewPackage().
     156                 :            :      * Only present when m_result_type = ResultType::VALID. */
     157                 :            :     const std::optional<std::vector<Wtxid>> m_wtxids_fee_calculations;
     158                 :            : 
     159                 :            :     /** The wtxid of the transaction in the mempool which has the same txid but different witness. */
     160                 :            :     const std::optional<uint256> m_other_wtxid;
     161                 :            : 
     162                 :     660062 :     static MempoolAcceptResult Failure(TxValidationState state) {
     163         [ +  - ]:     660062 :         return MempoolAcceptResult(state);
     164                 :          0 :     }
     165                 :            : 
     166                 :       9528 :     static MempoolAcceptResult FeeFailure(TxValidationState state,
     167                 :            :                                           CFeeRate effective_feerate,
     168                 :            :                                           const std::vector<Wtxid>& wtxids_fee_calculations) {
     169         [ +  - ]:       9528 :         return MempoolAcceptResult(state, effective_feerate, wtxids_fee_calculations);
     170                 :          0 :     }
     171                 :            : 
     172                 :      78133 :     static MempoolAcceptResult Success(std::list<CTransactionRef>&& replaced_txns,
     173                 :            :                                        int64_t vsize,
     174                 :            :                                        CAmount fees,
     175                 :            :                                        CFeeRate effective_feerate,
     176                 :            :                                        const std::vector<Wtxid>& wtxids_fee_calculations) {
     177                 :     156266 :         return MempoolAcceptResult(std::move(replaced_txns), vsize, fees,
     178                 :      78133 :                                    effective_feerate, wtxids_fee_calculations);
     179                 :            :     }
     180                 :            : 
     181                 :         37 :     static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees) {
     182                 :         37 :         return MempoolAcceptResult(vsize, fees);
     183                 :            :     }
     184                 :            : 
     185                 :          1 :     static MempoolAcceptResult MempoolTxDifferentWitness(const uint256& other_wtxid) {
     186                 :          1 :         return MempoolAcceptResult(other_wtxid);
     187                 :            :     }
     188                 :            : 
     189                 :            : // Private constructors. Use static methods MempoolAcceptResult::Success, etc. to construct.
     190                 :            : private:
     191                 :            :     /** Constructor for failure case */
     192                 :    1320124 :     explicit MempoolAcceptResult(TxValidationState state)
     193                 :     660062 :         : m_result_type(ResultType::INVALID), m_state(state) {
     194         [ +  - ]:     660062 :             Assume(!state.IsValid()); // Can be invalid or error
     195                 :     660062 :         }
     196                 :            : 
     197                 :            :     /** Constructor for success case */
     198                 :     156266 :     explicit MempoolAcceptResult(std::list<CTransactionRef>&& replaced_txns,
     199                 :            :                                  int64_t vsize,
     200                 :            :                                  CAmount fees,
     201                 :            :                                  CFeeRate effective_feerate,
     202                 :            :                                  const std::vector<Wtxid>& wtxids_fee_calculations)
     203                 :      78133 :         : m_result_type(ResultType::VALID),
     204                 :      78133 :         m_replaced_transactions(std::move(replaced_txns)),
     205                 :      78133 :         m_vsize{vsize},
     206                 :      78133 :         m_base_fees(fees),
     207                 :      78133 :         m_effective_feerate(effective_feerate),
     208         [ +  - ]:      78133 :         m_wtxids_fee_calculations(wtxids_fee_calculations) {}
     209                 :            : 
     210                 :            :     /** Constructor for fee-related failure case */
     211                 :      19056 :     explicit MempoolAcceptResult(TxValidationState state,
     212                 :            :                                  CFeeRate effective_feerate,
     213                 :            :                                  const std::vector<Wtxid>& wtxids_fee_calculations)
     214                 :       9528 :         : m_result_type(ResultType::INVALID),
     215                 :       9528 :         m_state(state),
     216                 :       9528 :         m_effective_feerate(effective_feerate),
     217         [ +  - ]:       9528 :         m_wtxids_fee_calculations(wtxids_fee_calculations) {}
     218                 :            : 
     219                 :            :     /** Constructor for already-in-mempool case. It wouldn't replace any transactions. */
     220                 :        111 :     explicit MempoolAcceptResult(int64_t vsize, CAmount fees)
     221                 :        111 :         : m_result_type(ResultType::MEMPOOL_ENTRY), m_vsize{vsize}, m_base_fees(fees) {}
     222                 :            : 
     223                 :            :     /** Constructor for witness-swapped case. */
     224                 :          2 :     explicit MempoolAcceptResult(const uint256& other_wtxid)
     225                 :          2 :         : m_result_type(ResultType::DIFFERENT_WITNESS), m_other_wtxid(other_wtxid) {}
     226                 :            : };
     227                 :            : 
     228                 :            : /**
     229                 :            : * Validation result for package mempool acceptance.
     230                 :            : */
     231                 :            : struct PackageMempoolAcceptResult
     232                 :            : {
     233                 :            :     PackageValidationState m_state;
     234                 :            :     /**
     235                 :            :     * Map from wtxid to finished MempoolAcceptResults. The client is responsible
     236                 :            :     * for keeping track of the transaction objects themselves. If a result is not
     237                 :            :     * present, it means validation was unfinished for that transaction. If there
     238                 :            :     * was a package-wide error (see result in m_state), m_tx_results will be empty.
     239                 :            :     */
     240                 :            :     std::map<uint256, MempoolAcceptResult> m_tx_results;
     241                 :            : 
     242                 :     185366 :     explicit PackageMempoolAcceptResult(PackageValidationState state,
     243                 :            :                                         std::map<uint256, MempoolAcceptResult>&& results)
     244                 :     185366 :         : m_state{state}, m_tx_results(std::move(results)) {}
     245                 :            : 
     246                 :            :     explicit PackageMempoolAcceptResult(PackageValidationState state, CFeeRate feerate,
     247                 :            :                                         std::map<uint256, MempoolAcceptResult>&& results)
     248                 :            :         : m_state{state}, m_tx_results(std::move(results)) {}
     249                 :            : 
     250                 :            :     /** Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult */
     251                 :         42 :     explicit PackageMempoolAcceptResult(const uint256& wtxid, const MempoolAcceptResult& result)
     252   [ +  -  +  - ]:         42 :         : m_tx_results{ {wtxid, result} } {}
     253                 :            : };
     254                 :            : 
     255                 :            : /**
     256                 :            :  * Try to add a transaction to the mempool. This is an internal function and is exposed only for testing.
     257                 :            :  * Client code should use ChainstateManager::ProcessTransaction()
     258                 :            :  *
     259                 :            :  * @param[in]  active_chainstate  Reference to the active chainstate.
     260                 :            :  * @param[in]  tx                 The transaction to submit for mempool acceptance.
     261                 :            :  * @param[in]  accept_time        The timestamp for adding the transaction to the mempool.
     262                 :            :  *                                It is also used to determine when the entry expires.
     263                 :            :  * @param[in]  bypass_limits      When true, don't enforce mempool fee and capacity limits,
     264                 :            :  *                                and set entry_sequence to zero.
     265                 :            :  * @param[in]  test_accept        When true, run validation checks but don't submit to mempool.
     266                 :            :  *
     267                 :            :  * @returns a MempoolAcceptResult indicating whether the transaction was accepted/rejected with reason.
     268                 :            :  */
     269                 :            : MempoolAcceptResult AcceptToMemoryPool(Chainstate& active_chainstate, const CTransactionRef& tx,
     270                 :            :                                        int64_t accept_time, bool bypass_limits, bool test_accept)
     271                 :            :     EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     272                 :            : 
     273                 :            : /**
     274                 :            : * Validate (and maybe submit) a package to the mempool. See doc/policy/packages.md for full details
     275                 :            : * on package validation rules.
     276                 :            : * @param[in]    test_accept         When true, run validation checks but don't submit to mempool.
     277                 :            : * @param[in]    client_maxfeerate    If exceeded by an individual transaction, rest of (sub)package evaluation is aborted.
     278                 :            : *                                   Only for sanity checks against local submission of transactions.
     279                 :            : * @returns a PackageMempoolAcceptResult which includes a MempoolAcceptResult for each transaction.
     280                 :            : * If a transaction fails, validation will exit early and some results may be missing. It is also
     281                 :            : * possible for the package to be partially submitted.
     282                 :            : */
     283                 :            : PackageMempoolAcceptResult ProcessNewPackage(Chainstate& active_chainstate, CTxMemPool& pool,
     284                 :            :                                                    const Package& txns, bool test_accept, const std::optional<CFeeRate>& client_maxfeerate)
     285                 :            :                                                    EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     286                 :            : 
     287                 :            : /* Mempool validation helper functions */
     288                 :            : 
     289                 :            : /**
     290                 :            :  * Check if transaction will be final in the next block to be created.
     291                 :            :  */
     292                 :            : bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     293                 :            : 
     294                 :            : /**
     295                 :            :  * Calculate LockPoints required to check if transaction will be BIP68 final in the next block
     296                 :            :  * to be created on top of tip.
     297                 :            :  *
     298                 :            :  * @param[in]   tip             Chain tip for which tx sequence locks are calculated. For
     299                 :            :  *                              example, the tip of the current active chain.
     300                 :            :  * @param[in]   coins_view      Any CCoinsView that provides access to the relevant coins for
     301                 :            :  *                              checking sequence locks. For example, it can be a CCoinsViewCache
     302                 :            :  *                              that isn't connected to anything but contains all the relevant
     303                 :            :  *                              coins, or a CCoinsViewMemPool that is connected to the
     304                 :            :  *                              mempool and chainstate UTXO set. In the latter case, the caller
     305                 :            :  *                              is responsible for holding the appropriate locks to ensure that
     306                 :            :  *                              calls to GetCoin() return correct coins.
     307                 :            :  * @param[in]   tx              The transaction being evaluated.
     308                 :            :  *
     309                 :            :  * @returns The resulting height and time calculated and the hash of the block needed for
     310                 :            :  *          calculation, or std::nullopt if there is an error.
     311                 :            :  */
     312                 :            : std::optional<LockPoints> CalculateLockPointsAtTip(
     313                 :            :     CBlockIndex* tip,
     314                 :            :     const CCoinsView& coins_view,
     315                 :            :     const CTransaction& tx);
     316                 :            : 
     317                 :            : /**
     318                 :            :  * Check if transaction will be BIP68 final in the next block to be created on top of tip.
     319                 :            :  * @param[in]   tip             Chain tip to check tx sequence locks against. For example,
     320                 :            :  *                              the tip of the current active chain.
     321                 :            :  * @param[in]   lock_points     LockPoints containing the height and time at which this
     322                 :            :  *                              transaction is final.
     323                 :            :  * Simulates calling SequenceLocks() with data from the tip passed in.
     324                 :            :  * The LockPoints should not be considered valid if CheckSequenceLocksAtTip returns false.
     325                 :            :  */
     326                 :            : bool CheckSequenceLocksAtTip(CBlockIndex* tip,
     327                 :            :                              const LockPoints& lock_points);
     328                 :            : 
     329                 :            : /**
     330                 :            :  * Closure representing one script verification
     331                 :            :  * Note that this stores references to the spending transaction
     332                 :            :  */
     333                 :            : class CScriptCheck
     334                 :            : {
     335                 :            : private:
     336                 :            :     CTxOut m_tx_out;
     337                 :            :     const CTransaction *ptxTo;
     338                 :            :     unsigned int nIn;
     339                 :            :     unsigned int nFlags;
     340                 :            :     bool cacheStore;
     341                 :     263346 :     ScriptError error{SCRIPT_ERR_UNKNOWN_ERROR};
     342                 :            :     PrecomputedTransactionData *txdata;
     343                 :            : 
     344                 :            : public:
     345                 :     263346 :     CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
     346                 :     526692 :         m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), txdata(txdataIn) { }
     347                 :            : 
     348                 :            :     CScriptCheck(const CScriptCheck&) = delete;
     349                 :            :     CScriptCheck& operator=(const CScriptCheck&) = delete;
     350                 :       1660 :     CScriptCheck(CScriptCheck&&) = default;
     351                 :          0 :     CScriptCheck& operator=(CScriptCheck&&) = default;
     352                 :            : 
     353                 :            :     bool operator()();
     354                 :            : 
     355                 :      34490 :     ScriptError GetScriptError() const { return error; }
     356                 :            : };
     357                 :            : 
     358                 :            : // CScriptCheck is used a lot in std::vector, make sure that's efficient
     359                 :            : static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);
     360                 :            : static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);
     361                 :            : static_assert(std::is_nothrow_destructible_v<CScriptCheck>);
     362                 :            : 
     363                 :            : /** Initializes the script-execution cache */
     364                 :            : [[nodiscard]] bool InitScriptExecutionCache(size_t max_size_bytes);
     365                 :            : 
     366                 :            : /** Functions for validating blocks and updating the block tree */
     367                 :            : 
     368                 :            : /** Context-independent validity checks */
     369                 :            : bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
     370                 :            : 
     371                 :            : /** Check a block is completely valid from start to finish (only works on top of our current best block) */
     372                 :            : bool TestBlockValidity(BlockValidationState& state,
     373                 :            :                        const CChainParams& chainparams,
     374                 :            :                        Chainstate& chainstate,
     375                 :            :                        const CBlock& block,
     376                 :            :                        CBlockIndex* pindexPrev,
     377                 :            :                        bool fCheckPOW = true,
     378                 :            :                        bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     379                 :            : 
     380                 :            : /** Check with the proof of work on each blockheader matches the value in nBits */
     381                 :            : bool HasValidProofOfWork(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams);
     382                 :            : 
     383                 :            : /** Check if a block has been mutated (with respect to its merkle root and witness commitments). */
     384                 :            : bool IsBlockMutated(const CBlock& block, bool check_witness_root);
     385                 :            : 
     386                 :            : /** Return the sum of the claimed work on a given set of headers. No verification of PoW is done. */
     387                 :            : arith_uint256 CalculateClaimedHeadersWork(const std::vector<CBlockHeader>& headers);
     388                 :            : 
     389                 :            : enum class VerifyDBResult {
     390                 :            :     SUCCESS,
     391                 :            :     CORRUPTED_BLOCK_DB,
     392                 :            :     INTERRUPTED,
     393                 :            :     SKIPPED_L3_CHECKS,
     394                 :            :     SKIPPED_MISSING_BLOCKS,
     395                 :            : };
     396                 :            : 
     397                 :            : /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
     398                 :            : class CVerifyDB
     399                 :            : {
     400                 :            : private:
     401                 :            :     kernel::Notifications& m_notifications;
     402                 :            : 
     403                 :            : public:
     404                 :            :     explicit CVerifyDB(kernel::Notifications& notifications);
     405                 :            :     ~CVerifyDB();
     406                 :            :     [[nodiscard]] VerifyDBResult VerifyDB(
     407                 :            :         Chainstate& chainstate,
     408                 :            :         const Consensus::Params& consensus_params,
     409                 :            :         CCoinsView& coinsview,
     410                 :            :         int nCheckLevel,
     411                 :            :         int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     412                 :            : };
     413                 :            : 
     414                 :            : enum DisconnectResult
     415                 :            : {
     416                 :            :     DISCONNECT_OK,      // All good.
     417                 :            :     DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
     418                 :            :     DISCONNECT_FAILED   // Something else went wrong.
     419                 :            : };
     420                 :            : 
     421                 :            : class ConnectTrace;
     422                 :            : 
     423                 :            : /** @see Chainstate::FlushStateToDisk */
     424                 :            : enum class FlushStateMode {
     425                 :            :     NONE,
     426                 :            :     IF_NEEDED,
     427                 :            :     PERIODIC,
     428                 :            :     ALWAYS
     429                 :            : };
     430                 :            : 
     431                 :            : /**
     432                 :            :  * A convenience class for constructing the CCoinsView* hierarchy used
     433                 :            :  * to facilitate access to the UTXO set.
     434                 :            :  *
     435                 :            :  * This class consists of an arrangement of layered CCoinsView objects,
     436                 :            :  * preferring to store and retrieve coins in memory via `m_cacheview` but
     437                 :            :  * ultimately falling back on cache misses to the canonical store of UTXOs on
     438                 :            :  * disk, `m_dbview`.
     439                 :            :  */
     440                 :            : class CoinsViews {
     441                 :            : 
     442                 :            : public:
     443                 :            :     //! The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
     444                 :            :     //! All unspent coins reside in this store.
     445                 :            :     CCoinsViewDB m_dbview GUARDED_BY(cs_main);
     446                 :            : 
     447                 :            :     //! This view wraps access to the leveldb instance and handles read errors gracefully.
     448                 :            :     CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main);
     449                 :            : 
     450                 :            :     //! This is the top layer of the cache hierarchy - it keeps as many coins in memory as
     451                 :            :     //! can fit per the dbcache setting.
     452                 :            :     std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
     453                 :            : 
     454                 :            :     //! This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it
     455                 :            :     //! *does not* create a CCoinsViewCache instance by default. This is done separately because the
     456                 :            :     //! presence of the cache has implications on whether or not we're allowed to flush the cache's
     457                 :            :     //! state to disk, which should not be done until the health of the database is verified.
     458                 :            :     //!
     459                 :            :     //! All arguments forwarded onto CCoinsViewDB.
     460                 :            :     CoinsViews(DBParams db_params, CoinsViewOptions options);
     461                 :            : 
     462                 :            :     //! Initialize the CCoinsViewCache member.
     463                 :            :     void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     464                 :            : };
     465                 :            : 
     466                 :            : enum class CoinsCacheSizeState
     467                 :            : {
     468                 :            :     //! The coins cache is in immediate need of a flush.
     469                 :            :     CRITICAL = 2,
     470                 :            :     //! The cache is at >= 90% capacity.
     471                 :            :     LARGE = 1,
     472                 :            :     OK = 0
     473                 :            : };
     474                 :            : 
     475                 :            : /**
     476                 :            :  * Chainstate stores and provides an API to update our local knowledge of the
     477                 :            :  * current best chain.
     478                 :            :  *
     479                 :            :  * Eventually, the API here is targeted at being exposed externally as a
     480                 :            :  * consumable library, so any functions added must only call
     481                 :            :  * other class member functions, pure functions in other parts of the consensus
     482                 :            :  * library, callbacks via the validation interface, or read/write-to-disk
     483                 :            :  * functions (eventually this will also be via callbacks).
     484                 :            :  *
     485                 :            :  * Anything that is contingent on the current tip of the chain is stored here,
     486                 :            :  * whereas block information and metadata independent of the current tip is
     487                 :            :  * kept in `BlockManager`.
     488                 :            :  */
     489                 :            : class Chainstate
     490                 :            : {
     491                 :            : protected:
     492                 :            :     /**
     493                 :            :      * The ChainState Mutex
     494                 :            :      * A lock that must be held when modifying this ChainState - held in ActivateBestChain() and
     495                 :            :      * InvalidateBlock()
     496                 :            :      */
     497                 :            :     Mutex m_chainstate_mutex;
     498                 :            : 
     499                 :            :     //! Optional mempool that is kept in sync with the chain.
     500                 :            :     //! Only the active chainstate has a mempool.
     501                 :            :     CTxMemPool* m_mempool;
     502                 :            : 
     503                 :            :     //! Manages the UTXO set, which is a reflection of the contents of `m_chain`.
     504                 :            :     std::unique_ptr<CoinsViews> m_coins_views;
     505                 :            : 
     506                 :            :     //! This toggle exists for use when doing background validation for UTXO
     507                 :            :     //! snapshots.
     508                 :            :     //!
     509                 :            :     //! In the expected case, it is set once the background validation chain reaches the
     510                 :            :     //! same height as the base of the snapshot and its UTXO set is found to hash to
     511                 :            :     //! the expected assumeutxo value. It signals that we should no longer connect
     512                 :            :     //! blocks to the background chainstate. When set on the background validation
     513                 :            :     //! chainstate, it signifies that we have fully validated the snapshot chainstate.
     514                 :            :     //!
     515                 :            :     //! In the unlikely case that the snapshot chainstate is found to be invalid, this
     516                 :            :     //! is set to true on the snapshot chainstate.
     517                 :            :     bool m_disabled GUARDED_BY(::cs_main) {false};
     518                 :            : 
     519                 :            :     //! Cached result of LookupBlockIndex(*m_from_snapshot_blockhash)
     520                 :            :     const CBlockIndex* m_cached_snapshot_base GUARDED_BY(::cs_main) {nullptr};
     521                 :            : 
     522                 :            : public:
     523                 :            :     //! Reference to a BlockManager instance which itself is shared across all
     524                 :            :     //! Chainstate instances.
     525                 :            :     node::BlockManager& m_blockman;
     526                 :            : 
     527                 :            :     //! The chainstate manager that owns this chainstate. The reference is
     528                 :            :     //! necessary so that this instance can check whether it is the active
     529                 :            :     //! chainstate within deeply nested method calls.
     530                 :            :     ChainstateManager& m_chainman;
     531                 :            : 
     532                 :            :     explicit Chainstate(
     533                 :            :         CTxMemPool* mempool,
     534                 :            :         node::BlockManager& blockman,
     535                 :            :         ChainstateManager& chainman,
     536                 :            :         std::optional<uint256> from_snapshot_blockhash = std::nullopt);
     537                 :            : 
     538                 :            :     //! Return the current role of the chainstate. See `ChainstateManager`
     539                 :            :     //! documentation for a description of the different types of chainstates.
     540                 :            :     //!
     541                 :            :     //! @sa ChainstateRole
     542                 :            :     ChainstateRole GetRole() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     543                 :            : 
     544                 :            :     /**
     545                 :            :      * Initialize the CoinsViews UTXO set database management data structures. The in-memory
     546                 :            :      * cache is initialized separately.
     547                 :            :      *
     548                 :            :      * All parameters forwarded to CoinsViews.
     549                 :            :      */
     550                 :            :     void InitCoinsDB(
     551                 :            :         size_t cache_size_bytes,
     552                 :            :         bool in_memory,
     553                 :            :         bool should_wipe,
     554                 :            :         fs::path leveldb_name = "chainstate");
     555                 :            : 
     556                 :            :     //! Initialize the in-memory coins cache (to be done after the health of the on-disk database
     557                 :            :     //! is verified).
     558                 :            :     void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     559                 :            : 
     560                 :            :     //! @returns whether or not the CoinsViews object has been fully initialized and we can
     561                 :            :     //!          safely flush this object to disk.
     562                 :    1135604 :     bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
     563                 :            :     {
     564                 :    1135604 :         AssertLockHeld(::cs_main);
     565         [ -  + ]:    1135604 :         return m_coins_views && m_coins_views->m_cacheview;
     566                 :            :     }
     567                 :            : 
     568                 :            :     //! The current chain of blockheaders we consult and build on.
     569                 :            :     //! @see CChain, CBlockIndex.
     570                 :            :     CChain m_chain;
     571                 :            : 
     572                 :            :     /**
     573                 :            :      * The blockhash which is the base of the snapshot this chainstate was created from.
     574                 :            :      *
     575                 :            :      * std::nullopt if this chainstate was not created from a snapshot.
     576                 :            :      */
     577                 :            :     const std::optional<uint256> m_from_snapshot_blockhash;
     578                 :            : 
     579                 :            :     /**
     580                 :            :      * The base of the snapshot this chainstate was created from.
     581                 :            :      *
     582                 :            :      * nullptr if this chainstate was not created from a snapshot.
     583                 :            :      */
     584                 :            :     const CBlockIndex* SnapshotBase() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     585                 :            : 
     586                 :            :     /**
     587                 :            :      * The set of all CBlockIndex entries that have as much work as our current
     588                 :            :      * tip or more, and transaction data needed to be validated (with
     589                 :            :      * BLOCK_VALID_TRANSACTIONS for each block and its parents back to the
     590                 :            :      * genesis block or an assumeutxo snapshot block). Entries may be failed,
     591                 :            :      * though, and pruning nodes may be missing the data for the block.
     592                 :            :      */
     593                 :            :     std::set<CBlockIndex*, node::CBlockIndexWorkComparator> setBlockIndexCandidates;
     594                 :            : 
     595                 :            :     //! @returns A reference to the in-memory cache of the UTXO set.
     596                 :    6501811 :     CCoinsViewCache& CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
     597                 :            :     {
     598                 :    6501811 :         AssertLockHeld(::cs_main);
     599                 :    6501811 :         Assert(m_coins_views);
     600                 :    6501811 :         return *Assert(m_coins_views->m_cacheview);
     601                 :            :     }
     602                 :            : 
     603                 :            :     //! @returns A reference to the on-disk UTXO set database.
     604                 :     122402 :     CCoinsViewDB& CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
     605                 :            :     {
     606                 :     122402 :         AssertLockHeld(::cs_main);
     607                 :     122402 :         return Assert(m_coins_views)->m_dbview;
     608                 :            :     }
     609                 :            : 
     610                 :            :     //! @returns A pointer to the mempool.
     611                 :    1185828 :     CTxMemPool* GetMempool()
     612                 :            :     {
     613                 :    1185828 :         return m_mempool;
     614                 :            :     }
     615                 :            : 
     616                 :            :     //! @returns A reference to a wrapped view of the in-memory UTXO set that
     617                 :            :     //!     handles disk read errors gracefully.
     618                 :          0 :     CCoinsViewErrorCatcher& CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
     619                 :            :     {
     620                 :          0 :         AssertLockHeld(::cs_main);
     621                 :          0 :         return Assert(m_coins_views)->m_catcherview;
     622                 :            :     }
     623                 :            : 
     624                 :            :     //! Destructs all objects related to accessing the UTXO set.
     625                 :          0 :     void ResetCoinsViews() { m_coins_views.reset(); }
     626                 :            : 
     627                 :            :     //! Does this chainstate have a UTXO set attached?
     628                 :          0 :     bool HasCoinsViews() const { return (bool)m_coins_views; }
     629                 :            : 
     630                 :            :     //! The cache size of the on-disk coins view.
     631                 :            :     size_t m_coinsdb_cache_size_bytes{0};
     632                 :            : 
     633                 :            :     //! The cache size of the in-memory coins view.
     634                 :            :     size_t m_coinstip_cache_size_bytes{0};
     635                 :            : 
     636                 :            :     //! Resize the CoinsViews caches dynamically and flush state to disk.
     637                 :            :     //! @returns true unless an error occurred during the flush.
     638                 :            :     bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
     639                 :            :         EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     640                 :            : 
     641                 :            :     /**
     642                 :            :      * Update the on-disk chain state.
     643                 :            :      * The caches and indexes are flushed depending on the mode we're called with
     644                 :            :      * if they're too large, if it's been a while since the last write,
     645                 :            :      * or always and in all cases if we're in prune mode and are deleting files.
     646                 :            :      *
     647                 :            :      * If FlushStateMode::NONE is used, then FlushStateToDisk(...) won't do anything
     648                 :            :      * besides checking if we need to prune.
     649                 :            :      *
     650                 :            :      * @returns true unless a system error occurred
     651                 :            :      */
     652                 :            :     bool FlushStateToDisk(
     653                 :            :         BlockValidationState& state,
     654                 :            :         FlushStateMode mode,
     655                 :            :         int nManualPruneHeight = 0);
     656                 :            : 
     657                 :            :     //! Unconditionally flush all changes to disk.
     658                 :            :     void ForceFlushStateToDisk();
     659                 :            : 
     660                 :            :     //! Prune blockfiles from the disk if necessary and then flush chainstate changes
     661                 :            :     //! if we pruned.
     662                 :            :     void PruneAndFlush();
     663                 :            : 
     664                 :            :     /**
     665                 :            :      * Find the best known block, and make it the tip of the block chain. The
     666                 :            :      * result is either failure or an activated best chain. pblock is either
     667                 :            :      * nullptr or a pointer to a block that is already loaded (to avoid loading
     668                 :            :      * it again from disk).
     669                 :            :      *
     670                 :            :      * ActivateBestChain is split into steps (see ActivateBestChainStep) so that
     671                 :            :      * we avoid holding cs_main for an extended period of time; the length of this
     672                 :            :      * call may be quite long during reindexing or a substantial reorg.
     673                 :            :      *
     674                 :            :      * May not be called with cs_main held. May not be called in a
     675                 :            :      * validationinterface callback.
     676                 :            :      *
     677                 :            :      * Note that if this is called while a snapshot chainstate is active, and if
     678                 :            :      * it is called on a background chainstate whose tip has reached the base block
     679                 :            :      * of the snapshot, its execution will take *MINUTES* while it hashes the
     680                 :            :      * background UTXO set to verify the assumeutxo value the snapshot was activated
     681                 :            :      * with. `cs_main` will be held during this time.
     682                 :            :      *
     683                 :            :      * @returns true unless a system error occurred
     684                 :            :      */
     685                 :            :     bool ActivateBestChain(
     686                 :            :         BlockValidationState& state,
     687                 :            :         std::shared_ptr<const CBlock> pblock = nullptr)
     688                 :            :         EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
     689                 :            :         LOCKS_EXCLUDED(::cs_main);
     690                 :            : 
     691                 :            :     // Block (dis)connection on a given view:
     692                 :            :     DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
     693                 :            :         EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     694                 :            :     bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
     695                 :            :                       CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     696                 :            : 
     697                 :            :     // Apply the effects of a block disconnection on the UTXO set.
     698                 :            :     bool DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
     699                 :            : 
     700                 :            :     // Manual block validity manipulation:
     701                 :            :     /** Mark a block as precious and reorganize.
     702                 :            :      *
     703                 :            :      * May not be called in a validationinterface callback.
     704                 :            :      */
     705                 :            :     bool PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
     706                 :            :         EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
     707                 :            :         LOCKS_EXCLUDED(::cs_main);
     708                 :            : 
     709                 :            :     /** Mark a block as invalid. */
     710                 :            :     bool InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex)
     711                 :            :         EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
     712                 :            :         LOCKS_EXCLUDED(::cs_main);
     713                 :            : 
     714                 :            :     /** Remove invalidity status from a block and its descendants. */
     715                 :            :     void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     716                 :            : 
     717                 :            :     /** Replay blocks that aren't fully applied to the database. */
     718                 :            :     bool ReplayBlocks();
     719                 :            : 
     720                 :            :     /** Whether the chain state needs to be redownloaded due to lack of witness data */
     721                 :            :     [[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     722                 :            :     /** Ensures we have a genesis block in the block tree, possibly writing one to disk. */
     723                 :            :     bool LoadGenesisBlock();
     724                 :            : 
     725                 :            :     void TryAddBlockIndexCandidate(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     726                 :            : 
     727                 :            :     void PruneBlockIndexCandidates();
     728                 :            : 
     729                 :            :     void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     730                 :            : 
     731                 :            :     /** Find the last common block of this chain and a locator. */
     732                 :            :     const CBlockIndex* FindForkInGlobalIndex(const CBlockLocator& locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     733                 :            : 
     734                 :            :     /** Update the chain tip based on database information, i.e. CoinsTip()'s best block. */
     735                 :            :     bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     736                 :            : 
     737                 :            :     //! Dictates whether we need to flush the cache to disk or not.
     738                 :            :     //!
     739                 :            :     //! @return the state of the size of the coins cache.
     740                 :            :     CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     741                 :            : 
     742                 :            :     CoinsCacheSizeState GetCoinsCacheSizeState(
     743                 :            :         size_t max_coins_cache_size_bytes,
     744                 :            :         size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     745                 :            : 
     746                 :            :     std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     747                 :            : 
     748                 :            :     //! Indirection necessary to make lock annotations work with an optional mempool.
     749                 :     102828 :     RecursiveMutex* MempoolMutex() const LOCK_RETURNED(m_mempool->cs)
     750                 :            :     {
     751         [ +  - ]:     102828 :         return m_mempool ? &m_mempool->cs : nullptr;
     752                 :            :     }
     753                 :            : 
     754                 :            : private:
     755                 :            :     bool ActivateBestChainStep(BlockValidationState& state, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
     756                 :            :     bool ConnectTip(BlockValidationState& state, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions& disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
     757                 :            : 
     758                 :            :     void InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     759                 :            :     CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     760                 :            : 
     761                 :            :     bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     762                 :            : 
     763                 :            :     void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     764                 :            :     void InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     765                 :            : 
     766                 :            :     /**
     767                 :            :      * Make mempool consistent after a reorg, by re-adding or recursively erasing
     768                 :            :      * disconnected block transactions from the mempool, and also removing any
     769                 :            :      * other transactions from the mempool that are no longer valid given the new
     770                 :            :      * tip/height.
     771                 :            :      *
     772                 :            :      * Note: we assume that disconnectpool only contains transactions that are NOT
     773                 :            :      * confirmed in the current chain nor already in the mempool (otherwise,
     774                 :            :      * in-mempool descendants of such transactions would be removed).
     775                 :            :      *
     776                 :            :      * Passing fAddToMempool=false will skip trying to add the transactions back,
     777                 :            :      * and instead just erase from the mempool as needed.
     778                 :            :      */
     779                 :            :     void MaybeUpdateMempoolForReorg(
     780                 :            :         DisconnectedBlockTransactions& disconnectpool,
     781                 :            :         bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
     782                 :            : 
     783                 :            :     /** Check warning conditions and do some notifications on new chain tip set. */
     784                 :            :     void UpdateTip(const CBlockIndex* pindexNew)
     785                 :            :         EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     786                 :            : 
     787                 :            :     SteadyClock::time_point m_last_write{};
     788                 :            :     SteadyClock::time_point m_last_flush{};
     789                 :            : 
     790                 :            :     /**
     791                 :            :      * In case of an invalid snapshot, rename the coins leveldb directory so
     792                 :            :      * that it can be examined for issue diagnosis.
     793                 :            :      */
     794                 :            :     [[nodiscard]] util::Result<void> InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     795                 :            : 
     796                 :            :     friend ChainstateManager;
     797                 :            : };
     798                 :            : 
     799                 :            : 
     800                 :            : enum class SnapshotCompletionResult {
     801                 :            :     SUCCESS,
     802                 :            :     SKIPPED,
     803                 :            : 
     804                 :            :     // Expected assumeutxo configuration data is not found for the height of the
     805                 :            :     // base block.
     806                 :            :     MISSING_CHAINPARAMS,
     807                 :            : 
     808                 :            :     // Failed to generate UTXO statistics (to check UTXO set hash) for the background
     809                 :            :     // chainstate.
     810                 :            :     STATS_FAILED,
     811                 :            : 
     812                 :            :     // The UTXO set hash of the background validation chainstate does not match
     813                 :            :     // the one expected by assumeutxo chainparams.
     814                 :            :     HASH_MISMATCH,
     815                 :            : 
     816                 :            :     // The blockhash of the current tip of the background validation chainstate does
     817                 :            :     // not match the one expected by the snapshot chainstate.
     818                 :            :     BASE_BLOCKHASH_MISMATCH,
     819                 :            : };
     820                 :            : 
     821                 :            : /**
     822                 :            :  * Provides an interface for creating and interacting with one or two
     823                 :            :  * chainstates: an IBD chainstate generated by downloading blocks, and
     824                 :            :  * an optional snapshot chainstate loaded from a UTXO snapshot. Managed
     825                 :            :  * chainstates can be maintained at different heights simultaneously.
     826                 :            :  *
     827                 :            :  * This class provides abstractions that allow the retrieval of the current
     828                 :            :  * most-work chainstate ("Active") as well as chainstates which may be in
     829                 :            :  * background use to validate UTXO snapshots.
     830                 :            :  *
     831                 :            :  * Definitions:
     832                 :            :  *
     833                 :            :  * *IBD chainstate*: a chainstate whose current state has been "fully"
     834                 :            :  *   validated by the initial block download process.
     835                 :            :  *
     836                 :            :  * *Snapshot chainstate*: a chainstate populated by loading in an
     837                 :            :  *    assumeutxo UTXO snapshot.
     838                 :            :  *
     839                 :            :  * *Active chainstate*: the chainstate containing the current most-work
     840                 :            :  *    chain. Consulted by most parts of the system (net_processing,
     841                 :            :  *    wallet) as a reflection of the current chain and UTXO set.
     842                 :            :  *    This may either be an IBD chainstate or a snapshot chainstate.
     843                 :            :  *
     844                 :            :  * *Background IBD chainstate*: an IBD chainstate for which the
     845                 :            :  *    IBD process is happening in the background while use of the
     846                 :            :  *    active (snapshot) chainstate allows the rest of the system to function.
     847                 :            :  */
     848                 :            : class ChainstateManager
     849                 :            : {
     850                 :            : private:
     851                 :            :     //! The chainstate used under normal operation (i.e. "regular" IBD) or, if
     852                 :            :     //! a snapshot is in use, for background validation.
     853                 :            :     //!
     854                 :            :     //! Its contents (including on-disk data) will be deleted *upon shutdown*
     855                 :            :     //! after background validation of the snapshot has completed. We do not
     856                 :            :     //! free the chainstate contents immediately after it finishes validation
     857                 :            :     //! to cautiously avoid a case where some other part of the system is still
     858                 :            :     //! using this pointer (e.g. net_processing).
     859                 :            :     //!
     860                 :            :     //! Once this pointer is set to a corresponding chainstate, it will not
     861                 :            :     //! be reset until init.cpp:Shutdown().
     862                 :            :     //!
     863                 :            :     //! It is important for the pointer to not be deleted until shutdown,
     864                 :            :     //! because cs_main is not always held when the pointer is accessed, for
     865                 :            :     //! example when calling ActivateBestChain, so there's no way you could
     866                 :            :     //! prevent code from using the pointer while deleting it.
     867                 :            :     std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main);
     868                 :            : 
     869                 :            :     //! A chainstate initialized on the basis of a UTXO snapshot. If this is
     870                 :            :     //! non-null, it is always our active chainstate.
     871                 :            :     //!
     872                 :            :     //! Once this pointer is set to a corresponding chainstate, it will not
     873                 :            :     //! be reset until init.cpp:Shutdown().
     874                 :            :     //!
     875                 :            :     //! It is important for the pointer to not be deleted until shutdown,
     876                 :            :     //! because cs_main is not always held when the pointer is accessed, for
     877                 :            :     //! example when calling ActivateBestChain, so there's no way you could
     878                 :            :     //! prevent code from using the pointer while deleting it.
     879                 :            :     std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main);
     880                 :            : 
     881                 :            :     //! Points to either the ibd or snapshot chainstate; indicates our
     882                 :            :     //! most-work chain.
     883                 :            :     Chainstate* m_active_chainstate GUARDED_BY(::cs_main) {nullptr};
     884                 :            : 
     885                 :            :     CBlockIndex* m_best_invalid GUARDED_BY(::cs_main){nullptr};
     886                 :            : 
     887                 :            :     //! Internal helper for ActivateSnapshot().
     888                 :            :     [[nodiscard]] bool PopulateAndValidateSnapshot(
     889                 :            :         Chainstate& snapshot_chainstate,
     890                 :            :         AutoFile& coins_file,
     891                 :            :         const node::SnapshotMetadata& metadata);
     892                 :            : 
     893                 :            :     /**
     894                 :            :      * If a block header hasn't already been seen, call CheckBlockHeader on it, ensure
     895                 :            :      * that it doesn't descend from an invalid block, and then add it to m_block_index.
     896                 :            :      * Caller must set min_pow_checked=true in order to add a new header to the
     897                 :            :      * block index (permanent memory storage), indicating that the header is
     898                 :            :      * known to be part of a sufficiently high-work chain (anti-dos check).
     899                 :            :      */
     900                 :            :     bool AcceptBlockHeader(
     901                 :            :         const CBlockHeader& block,
     902                 :            :         BlockValidationState& state,
     903                 :            :         CBlockIndex** ppindex,
     904                 :            :         bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     905                 :            :     friend Chainstate;
     906                 :            : 
     907                 :            :     /** Most recent headers presync progress update, for rate-limiting. */
     908                 :            :     std::chrono::time_point<std::chrono::steady_clock> m_last_presync_update GUARDED_BY(::cs_main) {};
     909                 :            : 
     910                 :            :     std::array<ThresholdConditionCache, VERSIONBITS_NUM_BITS> m_warningcache GUARDED_BY(::cs_main);
     911                 :            : 
     912                 :            :     //! Return true if a chainstate is considered usable.
     913                 :            :     //!
     914                 :            :     //! This is false when a background validation chainstate has completed its
     915                 :            :     //! validation of an assumed-valid chainstate, or when a snapshot
     916                 :            :     //! chainstate has been found to be invalid.
     917                 :  127167358 :     bool IsUsable(const Chainstate* const cs) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
     918         [ +  + ]:  127167358 :         return cs && !cs->m_disabled;
     919                 :            :     }
     920                 :            : 
     921                 :            :     //! A queue for script verifications that have to be performed by worker threads.
     922                 :            :     CCheckQueue<CScriptCheck> m_script_check_queue;
     923                 :            : 
     924                 :            : public:
     925                 :            :     using Options = kernel::ChainstateManagerOpts;
     926                 :            : 
     927                 :            :     explicit ChainstateManager(const util::SignalInterrupt& interrupt, Options options, node::BlockManager::Options blockman_options);
     928                 :            : 
     929                 :            :     //! Function to restart active indexes; set dynamically to avoid a circular
     930                 :            :     //! dependency on `base/index.cpp`.
     931                 :            :     std::function<void()> restart_indexes = std::function<void()>();
     932                 :            : 
     933                 :    1668093 :     const CChainParams& GetParams() const { return m_options.chainparams; }
     934                 :    4243453 :     const Consensus::Params& GetConsensus() const { return m_options.chainparams.GetConsensus(); }
     935                 :     514221 :     bool ShouldCheckBlockIndex() const { return *Assert(m_options.check_block_index); }
     936                 :    1606534 :     const arith_uint256& MinimumChainWork() const { return *Assert(m_options.minimum_chain_work); }
     937                 :     212915 :     const uint256& AssumedValidBlock() const { return *Assert(m_options.assumed_valid_block); }
     938                 :     321423 :     kernel::Notifications& GetNotifications() const { return m_options.notifications; };
     939                 :            : 
     940                 :            :     /**
     941                 :            :      * Make various assertions about the state of the block index.
     942                 :            :      *
     943                 :            :      * By default this only executes fully when using the Regtest chain; see: m_options.check_block_index.
     944                 :            :      */
     945                 :            :     void CheckBlockIndex();
     946                 :            : 
     947                 :            :     /**
     948                 :            :      * Alias for ::cs_main.
     949                 :            :      * Should be used in new code to make it easier to make ::cs_main a member
     950                 :            :      * of this class.
     951                 :            :      * Generally, methods of this class should be annotated to require this
     952                 :            :      * mutex. This will make calling code more verbose, but also help to:
     953                 :            :      * - Clarify that the method will acquire a mutex that heavily affects
     954                 :            :      *   overall performance.
     955                 :            :      * - Force call sites to think how long they need to acquire the mutex to
     956                 :            :      *   get consistent results.
     957                 :            :      */
     958                 :     730509 :     RecursiveMutex& GetMutex() const LOCK_RETURNED(::cs_main) { return ::cs_main; }
     959                 :            : 
     960                 :            :     const util::SignalInterrupt& m_interrupt;
     961                 :            :     const Options m_options;
     962                 :            :     std::thread m_thread_load;
     963                 :            :     //! A single BlockManager instance is shared across each constructed
     964                 :            :     //! chainstate to avoid duplicating block metadata.
     965                 :            :     node::BlockManager m_blockman;
     966                 :            : 
     967                 :            :     /**
     968                 :            :      * Whether initial block download has ended and IsInitialBlockDownload
     969                 :            :      * should return false from now on.
     970                 :            :      *
     971                 :            :      * Mutable because we need to be able to mark IsInitialBlockDownload()
     972                 :            :      * const, which latches this for caching purposes.
     973                 :            :      */
     974                 :            :     mutable std::atomic<bool> m_cached_finished_ibd{false};
     975                 :            : 
     976                 :            :     /**
     977                 :            :      * Every received block is assigned a unique and increasing identifier, so we
     978                 :            :      * know which one to give priority in case of a fork.
     979                 :            :      */
     980                 :            :     /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
     981                 :            :     int32_t nBlockSequenceId GUARDED_BY(::cs_main) = 1;
     982                 :            :     /** Decreasing counter (used by subsequent preciousblock calls). */
     983                 :            :     int32_t nBlockReverseSequenceId = -1;
     984                 :            :     /** chainwork for the last block that preciousblock has been applied to. */
     985                 :            :     arith_uint256 nLastPreciousChainwork = 0;
     986                 :            : 
     987                 :            :     // Reset the memory-only sequence counters we use to track block arrival
     988                 :            :     // (used by tests to reset state)
     989                 :            :     void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
     990                 :            :     {
     991                 :            :         AssertLockHeld(::cs_main);
     992                 :            :         nBlockSequenceId = 1;
     993                 :            :         nBlockReverseSequenceId = -1;
     994                 :            :     }
     995                 :            : 
     996                 :            : 
     997                 :            :     /**
     998                 :            :      * In order to efficiently track invalidity of headers, we keep the set of
     999                 :            :      * blocks which we tried to connect and found to be invalid here (ie which
    1000                 :            :      * were set to BLOCK_FAILED_VALID since the last restart). We can then
    1001                 :            :      * walk this set and check if a new header is a descendant of something in
    1002                 :            :      * this set, preventing us from having to walk m_block_index when we try
    1003                 :            :      * to connect a bad block and fail.
    1004                 :            :      *
    1005                 :            :      * While this is more complicated than marking everything which descends
    1006                 :            :      * from an invalid block as invalid at the time we discover it to be
    1007                 :            :      * invalid, doing so would require walking all of m_block_index to find all
    1008                 :            :      * descendants. Since this case should be very rare, keeping track of all
    1009                 :            :      * BLOCK_FAILED_VALID blocks in a set should be just fine and work just as
    1010                 :            :      * well.
    1011                 :            :      *
    1012                 :            :      * Because we already walk m_block_index in height-order at startup, we go
    1013                 :            :      * ahead and mark descendants of invalid blocks as FAILED_CHILD at that time,
    1014                 :            :      * instead of putting things in this set.
    1015                 :            :      */
    1016                 :            :     std::set<CBlockIndex*> m_failed_blocks;
    1017                 :            : 
    1018                 :            :     /** Best header we've seen so far (used for getheaders queries' starting points). */
    1019                 :            :     CBlockIndex* m_best_header GUARDED_BY(::cs_main){nullptr};
    1020                 :            : 
    1021                 :            :     //! The total number of bytes available for us to use across all in-memory
    1022                 :            :     //! coins caches. This will be split somehow across chainstates.
    1023                 :            :     int64_t m_total_coinstip_cache{0};
    1024                 :            :     //
    1025                 :            :     //! The total number of bytes available for us to use across all leveldb
    1026                 :            :     //! coins databases. This will be split somehow across chainstates.
    1027                 :            :     int64_t m_total_coinsdb_cache{0};
    1028                 :            : 
    1029                 :            :     //! Instantiate a new chainstate.
    1030                 :            :     //!
    1031                 :            :     //! @param[in] mempool              The mempool to pass to the chainstate
    1032                 :            :     //                                  constructor
    1033                 :            :     Chainstate& InitializeChainstate(CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
    1034                 :            : 
    1035                 :            :     //! Get all chainstates currently being used.
    1036                 :            :     std::vector<Chainstate*> GetAll();
    1037                 :            : 
    1038                 :            :     //! Construct and activate a Chainstate on the basis of UTXO snapshot data.
    1039                 :            :     //!
    1040                 :            :     //! Steps:
    1041                 :            :     //!
    1042                 :            :     //! - Initialize an unused Chainstate.
    1043                 :            :     //! - Load its `CoinsViews` contents from `coins_file`.
    1044                 :            :     //! - Verify that the hash of the resulting coinsdb matches the expected hash
    1045                 :            :     //!   per assumeutxo chain parameters.
    1046                 :            :     //! - Wait for our headers chain to include the base block of the snapshot.
    1047                 :            :     //! - "Fast forward" the tip of the new chainstate to the base of the snapshot,
    1048                 :            :     //!   faking nTx* block index data along the way.
    1049                 :            :     //! - Move the new chainstate to `m_snapshot_chainstate` and make it our
    1050                 :            :     //!   ChainstateActive().
    1051                 :            :     [[nodiscard]] bool ActivateSnapshot(
    1052                 :            :         AutoFile& coins_file, const node::SnapshotMetadata& metadata, bool in_memory);
    1053                 :            : 
    1054                 :            :     //! Once the background validation chainstate has reached the height which
    1055                 :            :     //! is the base of the UTXO snapshot in use, compare its coins to ensure
    1056                 :            :     //! they match those expected by the snapshot.
    1057                 :            :     //!
    1058                 :            :     //! If the coins match (expected), then mark the validation chainstate for
    1059                 :            :     //! deletion and continue using the snapshot chainstate as active.
    1060                 :            :     //! Otherwise, revert to using the ibd chainstate and shutdown.
    1061                 :            :     SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
    1062                 :            : 
    1063                 :            :     //! Returns nullptr if no snapshot has been loaded.
    1064                 :            :     const CBlockIndex* GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
    1065                 :            : 
    1066                 :            :     //! The most-work chain.
    1067                 :            :     Chainstate& ActiveChainstate() const;
    1068                 :    3569964 :     CChain& ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChainstate().m_chain; }
    1069                 :     502713 :     int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Height(); }
    1070                 :     225724 :     CBlockIndex* ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Tip(); }
    1071                 :            : 
    1072                 :            :     //! The state of a background sync (for net processing)
    1073                 :     362708 :     bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
    1074         [ +  - ]:     362708 :         return IsUsable(m_snapshot_chainstate.get()) && IsUsable(m_ibd_chainstate.get());
    1075                 :            :     }
    1076                 :            : 
    1077                 :            :     //! The tip of the background sync chain
    1078                 :          0 :     const CBlockIndex* GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
    1079         [ #  # ]:          0 :         return BackgroundSyncInProgress() ? m_ibd_chainstate->m_chain.Tip() : nullptr;
    1080                 :            :     }
    1081                 :            : 
    1082                 :       2056 :     node::BlockMap& BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
    1083                 :            :     {
    1084                 :       2056 :         AssertLockHeld(::cs_main);
    1085                 :       2056 :         return m_blockman.m_block_index;
    1086                 :            :     }
    1087                 :            : 
    1088                 :            :     /**
    1089                 :            :      * Track versionbit status
    1090                 :            :      */
    1091                 :            :     mutable VersionBitsCache m_versionbitscache;
    1092                 :            : 
    1093                 :            :     //! @returns true if a snapshot-based chainstate is in use. Also implies
    1094                 :            :     //!          that a background validation chainstate is also in use.
    1095                 :            :     bool IsSnapshotActive() const;
    1096                 :            : 
    1097                 :            :     std::optional<uint256> SnapshotBlockhash() const;
    1098                 :            : 
    1099                 :            :     //! Is there a snapshot in use and has it been fully validated?
    1100                 :          0 :     bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
    1101                 :            :     {
    1102   [ #  #  #  # ]:          0 :         return m_snapshot_chainstate && m_ibd_chainstate && m_ibd_chainstate->m_disabled;
    1103                 :            :     }
    1104                 :            : 
    1105                 :            :     /** Check whether we are doing an initial block download (synchronizing from disk or network) */
    1106                 :            :     bool IsInitialBlockDownload() const;
    1107                 :            : 
    1108                 :            :     /**
    1109                 :            :      * Import blocks from an external file
    1110                 :            :      *
    1111                 :            :      * During reindexing, this function is called for each block file (datadir/blocks/blk?????.dat).
    1112                 :            :      * It reads all blocks contained in the given file and attempts to process them (add them to the
    1113                 :            :      * block index). The blocks may be out of order within each file and across files. Often this
    1114                 :            :      * function reads a block but finds that its parent hasn't been read yet, so the block can't be
    1115                 :            :      * processed yet. The function will add an entry to the blocks_with_unknown_parent map (which is
    1116                 :            :      * passed as an argument), so that when the block's parent is later read and processed, this
    1117                 :            :      * function can re-read the child block from disk and process it.
    1118                 :            :      *
    1119                 :            :      * Because a block's parent may be in a later file, not just later in the same file, the
    1120                 :            :      * blocks_with_unknown_parent map must be passed in and out with each call. It's a multimap,
    1121                 :            :      * rather than just a map, because multiple blocks may have the same parent (when chain splits
    1122                 :            :      * or stale blocks exist). It maps from parent-hash to child-disk-position.
    1123                 :            :      *
    1124                 :            :      * This function can also be used to read blocks from user-specified block files using the
    1125                 :            :      * -loadblock= option. There's no unknown-parent tracking, so the last two arguments are omitted.
    1126                 :            :      *
    1127                 :            :      *
    1128                 :            :      * @param[in]     file_in                       File containing blocks to read
    1129                 :            :      * @param[in]     dbp                           (optional) Disk block position (only for reindex)
    1130                 :            :      * @param[in,out] blocks_with_unknown_parent    (optional) Map of disk positions for blocks with
    1131                 :            :      *                                              unknown parent, key is parent block hash
    1132                 :            :      *                                              (only used for reindex)
    1133                 :            :      * */
    1134                 :            :     void LoadExternalBlockFile(
    1135                 :            :         AutoFile& file_in,
    1136                 :            :         FlatFilePos* dbp = nullptr,
    1137                 :            :         std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent = nullptr);
    1138                 :            : 
    1139                 :            :     /**
    1140                 :            :      * Process an incoming block. This only returns after the best known valid
    1141                 :            :      * block is made active. Note that it does not, however, guarantee that the
    1142                 :            :      * specific block passed to it has been checked for validity!
    1143                 :            :      *
    1144                 :            :      * If you want to *possibly* get feedback on whether block is valid, you must
    1145                 :            :      * install a CValidationInterface (see validationinterface.h) - this will have
    1146                 :            :      * its BlockChecked method called whenever *any* block completes validation.
    1147                 :            :      *
    1148                 :            :      * Note that we guarantee that either the proof-of-work is valid on block, or
    1149                 :            :      * (and possibly also) BlockChecked will have been called.
    1150                 :            :      *
    1151                 :            :      * May not be called in a validationinterface callback.
    1152                 :            :      *
    1153                 :            :      * @param[in]   block The block we want to process.
    1154                 :            :      * @param[in]   force_processing Process this block even if unrequested; used for non-network block sources.
    1155                 :            :      * @param[in]   min_pow_checked  True if proof-of-work anti-DoS checks have
    1156                 :            :      *                               been done by caller for headers chain
    1157                 :            :      *                               (note: only affects headers acceptance; if
    1158                 :            :      *                               block header is already present in block
    1159                 :            :      *                               index then this parameter has no effect)
    1160                 :            :      * @param[out]  new_block A boolean which is set to indicate if the block was first received via this call
    1161                 :            :      * @returns     If the block was processed, independently of block validity
    1162                 :            :      */
    1163                 :            :     bool ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block) LOCKS_EXCLUDED(cs_main);
    1164                 :            : 
    1165                 :            :     /**
    1166                 :            :      * Process incoming block headers.
    1167                 :            :      *
    1168                 :            :      * May not be called in a
    1169                 :            :      * validationinterface callback.
    1170                 :            :      *
    1171                 :            :      * @param[in]  block The block headers themselves
    1172                 :            :      * @param[in]  min_pow_checked  True if proof-of-work anti-DoS checks have been done by caller for headers chain
    1173                 :            :      * @param[out] state This may be set to an Error state if any error occurred processing them
    1174                 :            :      * @param[out] ppindex If set, the pointer will be set to point to the last new block index object for the given headers
    1175                 :            :      */
    1176                 :            :     bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
    1177                 :            : 
    1178                 :            :     /**
    1179                 :            :      * Sufficiently validate a block for disk storage (and store on disk).
    1180                 :            :      *
    1181                 :            :      * @param[in]   pblock          The block we want to process.
    1182                 :            :      * @param[in]   fRequested      Whether we requested this block from a
    1183                 :            :      *                              peer.
    1184                 :            :      * @param[in]   dbp             The location on disk, if we are importing
    1185                 :            :      *                              this block from prior storage.
    1186                 :            :      * @param[in]   min_pow_checked True if proof-of-work anti-DoS checks have
    1187                 :            :      *                              been done by caller for headers chain
    1188                 :            :      *
    1189                 :            :      * @param[out]  state       The state of the block validation.
    1190                 :            :      * @param[out]  ppindex     Optional return parameter to get the
    1191                 :            :      *                          CBlockIndex pointer for this block.
    1192                 :            :      * @param[out]  fNewBlock   Optional return parameter to indicate if the
    1193                 :            :      *                          block is new to our storage.
    1194                 :            :      *
    1195                 :            :      * @returns   False if the block or header is invalid, or if saving to disk fails (likely a fatal error); true otherwise.
    1196                 :            :      */
    1197                 :            :     bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
    1198                 :            : 
    1199                 :            :     void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
    1200                 :            : 
    1201                 :            :     /**
    1202                 :            :      * Try to add a transaction to the memory pool.
    1203                 :            :      *
    1204                 :            :      * @param[in]  tx              The transaction to submit for mempool acceptance.
    1205                 :            :      * @param[in]  test_accept     When true, run validation checks but don't submit to mempool.
    1206                 :            :      */
    1207                 :            :     [[nodiscard]] MempoolAcceptResult ProcessTransaction(const CTransactionRef& tx, bool test_accept=false)
    1208                 :            :         EXCLUSIVE_LOCKS_REQUIRED(cs_main);
    1209                 :            : 
    1210                 :            :     //! Load the block tree and coins database from disk, initializing state if we're running with -reindex
    1211                 :            :     bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
    1212                 :            : 
    1213                 :            :     //! Check to see if caches are out of balance and if so, call
    1214                 :            :     //! ResizeCoinsCaches() as needed.
    1215                 :            :     void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
    1216                 :            : 
    1217                 :            :     /** Update uncommitted block structures (currently: only the witness reserved value). This is safe for submitted blocks. */
    1218                 :            :     void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const;
    1219                 :            : 
    1220                 :            :     /** Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks). */
    1221                 :            :     std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const;
    1222                 :            : 
    1223                 :            :     /** This is used by net_processing to report pre-synchronization progress of headers, as
    1224                 :            :      *  headers are not yet fed to validation during that time, but validation is (for now)
    1225                 :            :      *  responsible for logging and signalling through NotifyHeaderTip, so it needs this
    1226                 :            :      *  information. */
    1227                 :            :     void ReportHeadersPresync(const arith_uint256& work, int64_t height, int64_t timestamp);
    1228                 :            : 
    1229                 :            :     //! When starting up, search the datadir for a chainstate based on a UTXO
    1230                 :            :     //! snapshot that is in the process of being validated.
    1231                 :            :     bool DetectSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
    1232                 :            : 
    1233                 :            :     void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
    1234                 :            : 
    1235                 :            :     //! Remove the snapshot-based chainstate and all on-disk artifacts.
    1236                 :            :     //! Used when reindex{-chainstate} is called during snapshot use.
    1237                 :            :     [[nodiscard]] bool DeleteSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
    1238                 :            : 
    1239                 :            :     //! Switch the active chainstate to one based on a UTXO snapshot that was loaded
    1240                 :            :     //! previously.
    1241                 :            :     Chainstate& ActivateExistingSnapshot(uint256 base_blockhash) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
    1242                 :            : 
    1243                 :            :     //! If we have validated a snapshot chain during this runtime, copy its
    1244                 :            :     //! chainstate directory over to the main `chainstate` location, completing
    1245                 :            :     //! validation of the snapshot.
    1246                 :            :     //!
    1247                 :            :     //! If the cleanup succeeds, the caller will need to ensure chainstates are
    1248                 :            :     //! reinitialized, since ResetChainstates() will be called before leveldb
    1249                 :            :     //! directories are moved or deleted.
    1250                 :            :     //!
    1251                 :            :     //! @sa node/chainstate:LoadChainstate()
    1252                 :            :     bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
    1253                 :            : 
    1254                 :            :     //! @returns the chainstate that indexes should consult when ensuring that an
    1255                 :            :     //!   index is synced with a chain where we can expect block index entries to have
    1256                 :            :     //!   BLOCK_HAVE_DATA beneath the tip.
    1257                 :            :     //!
    1258                 :            :     //!   In other words, give us the chainstate for which we can reasonably expect
    1259                 :            :     //!   that all blocks beneath the tip have been indexed. In practice this means
    1260                 :            :     //!   when using an assumed-valid chainstate based upon a snapshot, return only the
    1261                 :            :     //!   fully validated chain.
    1262                 :            :     Chainstate& GetChainstateForIndexing() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
    1263                 :            : 
    1264                 :            :     //! Return the [start, end] (inclusive) of block heights we can prune.
    1265                 :            :     //!
    1266                 :            :     //! start > end is possible, meaning no blocks can be pruned.
    1267                 :            :     std::pair<int, int> GetPruneRange(
    1268                 :            :         const Chainstate& chainstate, int last_height_can_prune) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
    1269                 :            : 
    1270                 :            :     //! Return the height of the base block of the snapshot in use, if one exists, else
    1271                 :            :     //! nullopt.
    1272                 :            :     std::optional<int> GetSnapshotBaseHeight() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
    1273                 :            : 
    1274                 :     423532 :     CCheckQueue<CScriptCheck>& GetCheckQueue() { return m_script_check_queue; }
    1275                 :            : 
    1276                 :            :     ~ChainstateManager();
    1277                 :            : };
    1278                 :            : 
    1279                 :            : /** Deployment* info via ChainstateManager */
    1280                 :            : template<typename DEP>
    1281                 :     881114 : bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const ChainstateManager& chainman, DEP dep)
    1282                 :            : {
    1283                 :     881114 :     return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
    1284                 :            : }
    1285                 :            : 
    1286                 :            : template<typename DEP>
    1287                 :    1433379 : bool DeploymentActiveAt(const CBlockIndex& index, const ChainstateManager& chainman, DEP dep)
    1288                 :            : {
    1289                 :    1433379 :     return DeploymentActiveAt(index, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
    1290                 :            : }
    1291                 :            : 
    1292                 :            : template<typename DEP>
    1293                 :         21 : bool DeploymentEnabled(const ChainstateManager& chainman, DEP dep)
    1294                 :            : {
    1295                 :         21 :     return DeploymentEnabled(chainman.GetConsensus(), dep);
    1296                 :            : }
    1297                 :            : 
    1298                 :            : /** Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30) */
    1299                 :            : bool IsBIP30Repeat(const CBlockIndex& block_index);
    1300                 :            : 
    1301                 :            : /** Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30) */
    1302                 :            : bool IsBIP30Unspendable(const CBlockIndex& block_index);
    1303                 :            : 
    1304                 :            : #endif // BITCOIN_VALIDATION_H

Generated by: LCOV version 1.16