LCOV - code coverage report
Current view: top level - src - validation.h (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 88.8 % 89 79
Test Date: 2024-12-02 12:23:29 Functions: 82.6 % 23 19
Branches: 24.8 % 656 163

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

Generated by: LCOV version 2.0-1