LCOV - code coverage report
Current view: top level - src - validation.h (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 96.3 % 107 103
Test Date: 2025-12-19 05:13:39 Functions: 96.2 % 26 25
Branches: 39.8 % 1102 439

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

Generated by: LCOV version 2.0-1