/ src / validation.cpp
validation.cpp
   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  #include <bitcoin-build-config.h> // IWYU pragma: keep
   7  
   8  #include <validation.h>
   9  
  10  #include <arith_uint256.h>
  11  #include <chain.h>
  12  #include <checkqueue.h>
  13  #include <clientversion.h>
  14  #include <consensus/amount.h>
  15  #include <consensus/consensus.h>
  16  #include <consensus/merkle.h>
  17  #include <consensus/tx_check.h>
  18  #include <consensus/tx_verify.h>
  19  #include <consensus/validation.h>
  20  #include <cuckoocache.h>
  21  #include <flatfile.h>
  22  #include <hash.h>
  23  #include <kernel/chainparams.h>
  24  #include <kernel/coinstats.h>
  25  #include <kernel/disconnected_transactions.h>
  26  #include <kernel/mempool_entry.h>
  27  #include <kernel/messagestartchars.h>
  28  #include <kernel/notifications_interface.h>
  29  #include <kernel/types.h>
  30  #include <kernel/warning.h>
  31  #include <logging/timer.h>
  32  #include <node/blockstorage.h>
  33  #include <node/utxo_snapshot.h>
  34  #include <policy/ephemeral_policy.h>
  35  #include <policy/policy.h>
  36  #include <policy/rbf.h>
  37  #include <policy/settings.h>
  38  #include <policy/truc_policy.h>
  39  #include <pow.h>
  40  #include <primitives/block.h>
  41  #include <primitives/transaction.h>
  42  #include <random.h>
  43  #include <script/script.h>
  44  #include <script/sigcache.h>
  45  #include <signet.h>
  46  #include <tinyformat.h>
  47  #include <txdb.h>
  48  #include <txmempool.h>
  49  #include <uint256.h>
  50  #include <undo.h>
  51  #include <util/check.h>
  52  #include <util/fs.h>
  53  #include <util/fs_helpers.h>
  54  #include <util/hasher.h>
  55  #include <util/log.h>
  56  #include <util/moneystr.h>
  57  #include <util/rbf.h>
  58  #include <util/result.h>
  59  #include <util/signalinterrupt.h>
  60  #include <util/strencodings.h>
  61  #include <util/string.h>
  62  #include <util/time.h>
  63  #include <util/trace.h>
  64  #include <util/translation.h>
  65  #include <validationinterface.h>
  66  
  67  #include <algorithm>
  68  #include <cassert>
  69  #include <chrono>
  70  #include <deque>
  71  #include <numeric>
  72  #include <optional>
  73  #include <ranges>
  74  #include <span>
  75  #include <string>
  76  #include <tuple>
  77  #include <utility>
  78  
  79  using kernel::CCoinsStats;
  80  using kernel::ChainstateRole;
  81  using kernel::CoinStatsHashType;
  82  using kernel::ComputeUTXOStats;
  83  using kernel::Notifications;
  84  
  85  using fsbridge::FopenFn;
  86  using node::BlockManager;
  87  using node::BlockMap;
  88  using node::CBlockIndexHeightOnlyComparator;
  89  using node::CBlockIndexWorkComparator;
  90  using node::SnapshotMetadata;
  91  
  92  /** Time window to wait between writing blocks/block index and chainstate to disk.
  93   *  Randomize writing time inside the window to prevent a situation where the
  94   *  network over time settles into a few cohorts of synchronized writers.
  95  */
  96  static constexpr auto DATABASE_WRITE_INTERVAL_MIN{50min};
  97  static constexpr auto DATABASE_WRITE_INTERVAL_MAX{70min};
  98  /** Maximum age of our tip for us to be considered current for fee estimation */
  99  static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE{3};
 100  const std::vector<std::string> CHECKLEVEL_DOC {
 101      "level 0 reads the blocks from disk",
 102      "level 1 verifies block validity",
 103      "level 2 verifies undo data",
 104      "level 3 checks disconnection of tip blocks",
 105      "level 4 tries to reconnect the blocks",
 106      "each level includes the checks of the previous levels",
 107  };
 108  /** The number of blocks to keep below the deepest prune lock.
 109   *  There is nothing special about this number. It is higher than what we
 110   *  expect to see in regular mainnet reorgs, but not so high that it would
 111   *  noticeably interfere with the pruning mechanism.
 112   * */
 113  static constexpr int PRUNE_LOCK_BUFFER{10};
 114  
 115  TRACEPOINT_SEMAPHORE(validation, block_connected);
 116  TRACEPOINT_SEMAPHORE(utxocache, flush);
 117  TRACEPOINT_SEMAPHORE(mempool, replaced);
 118  TRACEPOINT_SEMAPHORE(mempool, rejected);
 119  
 120  const CBlockIndex* Chainstate::FindForkInGlobalIndex(const CBlockLocator& locator) const
 121  {
 122      AssertLockHeld(cs_main);
 123  
 124      // Find the latest block common to locator and chain - we expect that
 125      // locator.vHave is sorted descending by height.
 126      for (const uint256& hash : locator.vHave) {
 127          const CBlockIndex* pindex{m_blockman.LookupBlockIndex(hash)};
 128          if (pindex) {
 129              if (m_chain.Contains(pindex)) {
 130                  return pindex;
 131              }
 132              if (pindex->GetAncestor(m_chain.Height()) == m_chain.Tip()) {
 133                  return m_chain.Tip();
 134              }
 135          }
 136      }
 137      return m_chain.Genesis();
 138  }
 139  
 140  bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
 141                         const CCoinsViewCache& inputs, script_verify_flags flags, bool cacheSigStore,
 142                         bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
 143                         ValidationCache& validation_cache,
 144                         std::vector<CScriptCheck>* pvChecks = nullptr)
 145                         EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 146  
 147  bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx)
 148  {
 149      AssertLockHeld(cs_main);
 150  
 151      // CheckFinalTxAtTip() uses active_chain_tip.Height()+1 to evaluate
 152      // nLockTime because when IsFinalTx() is called within
 153      // AcceptBlock(), the height of the block *being*
 154      // evaluated is what is used. Thus if we want to know if a
 155      // transaction can be part of the *next* block, we need to call
 156      // IsFinalTx() with one more than active_chain_tip.Height().
 157      const int nBlockHeight = active_chain_tip.nHeight + 1;
 158  
 159      // BIP113 requires that time-locked transactions have nLockTime set to
 160      // less than the median time of the previous block they're contained in.
 161      // When the next block is created its previous block will be the current
 162      // chain tip, so we use that to calculate the median time passed to
 163      // IsFinalTx().
 164      const int64_t nBlockTime{active_chain_tip.GetMedianTimePast()};
 165  
 166      return IsFinalTx(tx, nBlockHeight, nBlockTime);
 167  }
 168  
 169  namespace {
 170  /**
 171   * A helper which calculates heights of inputs of a given transaction.
 172   *
 173   * @param[in] tip    The current chain tip. If an input belongs to a mempool
 174   *                   transaction, we assume it will be confirmed in the next block.
 175   * @param[in] coins  Any CCoinsView that provides access to the relevant coins.
 176   * @param[in] tx     The transaction being evaluated.
 177   *
 178   * @returns A vector of input heights or nullopt, in case of an error.
 179   */
 180  std::optional<std::vector<int>> CalculatePrevHeights(
 181      const CBlockIndex& tip,
 182      const CCoinsView& coins,
 183      const CTransaction& tx)
 184  {
 185      std::vector<int> prev_heights;
 186      prev_heights.resize(tx.vin.size());
 187      for (size_t i = 0; i < tx.vin.size(); ++i) {
 188          if (auto coin{coins.GetCoin(tx.vin[i].prevout)}) {
 189              prev_heights[i] = coin->nHeight == MEMPOOL_HEIGHT
 190                                ? tip.nHeight + 1 // Assume all mempool transaction confirm in the next block.
 191                                : coin->nHeight;
 192          } else {
 193              LogInfo("ERROR: %s: Missing input %d in transaction \'%s\'\n", __func__, i, tx.GetHash().GetHex());
 194              return std::nullopt;
 195          }
 196      }
 197      return prev_heights;
 198  }
 199  } // namespace
 200  
 201  std::optional<LockPoints> CalculateLockPointsAtTip(
 202      CBlockIndex* tip,
 203      const CCoinsView& coins_view,
 204      const CTransaction& tx)
 205  {
 206      assert(tip);
 207  
 208      auto prev_heights{CalculatePrevHeights(*tip, coins_view, tx)};
 209      if (!prev_heights.has_value()) return std::nullopt;
 210  
 211      CBlockIndex next_tip;
 212      next_tip.pprev = tip;
 213      // When SequenceLocks() is called within ConnectBlock(), the height
 214      // of the block *being* evaluated is what is used.
 215      // Thus if we want to know if a transaction can be part of the
 216      // *next* block, we need to use one more than active_chainstate.m_chain.Height()
 217      next_tip.nHeight = tip->nHeight + 1;
 218      const auto [min_height, min_time] = CalculateSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, prev_heights.value(), next_tip);
 219  
 220      // Also store the hash of the block with the highest height of
 221      // all the blocks which have sequence locked prevouts.
 222      // This hash needs to still be on the chain
 223      // for these LockPoint calculations to be valid
 224      // Note: It is impossible to correctly calculate a maxInputBlock
 225      // if any of the sequence locked inputs depend on unconfirmed txs,
 226      // except in the special case where the relative lock time/height
 227      // is 0, which is equivalent to no sequence lock. Since we assume
 228      // input height of tip+1 for mempool txs and test the resulting
 229      // min_height and min_time from CalculateSequenceLocks against tip+1.
 230      int max_input_height{0};
 231      for (const int height : prev_heights.value()) {
 232          // Can ignore mempool inputs since we'll fail if they had non-zero locks
 233          if (height != next_tip.nHeight) {
 234              max_input_height = std::max(max_input_height, height);
 235          }
 236      }
 237  
 238      // tip->GetAncestor(max_input_height) should never return a nullptr
 239      // because max_input_height is always less than the tip height.
 240      // It would, however, be a bad bug to continue execution, since a
 241      // LockPoints object with the maxInputBlock member set to nullptr
 242      // signifies no relative lock time.
 243      return LockPoints{min_height, min_time, Assert(tip->GetAncestor(max_input_height))};
 244  }
 245  
 246  bool CheckSequenceLocksAtTip(CBlockIndex* tip,
 247                               const LockPoints& lock_points)
 248  {
 249      assert(tip != nullptr);
 250  
 251      CBlockIndex index;
 252      index.pprev = tip;
 253      // CheckSequenceLocksAtTip() uses active_chainstate.m_chain.Height()+1 to evaluate
 254      // height based locks because when SequenceLocks() is called within
 255      // ConnectBlock(), the height of the block *being*
 256      // evaluated is what is used.
 257      // Thus if we want to know if a transaction can be part of the
 258      // *next* block, we need to use one more than active_chainstate.m_chain.Height()
 259      index.nHeight = tip->nHeight + 1;
 260  
 261      return EvaluateSequenceLocks(index, {lock_points.height, lock_points.time});
 262  }
 263  
 264  static void LimitMempoolSize(CTxMemPool& pool, CCoinsViewCache& coins_cache)
 265      EXCLUSIVE_LOCKS_REQUIRED(::cs_main, pool.cs)
 266  {
 267      AssertLockHeld(::cs_main);
 268      AssertLockHeld(pool.cs);
 269      int expired = pool.Expire(GetTime<std::chrono::seconds>() - pool.m_opts.expiry);
 270      if (expired != 0) {
 271          LogDebug(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
 272      }
 273  
 274      std::vector<COutPoint> vNoSpendsRemaining;
 275      pool.TrimToSize(pool.m_opts.max_size_bytes, &vNoSpendsRemaining);
 276      for (const COutPoint& removed : vNoSpendsRemaining)
 277          coins_cache.Uncache(removed);
 278  }
 279  
 280  static bool IsCurrentForFeeEstimation(Chainstate& active_chainstate) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 281  {
 282      AssertLockHeld(cs_main);
 283      if (active_chainstate.m_chainman.IsInitialBlockDownload()) {
 284          return false;
 285      }
 286      if (active_chainstate.m_chain.Tip()->GetBlockTime() < count_seconds(GetTime<std::chrono::seconds>() - MAX_FEE_ESTIMATION_TIP_AGE))
 287          return false;
 288      if (active_chainstate.m_chain.Height() < active_chainstate.m_chainman.m_best_header->nHeight - 1) {
 289          return false;
 290      }
 291      return true;
 292  }
 293  
 294  void Chainstate::MaybeUpdateMempoolForReorg(
 295      DisconnectedBlockTransactions& disconnectpool,
 296      bool fAddToMempool)
 297  {
 298      if (!m_mempool) return;
 299  
 300      AssertLockHeld(cs_main);
 301      AssertLockHeld(m_mempool->cs);
 302      std::vector<Txid> vHashUpdate;
 303      {
 304          // disconnectpool is ordered so that the front is the most recently-confirmed
 305          // transaction (the last tx of the block at the tip) in the disconnected chain.
 306          // Iterate disconnectpool in reverse, so that we add transactions
 307          // back to the mempool starting with the earliest transaction that had
 308          // been previously seen in a block.
 309          const auto queuedTx = disconnectpool.take();
 310          auto it = queuedTx.rbegin();
 311          while (it != queuedTx.rend()) {
 312              // ignore validation errors in resurrected transactions
 313              if (!fAddToMempool || (*it)->IsCoinBase() ||
 314                  AcceptToMemoryPool(*this, *it, GetTime(),
 315                      /*bypass_limits=*/true, /*test_accept=*/false).m_result_type !=
 316                          MempoolAcceptResult::ResultType::VALID) {
 317                  // If the transaction doesn't make it in to the mempool, remove any
 318                  // transactions that depend on it (which would now be orphans).
 319                  m_mempool->removeRecursive(**it, MemPoolRemovalReason::REORG);
 320              } else if (m_mempool->exists((*it)->GetHash())) {
 321                  vHashUpdate.push_back((*it)->GetHash());
 322              }
 323              ++it;
 324          }
 325      }
 326  
 327      // AcceptToMemoryPool/addNewTransaction all assume that new mempool entries have
 328      // no in-mempool children, which is generally not true when adding
 329      // previously-confirmed transactions back to the mempool.
 330      // UpdateTransactionsFromBlock finds descendants of any transactions in
 331      // the disconnectpool that were added back and cleans up the mempool state.
 332      m_mempool->UpdateTransactionsFromBlock(vHashUpdate);
 333  
 334      // Predicate to use for filtering transactions in removeForReorg.
 335      // Checks whether the transaction is still final and, if it spends a coinbase output, mature.
 336      // Also updates valid entries' cached LockPoints if needed.
 337      // If false, the tx is still valid and its lockpoints are updated.
 338      // If true, the tx would be invalid in the next block; remove this entry and all of its descendants.
 339      // Note that TRUC rules are not applied here, so reorgs may cause violations of TRUC inheritance or
 340      // topology restrictions.
 341      const auto filter_final_and_mature = [&](CTxMemPool::txiter it)
 342          EXCLUSIVE_LOCKS_REQUIRED(m_mempool->cs, ::cs_main) {
 343          AssertLockHeld(m_mempool->cs);
 344          AssertLockHeld(::cs_main);
 345          const CTransaction& tx = it->GetTx();
 346  
 347          // The transaction must be final.
 348          if (!CheckFinalTxAtTip(*Assert(m_chain.Tip()), tx)) return true;
 349  
 350          const LockPoints& lp = it->GetLockPoints();
 351          // CheckSequenceLocksAtTip checks if the transaction will be final in the next block to be
 352          // created on top of the new chain.
 353          if (TestLockPointValidity(m_chain, lp)) {
 354              if (!CheckSequenceLocksAtTip(m_chain.Tip(), lp)) {
 355                  return true;
 356              }
 357          } else {
 358              const CCoinsViewMemPool view_mempool{&CoinsTip(), *m_mempool};
 359              const std::optional<LockPoints> new_lock_points{CalculateLockPointsAtTip(m_chain.Tip(), view_mempool, tx)};
 360              if (new_lock_points.has_value() && CheckSequenceLocksAtTip(m_chain.Tip(), *new_lock_points)) {
 361                  // Now update the mempool entry lockpoints as well.
 362                  it->UpdateLockPoints(*new_lock_points);
 363              } else {
 364                  return true;
 365              }
 366          }
 367  
 368          // If the transaction spends any coinbase outputs, it must be mature.
 369          if (it->GetSpendsCoinbase()) {
 370              for (const CTxIn& txin : tx.vin) {
 371                  if (m_mempool->exists(txin.prevout.hash)) continue;
 372                  const Coin& coin{CoinsTip().AccessCoin(txin.prevout)};
 373                  assert(!coin.IsSpent());
 374                  const auto mempool_spend_height{m_chain.Tip()->nHeight + 1};
 375                  if (coin.IsCoinBase() && mempool_spend_height - coin.nHeight < COINBASE_MATURITY) {
 376                      return true;
 377                  }
 378              }
 379          }
 380          // Transaction is still valid and cached LockPoints are updated.
 381          return false;
 382      };
 383  
 384      // We also need to remove any now-immature transactions
 385      m_mempool->removeForReorg(m_chain, filter_final_and_mature);
 386      // Re-limit mempool size, in case we added any transactions
 387      LimitMempoolSize(*m_mempool, this->CoinsTip());
 388  }
 389  
 390  /**
 391  * Checks to avoid mempool polluting consensus critical paths since cached
 392  * signature and script validity results will be reused if we validate this
 393  * transaction again during block validation.
 394  * */
 395  static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, TxValidationState& state,
 396                  const CCoinsViewCache& view, const CTxMemPool& pool,
 397                  script_verify_flags flags, PrecomputedTransactionData& txdata, CCoinsViewCache& coins_tip,
 398                  ValidationCache& validation_cache)
 399                  EXCLUSIVE_LOCKS_REQUIRED(cs_main, pool.cs)
 400  {
 401      AssertLockHeld(cs_main);
 402      AssertLockHeld(pool.cs);
 403  
 404      assert(!tx.IsCoinBase());
 405      for (const CTxIn& txin : tx.vin) {
 406          const Coin& coin = view.AccessCoin(txin.prevout);
 407  
 408          // This coin was checked in PreChecks and MemPoolAccept
 409          // has been holding cs_main since then.
 410          Assume(!coin.IsSpent());
 411          if (coin.IsSpent()) return false;
 412  
 413          // If the Coin is available, there are 2 possibilities:
 414          // it is available in our current ChainstateActive UTXO set,
 415          // or it's a UTXO provided by a transaction in our mempool.
 416          // Ensure the scriptPubKeys in Coins from CoinsView are correct.
 417          const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
 418          if (txFrom) {
 419              assert(txFrom->GetHash() == txin.prevout.hash);
 420              assert(txFrom->vout.size() > txin.prevout.n);
 421              assert(txFrom->vout[txin.prevout.n] == coin.out);
 422          } else {
 423              const Coin& coinFromUTXOSet = coins_tip.AccessCoin(txin.prevout);
 424              assert(!coinFromUTXOSet.IsSpent());
 425              assert(coinFromUTXOSet.out == coin.out);
 426          }
 427      }
 428  
 429      // Call CheckInputScripts() to cache signature and script validity against current tip consensus rules.
 430      return CheckInputScripts(tx, state, view, flags, /* cacheSigStore= */ true, /* cacheFullScriptStore= */ true, txdata, validation_cache);
 431  }
 432  
 433  namespace {
 434  
 435  class MemPoolAccept
 436  {
 437  public:
 438      explicit MemPoolAccept(CTxMemPool& mempool, Chainstate& active_chainstate) :
 439          m_pool(mempool),
 440          m_view(&m_dummy),
 441          m_viewmempool(&active_chainstate.CoinsTip(), m_pool),
 442          m_active_chainstate(active_chainstate)
 443      {
 444      }
 445  
 446      // We put the arguments we're handed into a struct, so we can pass them
 447      // around easier.
 448      struct ATMPArgs {
 449          const CChainParams& m_chainparams;
 450          const int64_t m_accept_time;
 451          const bool m_bypass_limits;
 452          /*
 453           * Return any outpoints which were not previously present in the coins
 454           * cache, but were added as a result of validating the tx for mempool
 455           * acceptance. This allows the caller to optionally remove the cache
 456           * additions if the associated transaction ends up being rejected by
 457           * the mempool.
 458           */
 459          std::vector<COutPoint>& m_coins_to_uncache;
 460          /** When true, the transaction or package will not be submitted to the mempool. */
 461          const bool m_test_accept;
 462          /** Whether we allow transactions to replace mempool transactions. If false,
 463           * any transaction spending the same inputs as a transaction in the mempool is considered
 464           * a conflict. */
 465          const bool m_allow_replacement;
 466          /** When true, allow sibling eviction. This only occurs in single transaction package settings. */
 467          const bool m_allow_sibling_eviction;
 468          /** Used to skip the LimitMempoolSize() call within AcceptSingleTransaction(). This should be used when multiple
 469           * AcceptSubPackage calls are expected and the mempool will be trimmed at the end of AcceptPackage(). */
 470          const bool m_package_submission;
 471          /** When true, use package feerates instead of individual transaction feerates for fee-based
 472           * policies such as mempool min fee and min relay fee.
 473           */
 474          const bool m_package_feerates;
 475          /** Used for local submission of transactions to catch "absurd" fees
 476           * due to fee miscalculation by wallets. std:nullopt implies unset, allowing any feerates.
 477           * Any individual transaction failing this check causes immediate failure.
 478           */
 479          const std::optional<CFeeRate> m_client_maxfeerate;
 480  
 481          /** Parameters for single transaction mempool validation. */
 482          static ATMPArgs SingleAccept(const CChainParams& chainparams, int64_t accept_time,
 483                                       bool bypass_limits, std::vector<COutPoint>& coins_to_uncache,
 484                                       bool test_accept) {
 485              return ATMPArgs{/*chainparams=*/ chainparams,
 486                              /*accept_time=*/ accept_time,
 487                              /*bypass_limits=*/ bypass_limits,
 488                              /*coins_to_uncache=*/ coins_to_uncache,
 489                              /*test_accept=*/ test_accept,
 490                              /*allow_replacement=*/ true,
 491                              /*allow_sibling_eviction=*/ true,
 492                              /*package_submission=*/ false,
 493                              /*package_feerates=*/ false,
 494                              /*client_maxfeerate=*/ {}, // checked by caller
 495              };
 496          }
 497  
 498          /** Parameters for test package mempool validation through testmempoolaccept. */
 499          static ATMPArgs PackageTestAccept(const CChainParams& chainparams, int64_t accept_time,
 500                                            std::vector<COutPoint>& coins_to_uncache) {
 501              return ATMPArgs{/*chainparams=*/ chainparams,
 502                              /*accept_time=*/ accept_time,
 503                              /*bypass_limits=*/ false,
 504                              /*coins_to_uncache=*/ coins_to_uncache,
 505                              /*test_accept=*/ true,
 506                              /*allow_replacement=*/ false,
 507                              /*allow_sibling_eviction=*/ false,
 508                              /*package_submission=*/ false, // not submitting to mempool
 509                              /*package_feerates=*/ false,
 510                              /*client_maxfeerate=*/ {}, // checked by caller
 511              };
 512          }
 513  
 514          /** Parameters for child-with-parents package validation. */
 515          static ATMPArgs PackageChildWithParents(const CChainParams& chainparams, int64_t accept_time,
 516                                                  std::vector<COutPoint>& coins_to_uncache, const std::optional<CFeeRate>& client_maxfeerate) {
 517              return ATMPArgs{/*chainparams=*/ chainparams,
 518                              /*accept_time=*/ accept_time,
 519                              /*bypass_limits=*/ false,
 520                              /*coins_to_uncache=*/ coins_to_uncache,
 521                              /*test_accept=*/ false,
 522                              /*allow_replacement=*/ true,
 523                              /*allow_sibling_eviction=*/ false,
 524                              /*package_submission=*/ true,
 525                              /*package_feerates=*/ true,
 526                              /*client_maxfeerate=*/ client_maxfeerate,
 527              };
 528          }
 529  
 530          /** Parameters for a single transaction within a package. */
 531          static ATMPArgs SingleInPackageAccept(const ATMPArgs& package_args) {
 532              return ATMPArgs{/*chainparams=*/ package_args.m_chainparams,
 533                              /*accept_time=*/ package_args.m_accept_time,
 534                              /*bypass_limits=*/ false,
 535                              /*coins_to_uncache=*/ package_args.m_coins_to_uncache,
 536                              /*test_accept=*/ package_args.m_test_accept,
 537                              /*allow_replacement=*/ true,
 538                              /*allow_sibling_eviction=*/ true,
 539                              /*package_submission=*/ true, // trim at the end of AcceptPackage()
 540                              /*package_feerates=*/ false, // only 1 transaction
 541                              /*client_maxfeerate=*/ package_args.m_client_maxfeerate,
 542              };
 543          }
 544  
 545      private:
 546          // Private ctor to avoid exposing details to clients and allowing the possibility of
 547          // mixing up the order of the arguments. Use static functions above instead.
 548          ATMPArgs(const CChainParams& chainparams,
 549                   int64_t accept_time,
 550                   bool bypass_limits,
 551                   std::vector<COutPoint>& coins_to_uncache,
 552                   bool test_accept,
 553                   bool allow_replacement,
 554                   bool allow_sibling_eviction,
 555                   bool package_submission,
 556                   bool package_feerates,
 557                   std::optional<CFeeRate> client_maxfeerate)
 558              : m_chainparams{chainparams},
 559                m_accept_time{accept_time},
 560                m_bypass_limits{bypass_limits},
 561                m_coins_to_uncache{coins_to_uncache},
 562                m_test_accept{test_accept},
 563                m_allow_replacement{allow_replacement},
 564                m_allow_sibling_eviction{allow_sibling_eviction},
 565                m_package_submission{package_submission},
 566                m_package_feerates{package_feerates},
 567                m_client_maxfeerate{client_maxfeerate}
 568          {
 569              // If we are using package feerates, we must be doing package submission.
 570              // It also means sibling eviction is not permitted.
 571              if (m_package_feerates) {
 572                  Assume(m_package_submission);
 573                  Assume(!m_allow_sibling_eviction);
 574              }
 575              if (m_allow_sibling_eviction) Assume(m_allow_replacement);
 576          }
 577      };
 578  
 579      /** Clean up all non-chainstate coins from m_view and m_viewmempool. */
 580      void CleanupTemporaryCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
 581  
 582      // Single transaction acceptance
 583      MempoolAcceptResult AcceptSingleTransactionAndCleanup(const CTransactionRef& ptx, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
 584          LOCK(m_pool.cs);
 585          MempoolAcceptResult result = AcceptSingleTransactionInternal(ptx, args);
 586          ClearSubPackageState();
 587          return result;
 588      }
 589      MempoolAcceptResult AcceptSingleTransactionInternal(const CTransactionRef& ptx, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
 590  
 591      /**
 592      * Multiple transaction acceptance. Transactions may or may not be interdependent, but must not
 593      * conflict with each other, and the transactions cannot already be in the mempool. Parents must
 594      * come before children if any dependencies exist.
 595      */
 596      PackageMempoolAcceptResult AcceptMultipleTransactionsAndCleanup(const std::vector<CTransactionRef>& txns, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
 597          LOCK(m_pool.cs);
 598          PackageMempoolAcceptResult result = AcceptMultipleTransactionsInternal(txns, args);
 599          ClearSubPackageState();
 600          return result;
 601      }
 602      PackageMempoolAcceptResult AcceptMultipleTransactionsInternal(const std::vector<CTransactionRef>& txns, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
 603  
 604      /**
 605       * Submission of a subpackage.
 606       * If subpackage size == 1, calls AcceptSingleTransaction() with adjusted ATMPArgs to
 607       * enable sibling eviction and creates a PackageMempoolAcceptResult
 608       * wrapping the result.
 609       *
 610       * If subpackage size > 1, calls AcceptMultipleTransactions() with the provided ATMPArgs.
 611       *
 612       * Also cleans up all non-chainstate coins from m_view at the end.
 613      */
 614      PackageMempoolAcceptResult AcceptSubPackage(const std::vector<CTransactionRef>& subpackage, ATMPArgs& args)
 615          EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
 616  
 617      /**
 618       * Package (more specific than just multiple transactions) acceptance. Package must be a child
 619       * with all of its unconfirmed parents, and topologically sorted.
 620       */
 621      PackageMempoolAcceptResult AcceptPackage(const Package& package, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
 622  
 623  private:
 624      // All the intermediate state that gets passed between the various levels
 625      // of checking a given transaction.
 626      struct Workspace {
 627          explicit Workspace(const CTransactionRef& ptx) : m_ptx(ptx), m_hash(ptx->GetHash()) {}
 628          /** Txids of mempool transactions that this transaction directly conflicts with or may
 629           * replace via sibling eviction. */
 630          std::set<Txid> m_conflicts;
 631          /** Iterators to mempool entries that this transaction directly conflicts with or may
 632           * replace via sibling eviction. */
 633          CTxMemPool::setEntries m_iters_conflicting;
 634          /** All mempool parents of this transaction. */
 635          std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> m_parents;
 636          /* Handle to the tx in the changeset */
 637          CTxMemPool::ChangeSet::TxHandle m_tx_handle;
 638          /** Whether RBF-related data structures (m_conflicts, m_iters_conflicting,
 639           * m_replaced_transactions) include a sibling in addition to txns with conflicting inputs. */
 640          bool m_sibling_eviction{false};
 641  
 642          /** Virtual size of the transaction as used by the mempool, calculated using serialized size
 643           * of the transaction and sigops. */
 644          int64_t m_vsize;
 645          /** Fees paid by this transaction: total input amounts subtracted by total output amounts. */
 646          CAmount m_base_fees;
 647          /** Base fees + any fee delta set by the user with prioritisetransaction. */
 648          CAmount m_modified_fees;
 649  
 650          /** If we're doing package validation (i.e. m_package_feerates=true), the "effective"
 651           * package feerate of this transaction is the total fees divided by the total size of
 652           * transactions (which may include its ancestors and/or descendants). */
 653          CFeeRate m_package_feerate{0};
 654  
 655          const CTransactionRef& m_ptx;
 656          /** Txid. */
 657          const Txid& m_hash;
 658          TxValidationState m_state;
 659          /** A temporary cache containing serialized transaction data for signature verification.
 660           * Reused across PolicyScriptChecks and ConsensusScriptChecks. */
 661          PrecomputedTransactionData m_precomputed_txdata;
 662      };
 663  
 664      // Run the policy checks on a given transaction, excluding any script checks.
 665      // Looks up inputs, calculates feerate, considers replacement, evaluates
 666      // package limits, etc. As this function can be invoked for "free" by a peer,
 667      // only tests that are fast should be done here (to avoid CPU DoS).
 668      bool PreChecks(ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
 669  
 670      // Run checks for mempool replace-by-fee, only used in AcceptSingleTransaction.
 671      bool ReplacementChecks(Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
 672  
 673      bool PackageRBFChecks(const std::vector<CTransactionRef>& txns,
 674                            std::vector<Workspace>& workspaces,
 675                            int64_t total_vsize,
 676                            PackageValidationState& package_state) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
 677  
 678      // Run the script checks using our policy flags. As this can be slow, we should
 679      // only invoke this on transactions that have otherwise passed policy checks.
 680      bool PolicyScriptChecks(const ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
 681  
 682      // Re-run the script checks, using consensus flags, and try to cache the
 683      // result in the scriptcache. This should be done after
 684      // PolicyScriptChecks(). This requires that all inputs either be in our
 685      // utxo set or in the mempool.
 686      bool ConsensusScriptChecks(const ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
 687  
 688      // Try to add the transaction to the mempool, removing any conflicts first.
 689      void FinalizeSubpackage(const ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
 690  
 691      // Submit all transactions to the mempool and call ConsensusScriptChecks to add to the script
 692      // cache - should only be called after successful validation of all transactions in the package.
 693      // Does not call LimitMempoolSize(), so mempool max_size_bytes may be temporarily exceeded.
 694      bool SubmitPackage(const ATMPArgs& args, std::vector<Workspace>& workspaces, PackageValidationState& package_state,
 695                         std::map<Wtxid, MempoolAcceptResult>& results)
 696           EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
 697  
 698      // Compare a package's feerate against minimum allowed.
 699      bool CheckFeeRate(size_t package_size, CAmount package_fee, TxValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_pool.cs)
 700      {
 701          AssertLockHeld(::cs_main);
 702          AssertLockHeld(m_pool.cs);
 703          CAmount mempoolRejectFee = m_pool.GetMinFee().GetFee(package_size);
 704          if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) {
 705              return state.Invalid(TxValidationResult::TX_RECONSIDERABLE, "mempool min fee not met", strprintf("%d < %d", package_fee, mempoolRejectFee));
 706          }
 707  
 708          if (package_fee < m_pool.m_opts.min_relay_feerate.GetFee(package_size)) {
 709              return state.Invalid(TxValidationResult::TX_RECONSIDERABLE, "min relay fee not met",
 710                                   strprintf("%d < %d", package_fee, m_pool.m_opts.min_relay_feerate.GetFee(package_size)));
 711          }
 712          return true;
 713      }
 714  
 715      ValidationCache& GetValidationCache()
 716      {
 717          return m_active_chainstate.m_chainman.m_validation_cache;
 718      }
 719  
 720  private:
 721      CTxMemPool& m_pool;
 722  
 723      /** Holds a cached view of available coins from the UTXO set, mempool, and artificial temporary coins (to enable package validation).
 724       * The view doesn't track whether a coin previously existed but has now been spent. We detect conflicts in other ways:
 725       * - conflicts within a transaction are checked in CheckTransaction (bad-txns-inputs-duplicate)
 726       * - conflicts within a package are checked in IsWellFormedPackage (conflict-in-package)
 727       * - conflicts with an existing mempool transaction are found in CTxMemPool::GetConflictTx and replacements are allowed
 728       * The temporary coins should persist between individual transaction checks so that package validation is possible,
 729       * but must be cleaned up when we finish validating a subpackage, whether accepted or rejected. The cache must also
 730       * be cleared when mempool contents change (when a changeset is applied or when the mempool trims itself) because it
 731       * can return cached coins that no longer exist in the backend. Use CleanupTemporaryCoins() anytime you are finished
 732       * with a SubPackageState or call LimitMempoolSize().
 733       */
 734      CCoinsViewCache m_view;
 735  
 736      // These are the two possible backends for m_view.
 737      /** When m_view is connected to m_viewmempool as its backend, it can pull coins from the mempool and from the UTXO
 738       * set. This is also where temporary coins are stored. */
 739      CCoinsViewMemPool m_viewmempool;
 740      /** When m_view is connected to m_dummy, it can no longer look up coins from the mempool or UTXO set (meaning no disk
 741       * operations happen), but can still return coins it accessed previously. Useful for keeping track of which coins
 742       * were pulled from disk. */
 743      CCoinsView m_dummy;
 744  
 745      Chainstate& m_active_chainstate;
 746  
 747      // Fields below are per *sub*package state and must be reset prior to subsequent
 748      // AcceptSingleTransaction and AcceptMultipleTransactions invocations
 749      struct SubPackageState {
 750          /** Aggregated modified fees of all transactions, used to calculate package feerate. */
 751          CAmount m_total_modified_fees{0};
 752          /** Aggregated virtual size of all transactions, used to calculate package feerate. */
 753          int64_t m_total_vsize{0};
 754  
 755          // RBF-related members
 756          /** Whether the transaction(s) would replace any mempool transactions and/or evict any siblings.
 757           * If so, RBF rules apply. */
 758          bool m_rbf{false};
 759          /** Mempool transactions that were replaced. */
 760          std::list<CTransactionRef> m_replaced_transactions;
 761          /* Changeset representing adding transactions and removing their conflicts. */
 762          std::unique_ptr<CTxMemPool::ChangeSet> m_changeset;
 763  
 764          /** Total modified fees of mempool transactions being replaced. */
 765          CAmount m_conflicting_fees{0};
 766          /** Total size (in virtual bytes) of mempool transactions being replaced. */
 767          size_t m_conflicting_size{0};
 768      };
 769  
 770      struct SubPackageState m_subpackage;
 771  
 772      /** Re-set sub-package state to not leak between evaluations */
 773      void ClearSubPackageState() EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs)
 774      {
 775          m_subpackage = SubPackageState{};
 776  
 777          // And clean coins while at it
 778          CleanupTemporaryCoins();
 779      }
 780  };
 781  
 782  bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
 783  {
 784      AssertLockHeld(cs_main);
 785      AssertLockHeld(m_pool.cs);
 786      const CTransactionRef& ptx = ws.m_ptx;
 787      const CTransaction& tx = *ws.m_ptx;
 788      const Txid& hash = ws.m_hash;
 789  
 790      // Copy/alias what we need out of args
 791      const int64_t nAcceptTime = args.m_accept_time;
 792      const bool bypass_limits = args.m_bypass_limits;
 793      std::vector<COutPoint>& coins_to_uncache = args.m_coins_to_uncache;
 794  
 795      // Alias what we need out of ws
 796      TxValidationState& state = ws.m_state;
 797  
 798      if (!CheckTransaction(tx, state)) {
 799          return false; // state filled in by CheckTransaction
 800      }
 801  
 802      // Coinbase is only valid in a block, not as a loose transaction
 803      if (tx.IsCoinBase())
 804          return state.Invalid(TxValidationResult::TX_CONSENSUS, "coinbase");
 805  
 806      // Rather not work on nonstandard transactions (unless -testnet/-regtest)
 807      std::string reason;
 808      if (m_pool.m_opts.require_standard && !IsStandardTx(tx, m_pool.m_opts.max_datacarrier_bytes, m_pool.m_opts.permit_bare_multisig, m_pool.m_opts.dust_relay_feerate, reason)) {
 809          return state.Invalid(TxValidationResult::TX_NOT_STANDARD, reason);
 810      }
 811  
 812      // Transactions smaller than 65 non-witness bytes are not relayed to mitigate CVE-2017-12842.
 813      if (::GetSerializeSize(TX_NO_WITNESS(tx)) < MIN_STANDARD_TX_NONWITNESS_SIZE)
 814          return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "tx-size-small");
 815  
 816      // Only accept nLockTime-using transactions that can be mined in the next
 817      // block; we don't want our mempool filled up with transactions that can't
 818      // be mined yet.
 819      if (!CheckFinalTxAtTip(*Assert(m_active_chainstate.m_chain.Tip()), tx)) {
 820          return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-final");
 821      }
 822  
 823      if (m_pool.exists(tx.GetWitnessHash())) {
 824          // Exact transaction already exists in the mempool.
 825          return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-in-mempool");
 826      } else if (m_pool.exists(tx.GetHash())) {
 827          // Transaction with the same non-witness data but different witness (same txid, different
 828          // wtxid) already exists in the mempool.
 829          return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-same-nonwitness-data-in-mempool");
 830      }
 831  
 832      // Check for conflicts with in-memory transactions
 833      for (const CTxIn &txin : tx.vin)
 834      {
 835          const CTransaction* ptxConflicting = m_pool.GetConflictTx(txin.prevout);
 836          if (ptxConflicting) {
 837              if (!args.m_allow_replacement) {
 838                  // Transaction conflicts with a mempool tx, but we're not allowing replacements in this context.
 839                  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "bip125-replacement-disallowed");
 840              }
 841              ws.m_conflicts.insert(ptxConflicting->GetHash());
 842          }
 843      }
 844  
 845      m_view.SetBackend(m_viewmempool);
 846  
 847      const CCoinsViewCache& coins_cache = m_active_chainstate.CoinsTip();
 848      // do all inputs exist?
 849      for (const CTxIn& txin : tx.vin) {
 850          if (!coins_cache.HaveCoinInCache(txin.prevout)) {
 851              coins_to_uncache.push_back(txin.prevout);
 852          }
 853  
 854          // Note: this call may add txin.prevout to the coins cache
 855          // (coins_cache.cacheCoins) by way of FetchCoin(). It should be removed
 856          // later (via coins_to_uncache) if this tx turns out to be invalid.
 857          if (!m_view.HaveCoin(txin.prevout)) {
 858              // Are inputs missing because we already have the tx?
 859              for (size_t out = 0; out < tx.vout.size(); out++) {
 860                  // Optimistically just do efficient check of cache for outputs
 861                  if (coins_cache.HaveCoinInCache(COutPoint(hash, out))) {
 862                      return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-known");
 863                  }
 864              }
 865              // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
 866              return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent");
 867          }
 868      }
 869  
 870      // This is const, but calls into the back end CoinsViews. The CCoinsViewDB at the bottom of the
 871      // hierarchy brings the best block into scope. See CCoinsViewDB::GetBestBlock().
 872      m_view.GetBestBlock();
 873  
 874      // we have all inputs cached now, so switch back to dummy (to protect
 875      // against bugs where we pull more inputs from disk that miss being added
 876      // to coins_to_uncache)
 877      m_view.SetBackend(m_dummy);
 878  
 879      assert(m_active_chainstate.m_blockman.LookupBlockIndex(m_view.GetBestBlock()) == m_active_chainstate.m_chain.Tip());
 880  
 881      // Only accept BIP68 sequence locked transactions that can be mined in the next
 882      // block; we don't want our mempool filled up with transactions that can't
 883      // be mined yet.
 884      // Pass in m_view which has all of the relevant inputs cached. Note that, since m_view's
 885      // backend was removed, it no longer pulls coins from the mempool.
 886      const std::optional<LockPoints> lock_points{CalculateLockPointsAtTip(m_active_chainstate.m_chain.Tip(), m_view, tx)};
 887      if (!lock_points.has_value() || !CheckSequenceLocksAtTip(m_active_chainstate.m_chain.Tip(), *lock_points)) {
 888          return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-BIP68-final");
 889      }
 890  
 891      // The mempool holds txs for the next block, so pass height+1 to CheckTxInputs
 892      if (!Consensus::CheckTxInputs(tx, state, m_view, m_active_chainstate.m_chain.Height() + 1, ws.m_base_fees)) {
 893          return false; // state filled in by CheckTxInputs
 894      }
 895  
 896      if (m_pool.m_opts.require_standard && !AreInputsStandard(tx, m_view)) {
 897          return state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs");
 898      }
 899  
 900      // Check for non-standard witnesses.
 901      if (tx.HasWitness() && m_pool.m_opts.require_standard && !IsWitnessStandard(tx, m_view)) {
 902          return state.Invalid(TxValidationResult::TX_WITNESS_MUTATED, "bad-witness-nonstandard");
 903      }
 904  
 905      int64_t nSigOpsCost = GetTransactionSigOpCost(tx, m_view, STANDARD_SCRIPT_VERIFY_FLAGS);
 906  
 907      // Keep track of transactions that spend a coinbase, which we re-scan
 908      // during reorgs to ensure COINBASE_MATURITY is still met.
 909      bool fSpendsCoinbase = false;
 910      for (const CTxIn &txin : tx.vin) {
 911          const Coin &coin = m_view.AccessCoin(txin.prevout);
 912          if (coin.IsCoinBase()) {
 913              fSpendsCoinbase = true;
 914              break;
 915          }
 916      }
 917  
 918      // Set entry_sequence to 0 when bypass_limits is used; this allows txs from a block
 919      // reorg to be marked earlier than any child txs that were already in the mempool.
 920      const uint64_t entry_sequence = bypass_limits ? 0 : m_pool.GetSequence();
 921      if (!m_subpackage.m_changeset) {
 922          m_subpackage.m_changeset = m_pool.GetChangeSet();
 923      }
 924      ws.m_tx_handle = m_subpackage.m_changeset->StageAddition(ptx, ws.m_base_fees, nAcceptTime, m_active_chainstate.m_chain.Height(), entry_sequence, fSpendsCoinbase, nSigOpsCost, lock_points.value());
 925  
 926      // ws.m_modified_fees includes any fee deltas from PrioritiseTransaction
 927      ws.m_modified_fees = ws.m_tx_handle->GetModifiedFee();
 928  
 929      ws.m_vsize = ws.m_tx_handle->GetTxSize();
 930  
 931      // Enforces 0-fee for dust transactions, no incentive to be mined alone
 932      if (m_pool.m_opts.require_standard) {
 933          if (!PreCheckEphemeralTx(*ptx, m_pool.m_opts.dust_relay_feerate, ws.m_base_fees, ws.m_modified_fees, state)) {
 934              return false; // state filled in by PreCheckEphemeralTx
 935          }
 936      }
 937  
 938      if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
 939          return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "bad-txns-too-many-sigops",
 940                  strprintf("%d", nSigOpsCost));
 941  
 942      // No individual transactions are allowed below the mempool min feerate except from disconnected
 943      // blocks and transactions in a package. Package transactions will be checked using package
 944      // feerate later.
 945      if (!bypass_limits && !args.m_package_feerates && !CheckFeeRate(ws.m_vsize, ws.m_modified_fees, state)) return false;
 946  
 947      ws.m_iters_conflicting = m_pool.GetIterSet(ws.m_conflicts);
 948  
 949      ws.m_parents = m_pool.GetParents(*ws.m_tx_handle);
 950  
 951      if (!args.m_bypass_limits) {
 952          // Perform the TRUC checks, using the in-mempool parents.
 953          if (const auto err{SingleTRUCChecks(m_pool, ws.m_ptx, ws.m_parents, ws.m_conflicts, ws.m_vsize)}) {
 954              // Single transaction contexts only.
 955              if (args.m_allow_sibling_eviction && err->second != nullptr) {
 956                  // We should only be considering where replacement is considered valid as well.
 957                  Assume(args.m_allow_replacement);
 958                  // Potential sibling eviction. Add the sibling to our list of mempool conflicts to be
 959                  // included in RBF checks.
 960                  ws.m_conflicts.insert(err->second->GetHash());
 961                  // Adding the sibling to m_iters_conflicting here means that it doesn't count towards
 962                  // RBF Carve Out above. This is correct, since removing to-be-replaced transactions from
 963                  // the descendant count is done separately in SingleTRUCChecks for TRUC transactions.
 964                  ws.m_iters_conflicting.insert(m_pool.GetIter(err->second->GetHash()).value());
 965                  ws.m_sibling_eviction = true;
 966                  // The sibling will be treated as part of the to-be-replaced set in ReplacementChecks.
 967                  // Note that we are not checking whether it opts in to replaceability via BIP125 or TRUC
 968                  // (which is normally done in PreChecks). However, the only way a TRUC transaction can
 969                  // have a non-TRUC and non-BIP125 descendant is due to a reorg.
 970              } else {
 971                  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "TRUC-violation", err->first);
 972              }
 973          }
 974      }
 975  
 976      // We want to detect conflicts in any tx in a package to trigger package RBF logic
 977      m_subpackage.m_rbf |= !ws.m_conflicts.empty();
 978      return true;
 979  }
 980  
 981  bool MemPoolAccept::ReplacementChecks(Workspace& ws)
 982  {
 983      AssertLockHeld(cs_main);
 984      AssertLockHeld(m_pool.cs);
 985  
 986      const CTransaction& tx = *ws.m_ptx;
 987      const Txid& hash = ws.m_hash;
 988      TxValidationState& state = ws.m_state;
 989  
 990      CFeeRate newFeeRate(ws.m_modified_fees, ws.m_vsize);
 991  
 992      CTxMemPool::setEntries all_conflicts;
 993  
 994      // Calculate all conflicting entries and enforce Rule #5.
 995      if (const auto err_string{GetEntriesForConflicts(tx, m_pool, ws.m_iters_conflicting, all_conflicts)}) {
 996          return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY,
 997                               strprintf("too many potential replacements%s", ws.m_sibling_eviction ? " (including sibling eviction)" : ""), *err_string);
 998      }
 999  
1000      // Check if it's economically rational to mine this transaction rather than the ones it
1001      // replaces and pays for its own relay fees. Enforce Rules #3 and #4.
1002      for (CTxMemPool::txiter it : all_conflicts) {
1003          m_subpackage.m_conflicting_fees += it->GetModifiedFee();
1004          m_subpackage.m_conflicting_size += it->GetTxSize();
1005      }
1006  
1007      if (const auto err_string{PaysForRBF(m_subpackage.m_conflicting_fees, ws.m_modified_fees, ws.m_vsize,
1008                                           m_pool.m_opts.incremental_relay_feerate, hash)}) {
1009          // Result may change in a package context
1010          return state.Invalid(TxValidationResult::TX_RECONSIDERABLE,
1011                               strprintf("insufficient fee%s", ws.m_sibling_eviction ? " (including sibling eviction)" : ""), *err_string);
1012      }
1013  
1014      // Add all the to-be-removed transactions to the changeset.
1015      for (auto it : all_conflicts) {
1016          m_subpackage.m_changeset->StageRemoval(it);
1017      }
1018  
1019      // Run cluster size limit checks and fail if we exceed them.
1020      if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1021          return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too-large-cluster", "");
1022      }
1023  
1024      if (const auto err_string{ImprovesFeerateDiagram(*m_subpackage.m_changeset)}) {
1025          // We checked above for the cluster size limits being respected, so a
1026          // failure here can only be due to an insufficient fee.
1027          Assume(err_string->first == DiagramCheckError::FAILURE);
1028          return state.Invalid(TxValidationResult::TX_RECONSIDERABLE, "replacement-failed", err_string->second);
1029      }
1030  
1031      return true;
1032  }
1033  
1034  bool MemPoolAccept::PackageRBFChecks(const std::vector<CTransactionRef>& txns,
1035                                       std::vector<Workspace>& workspaces,
1036                                       const int64_t total_vsize,
1037                                       PackageValidationState& package_state)
1038  {
1039      AssertLockHeld(cs_main);
1040      AssertLockHeld(m_pool.cs);
1041  
1042      assert(std::all_of(txns.cbegin(), txns.cend(), [this](const auto& tx)
1043                         { return !m_pool.exists(tx->GetHash());}));
1044  
1045      assert(txns.size() == workspaces.size());
1046  
1047      // We're in package RBF context; replacement proposal must be size 2
1048      if (workspaces.size() != 2 || !Assume(IsChildWithParents(txns))) {
1049          return package_state.Invalid(PackageValidationResult::PCKG_POLICY, "package RBF failed: package must be 1-parent-1-child");
1050      }
1051  
1052      // If the package has in-mempool parents, we won't consider a package RBF
1053      // since it would result in a cluster larger than 2.
1054      // N.B. To relax this constraint we will need to revisit how CCoinsViewMemPool::PackageAddTransaction
1055      // is being used inside AcceptMultipleTransactions to track available inputs while processing a package.
1056      // Specifically we would need to check that the ancestors of the new
1057      // transactions don't intersect with the set of transactions to be removed
1058      // due to RBF, which is not checked at all in the package acceptance
1059      // context.
1060      for (const auto& ws : workspaces) {
1061          if (!ws.m_parents.empty()) {
1062              return package_state.Invalid(PackageValidationResult::PCKG_POLICY, "package RBF failed: new transaction cannot have mempool ancestors");
1063          }
1064      }
1065  
1066      // Aggregate all conflicts into one set.
1067      CTxMemPool::setEntries direct_conflict_iters;
1068      for (Workspace& ws : workspaces) {
1069          // Aggregate all conflicts into one set.
1070          direct_conflict_iters.merge(ws.m_iters_conflicting);
1071      }
1072  
1073      const auto& parent_ws = workspaces[0];
1074      const auto& child_ws = workspaces[1];
1075  
1076      // Don't consider replacements that would cause us to remove a large number of mempool entries.
1077      // This limit is not increased in a package RBF. Use the aggregate number of transactions.
1078      CTxMemPool::setEntries all_conflicts;
1079      if (const auto err_string{GetEntriesForConflicts(*child_ws.m_ptx, m_pool, direct_conflict_iters,
1080                                                       all_conflicts)}) {
1081          return package_state.Invalid(PackageValidationResult::PCKG_POLICY,
1082                                       "package RBF failed: too many potential replacements", *err_string);
1083      }
1084  
1085      for (CTxMemPool::txiter it : all_conflicts) {
1086          m_subpackage.m_changeset->StageRemoval(it);
1087          m_subpackage.m_conflicting_fees += it->GetModifiedFee();
1088          m_subpackage.m_conflicting_size += it->GetTxSize();
1089      }
1090  
1091      // Use the child as the transaction for attributing errors to.
1092      const Txid& child_hash = child_ws.m_ptx->GetHash();
1093      if (const auto err_string{PaysForRBF(/*original_fees=*/m_subpackage.m_conflicting_fees,
1094                                           /*replacement_fees=*/m_subpackage.m_total_modified_fees,
1095                                           /*replacement_vsize=*/m_subpackage.m_total_vsize,
1096                                           m_pool.m_opts.incremental_relay_feerate, child_hash)}) {
1097          return package_state.Invalid(PackageValidationResult::PCKG_POLICY,
1098                                       "package RBF failed: insufficient anti-DoS fees", *err_string);
1099      }
1100  
1101      // Ensure this two transaction package is a "chunk" on its own; we don't want the child
1102      // to be only paying anti-DoS fees
1103      const CFeeRate parent_feerate(parent_ws.m_modified_fees, parent_ws.m_vsize);
1104      const CFeeRate package_feerate(m_subpackage.m_total_modified_fees, m_subpackage.m_total_vsize);
1105      if (package_feerate <= parent_feerate) {
1106          return package_state.Invalid(PackageValidationResult::PCKG_POLICY,
1107                                       "package RBF failed: package feerate is less than or equal to parent feerate",
1108                                       strprintf("package feerate %s <= parent feerate is %s", package_feerate.ToString(), parent_feerate.ToString()));
1109      }
1110  
1111      // Run cluster size limit checks and fail if we exceed them.
1112      if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1113          return package_state.Invalid(PackageValidationResult::PCKG_POLICY, "too-large-cluster", "");
1114      }
1115  
1116      // Check if it's economically rational to mine this package rather than the ones it replaces.
1117      if (const auto err_tup{ImprovesFeerateDiagram(*m_subpackage.m_changeset)}) {
1118          Assume(err_tup->first == DiagramCheckError::FAILURE);
1119          return package_state.Invalid(PackageValidationResult::PCKG_POLICY,
1120                                       "package RBF failed: " + err_tup.value().second, "");
1121      }
1122  
1123      LogDebug(BCLog::TXPACKAGES, "package RBF checks passed: parent %s (wtxid=%s), child %s (wtxid=%s), package hash (%s)\n",
1124          txns.front()->GetHash().ToString(), txns.front()->GetWitnessHash().ToString(),
1125          txns.back()->GetHash().ToString(), txns.back()->GetWitnessHash().ToString(),
1126          GetPackageHash(txns).ToString());
1127  
1128  
1129      return true;
1130  }
1131  
1132  bool MemPoolAccept::PolicyScriptChecks(const ATMPArgs& args, Workspace& ws)
1133  {
1134      AssertLockHeld(cs_main);
1135      AssertLockHeld(m_pool.cs);
1136      const CTransaction& tx = *ws.m_ptx;
1137      TxValidationState& state = ws.m_state;
1138  
1139      constexpr script_verify_flags scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
1140  
1141      // Check input scripts and signatures.
1142      // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1143      if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, false, ws.m_precomputed_txdata, GetValidationCache())) {
1144          // Detect a failure due to a missing witness so that p2p code can handle rejection caching appropriately.
1145          if (!tx.HasWitness() && SpendsNonAnchorWitnessProg(tx, m_view)) {
1146              state.Invalid(TxValidationResult::TX_WITNESS_STRIPPED,
1147                      state.GetRejectReason(), state.GetDebugMessage());
1148          }
1149          return false; // state filled in by CheckInputScripts
1150      }
1151  
1152      return true;
1153  }
1154  
1155  bool MemPoolAccept::ConsensusScriptChecks(const ATMPArgs& args, Workspace& ws)
1156  {
1157      AssertLockHeld(cs_main);
1158      AssertLockHeld(m_pool.cs);
1159      const CTransaction& tx = *ws.m_ptx;
1160      const Txid& hash = ws.m_hash;
1161      TxValidationState& state = ws.m_state;
1162  
1163      // Check again against the current block tip's script verification
1164      // flags to cache our script execution flags. This is, of course,
1165      // useless if the next block has different script flags from the
1166      // previous one, but because the cache tracks script flags for us it
1167      // will auto-invalidate and we'll just have a few blocks of extra
1168      // misses on soft-fork activation.
1169      //
1170      // This is also useful in case of bugs in the standard flags that cause
1171      // transactions to pass as valid when they're actually invalid. For
1172      // instance the STRICTENC flag was incorrectly allowing certain
1173      // CHECKSIG NOT scripts to pass, even though they were invalid.
1174      //
1175      // There is a similar check in CreateNewBlock() to prevent creating
1176      // invalid blocks (using TestBlockValidity), however allowing such
1177      // transactions into the mempool can be exploited as a DoS attack.
1178      script_verify_flags currentBlockScriptVerifyFlags{GetBlockScriptFlags(*m_active_chainstate.m_chain.Tip(), m_active_chainstate.m_chainman)};
1179      if (!CheckInputsFromMempoolAndCache(tx, state, m_view, m_pool, currentBlockScriptVerifyFlags,
1180                                          ws.m_precomputed_txdata, m_active_chainstate.CoinsTip(), GetValidationCache())) {
1181          LogError("BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not STANDARD flags %s, %s", hash.ToString(), state.ToString());
1182          return Assume(false);
1183      }
1184  
1185      return true;
1186  }
1187  
1188  void MemPoolAccept::FinalizeSubpackage(const ATMPArgs& args)
1189  {
1190      AssertLockHeld(cs_main);
1191      AssertLockHeld(m_pool.cs);
1192  
1193      if (!m_subpackage.m_changeset->GetRemovals().empty()) Assume(args.m_allow_replacement);
1194      // Remove conflicting transactions from the mempool
1195      for (CTxMemPool::txiter it : m_subpackage.m_changeset->GetRemovals())
1196      {
1197          std::string log_string = strprintf("replacing mempool tx %s (wtxid=%s, fees=%s, vsize=%s). ",
1198                                        it->GetTx().GetHash().ToString(),
1199                                        it->GetTx().GetWitnessHash().ToString(),
1200                                        it->GetFee(),
1201                                        it->GetTxSize());
1202          FeeFrac feerate{m_subpackage.m_total_modified_fees, int32_t(m_subpackage.m_total_vsize)};
1203          uint256 tx_or_package_hash{};
1204          const bool replaced_with_tx{m_subpackage.m_changeset->GetTxCount() == 1};
1205          if (replaced_with_tx) {
1206              const CTransaction& tx = m_subpackage.m_changeset->GetAddedTxn(0);
1207              tx_or_package_hash = tx.GetHash().ToUint256();
1208              log_string += strprintf("New tx %s (wtxid=%s, fees=%s, vsize=%s)",
1209                                      tx.GetHash().ToString(),
1210                                      tx.GetWitnessHash().ToString(),
1211                                      feerate.fee,
1212                                      feerate.size);
1213          } else {
1214              tx_or_package_hash = GetPackageHash(m_subpackage.m_changeset->GetAddedTxns());
1215              log_string += strprintf("New package %s with %lu txs, fees=%s, vsize=%s",
1216                                      tx_or_package_hash.ToString(),
1217                                      m_subpackage.m_changeset->GetTxCount(),
1218                                      feerate.fee,
1219                                      feerate.size);
1220  
1221          }
1222          LogDebug(BCLog::MEMPOOL, "%s\n", log_string);
1223          TRACEPOINT(mempool, replaced,
1224                  it->GetTx().GetHash().data(),
1225                  it->GetTxSize(),
1226                  it->GetFee(),
1227                  std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count(),
1228                  tx_or_package_hash.data(),
1229                  feerate.size,
1230                  feerate.fee,
1231                  replaced_with_tx
1232          );
1233          m_subpackage.m_replaced_transactions.push_back(it->GetSharedTx());
1234      }
1235      m_subpackage.m_changeset->Apply();
1236      m_subpackage.m_changeset.reset();
1237  }
1238  
1239  bool MemPoolAccept::SubmitPackage(const ATMPArgs& args, std::vector<Workspace>& workspaces,
1240                                    PackageValidationState& package_state,
1241                                    std::map<Wtxid, MempoolAcceptResult>& results)
1242  {
1243      AssertLockHeld(cs_main);
1244      AssertLockHeld(m_pool.cs);
1245      // Sanity check: none of the transactions should be in the mempool, and none of the transactions
1246      // should have a same-txid-different-witness equivalent in the mempool.
1247      assert(std::all_of(workspaces.cbegin(), workspaces.cend(), [this](const auto& ws) { return !m_pool.exists(ws.m_ptx->GetHash()); }));
1248  
1249      bool all_submitted = true;
1250      FinalizeSubpackage(args);
1251      // ConsensusScriptChecks adds to the script cache and is therefore consensus-critical;
1252      // CheckInputsFromMempoolAndCache asserts that transactions only spend coins available from the
1253      // mempool or UTXO set. Submit each transaction to the mempool immediately after calling
1254      // ConsensusScriptChecks to make the outputs available for subsequent transactions.
1255      for (Workspace& ws : workspaces) {
1256          if (!ConsensusScriptChecks(args, ws)) {
1257              results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1258              // Since PolicyScriptChecks() passed, this should never fail.
1259              Assume(false);
1260              all_submitted = false;
1261              package_state.Invalid(PackageValidationResult::PCKG_MEMPOOL_ERROR,
1262                                    strprintf("BUG! PolicyScriptChecks succeeded but ConsensusScriptChecks failed: %s",
1263                                              ws.m_ptx->GetHash().ToString()));
1264              // Remove the transaction from the mempool.
1265              if (!m_subpackage.m_changeset) m_subpackage.m_changeset = m_pool.GetChangeSet();
1266              m_subpackage.m_changeset->StageRemoval(m_pool.GetIter(ws.m_ptx->GetHash()).value());
1267          }
1268      }
1269      if (!all_submitted) {
1270          Assume(m_subpackage.m_changeset);
1271          // This code should be unreachable; it's here as belt-and-suspenders
1272          // to try to ensure we have no consensus-invalid transactions in the
1273          // mempool.
1274          m_subpackage.m_changeset->Apply();
1275          m_subpackage.m_changeset.reset();
1276          return false;
1277      }
1278  
1279      std::vector<Wtxid> all_package_wtxids;
1280      all_package_wtxids.reserve(workspaces.size());
1281      std::transform(workspaces.cbegin(), workspaces.cend(), std::back_inserter(all_package_wtxids),
1282                     [](const auto& ws) { return ws.m_ptx->GetWitnessHash(); });
1283  
1284      if (!m_subpackage.m_replaced_transactions.empty()) {
1285          LogDebug(BCLog::MEMPOOL, "replaced %u mempool transactions with %u new one(s) for %s additional fees, %d delta bytes\n",
1286                   m_subpackage.m_replaced_transactions.size(), workspaces.size(),
1287                   m_subpackage.m_total_modified_fees - m_subpackage.m_conflicting_fees,
1288                   m_subpackage.m_total_vsize - static_cast<int>(m_subpackage.m_conflicting_size));
1289      }
1290  
1291      // Add successful results. The returned results may change later if LimitMempoolSize() evicts them.
1292      for (Workspace& ws : workspaces) {
1293          auto iter = m_pool.GetIter(ws.m_ptx->GetHash());
1294          Assume(iter.has_value());
1295          const auto effective_feerate = args.m_package_feerates ? ws.m_package_feerate :
1296              CFeeRate{ws.m_modified_fees, static_cast<int32_t>(ws.m_vsize)};
1297          const auto effective_feerate_wtxids = args.m_package_feerates ? all_package_wtxids :
1298              std::vector<Wtxid>{ws.m_ptx->GetWitnessHash()};
1299          results.emplace(ws.m_ptx->GetWitnessHash(),
1300                          MempoolAcceptResult::Success(std::move(m_subpackage.m_replaced_transactions), ws.m_vsize,
1301                                           ws.m_base_fees, effective_feerate, effective_feerate_wtxids));
1302          if (!m_pool.m_opts.signals) continue;
1303          const CTransaction& tx = *ws.m_ptx;
1304          const auto tx_info = NewMempoolTransactionInfo(ws.m_ptx, ws.m_base_fees,
1305                                                         ws.m_vsize, (*iter)->GetHeight(),
1306                                                         args.m_bypass_limits, args.m_package_submission,
1307                                                         IsCurrentForFeeEstimation(m_active_chainstate),
1308                                                         m_pool.HasNoInputsOf(tx));
1309          m_pool.m_opts.signals->TransactionAddedToMempool(tx_info, m_pool.GetAndIncrementSequence());
1310      }
1311      return all_submitted;
1312  }
1313  
1314  MempoolAcceptResult MemPoolAccept::AcceptSingleTransactionInternal(const CTransactionRef& ptx, ATMPArgs& args)
1315  {
1316      AssertLockHeld(cs_main);
1317      AssertLockHeld(m_pool.cs);
1318  
1319      Workspace ws(ptx);
1320      const std::vector<Wtxid> single_wtxid{ws.m_ptx->GetWitnessHash()};
1321  
1322      if (!PreChecks(args, ws)) {
1323          if (ws.m_state.GetResult() == TxValidationResult::TX_RECONSIDERABLE) {
1324              // Failed for fee reasons. Provide the effective feerate and which tx was included.
1325              return MempoolAcceptResult::FeeFailure(ws.m_state, CFeeRate(ws.m_modified_fees, ws.m_vsize), single_wtxid);
1326          }
1327          return MempoolAcceptResult::Failure(ws.m_state);
1328      }
1329  
1330      if (m_subpackage.m_rbf && !ReplacementChecks(ws)) {
1331          if (ws.m_state.GetResult() == TxValidationResult::TX_RECONSIDERABLE) {
1332              // Failed for incentives-based fee reasons. Provide the effective feerate and which tx was included.
1333              return MempoolAcceptResult::FeeFailure(ws.m_state, CFeeRate(ws.m_modified_fees, ws.m_vsize), single_wtxid);
1334          }
1335          return MempoolAcceptResult::Failure(ws.m_state);
1336      }
1337  
1338      // Check if the transaction would exceed the cluster size limit.
1339      if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1340          ws.m_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too-large-cluster", "");
1341          return MempoolAcceptResult::Failure(ws.m_state);
1342      }
1343  
1344      // Now that we've verified the cluster limit is respected, we can perform
1345      // calculations involving the full ancestors of the tx.
1346      if (ws.m_conflicts.size()) {
1347          auto ancestors = m_subpackage.m_changeset->CalculateMemPoolAncestors(ws.m_tx_handle);
1348  
1349          // A transaction that spends outputs that would be replaced by it is invalid. Now
1350          // that we have the set of all ancestors we can detect this
1351          // pathological case by making sure ws.m_conflicts and this tx's ancestors don't
1352          // intersect.
1353          if (const auto err_string{EntriesAndTxidsDisjoint(ancestors, ws.m_conflicts, ptx->GetHash())}) {
1354              // We classify this as a consensus error because a transaction depending on something it
1355              // conflicts with would be inconsistent.
1356              ws.m_state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-spends-conflicting-tx", *err_string);
1357              return MempoolAcceptResult::Failure(ws.m_state);
1358          }
1359      }
1360  
1361      m_subpackage.m_total_vsize = ws.m_vsize;
1362      m_subpackage.m_total_modified_fees = ws.m_modified_fees;
1363  
1364      // Individual modified feerate exceeded caller-defined max; abort
1365      if (args.m_client_maxfeerate && CFeeRate(ws.m_modified_fees, ws.m_vsize) > args.m_client_maxfeerate.value()) {
1366          ws.m_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "max feerate exceeded", "");
1367          return MempoolAcceptResult::Failure(ws.m_state);
1368      }
1369  
1370      if (!args.m_bypass_limits && m_pool.m_opts.require_standard) {
1371          Wtxid dummy_wtxid;
1372          if (!CheckEphemeralSpends(/*package=*/{ptx}, m_pool.m_opts.dust_relay_feerate, m_pool, ws.m_state, dummy_wtxid)) {
1373              return MempoolAcceptResult::Failure(ws.m_state);
1374          }
1375      }
1376  
1377      // Perform the inexpensive checks first and avoid hashing and signature verification unless
1378      // those checks pass, to mitigate CPU exhaustion denial-of-service attacks.
1379      if (!PolicyScriptChecks(args, ws)) return MempoolAcceptResult::Failure(ws.m_state);
1380  
1381      if (!ConsensusScriptChecks(args, ws)) return MempoolAcceptResult::Failure(ws.m_state);
1382  
1383      const CFeeRate effective_feerate{ws.m_modified_fees, static_cast<int32_t>(ws.m_vsize)};
1384      // Tx was accepted, but not added
1385      if (args.m_test_accept) {
1386          return MempoolAcceptResult::Success(std::move(m_subpackage.m_replaced_transactions), ws.m_vsize,
1387                                              ws.m_base_fees, effective_feerate, single_wtxid);
1388      }
1389  
1390      FinalizeSubpackage(args);
1391  
1392      // Limit the mempool, if appropriate.
1393      if (!args.m_package_submission && !args.m_bypass_limits) {
1394          LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip());
1395          // If mempool contents change, then the m_view cache is dirty. Given this isn't a package
1396          // submission, we won't be using the cache anymore, but clear it anyway for clarity.
1397          CleanupTemporaryCoins();
1398  
1399          if (!m_pool.exists(ws.m_hash)) {
1400              // The tx no longer meets our (new) mempool minimum feerate but could be reconsidered in a package.
1401              ws.m_state.Invalid(TxValidationResult::TX_RECONSIDERABLE, "mempool full");
1402              return MempoolAcceptResult::FeeFailure(ws.m_state, CFeeRate(ws.m_modified_fees, ws.m_vsize), {ws.m_ptx->GetWitnessHash()});
1403          }
1404      }
1405  
1406      if (m_pool.m_opts.signals) {
1407          const CTransaction& tx = *ws.m_ptx;
1408          auto iter = m_pool.GetIter(tx.GetHash());
1409          Assume(iter.has_value());
1410          const auto tx_info = NewMempoolTransactionInfo(ws.m_ptx, ws.m_base_fees,
1411                                                         ws.m_vsize, (*iter)->GetHeight(),
1412                                                         args.m_bypass_limits, args.m_package_submission,
1413                                                         IsCurrentForFeeEstimation(m_active_chainstate),
1414                                                         m_pool.HasNoInputsOf(tx));
1415          m_pool.m_opts.signals->TransactionAddedToMempool(tx_info, m_pool.GetAndIncrementSequence());
1416      }
1417  
1418      if (!m_subpackage.m_replaced_transactions.empty()) {
1419          LogDebug(BCLog::MEMPOOL, "replaced %u mempool transactions with 1 new transaction for %s additional fees, %d delta bytes\n",
1420                   m_subpackage.m_replaced_transactions.size(),
1421                   ws.m_modified_fees - m_subpackage.m_conflicting_fees,
1422                   ws.m_vsize - static_cast<int>(m_subpackage.m_conflicting_size));
1423      }
1424  
1425      return MempoolAcceptResult::Success(std::move(m_subpackage.m_replaced_transactions), ws.m_vsize, ws.m_base_fees,
1426                                          effective_feerate, single_wtxid);
1427  }
1428  
1429  PackageMempoolAcceptResult MemPoolAccept::AcceptMultipleTransactionsInternal(const std::vector<CTransactionRef>& txns, ATMPArgs& args)
1430  {
1431      AssertLockHeld(cs_main);
1432      AssertLockHeld(m_pool.cs);
1433  
1434      // These context-free package limits can be done before taking the mempool lock.
1435      PackageValidationState package_state;
1436      if (!IsWellFormedPackage(txns, package_state)) return PackageMempoolAcceptResult(package_state, {});
1437  
1438      std::vector<Workspace> workspaces{};
1439      workspaces.reserve(txns.size());
1440      std::transform(txns.cbegin(), txns.cend(), std::back_inserter(workspaces),
1441                     [](const auto& tx) { return Workspace(tx); });
1442      std::map<Wtxid, MempoolAcceptResult> results;
1443  
1444      // Do all PreChecks first and fail fast to avoid running expensive script checks when unnecessary.
1445      for (Workspace& ws : workspaces) {
1446          if (!PreChecks(args, ws)) {
1447              package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1448              // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
1449              results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1450              return PackageMempoolAcceptResult(package_state, std::move(results));
1451          }
1452  
1453          // Individual modified feerate exceeded caller-defined max; abort
1454          // N.B. this doesn't take into account CPFPs. Chunk-aware validation may be more robust.
1455          if (args.m_client_maxfeerate && CFeeRate(ws.m_modified_fees, ws.m_vsize) > args.m_client_maxfeerate.value()) {
1456              // Need to set failure here both individually and at package level
1457              ws.m_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "max feerate exceeded", "");
1458              package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1459              // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
1460              results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1461              return PackageMempoolAcceptResult(package_state, std::move(results));
1462          }
1463  
1464          // Make the coins created by this transaction available for subsequent transactions in the
1465          // package to spend. If there are no conflicts within the package, no transaction can spend a coin
1466          // needed by another transaction in the package. We also need to make sure that no package
1467          // tx replaces (or replaces the ancestor of) the parent of another package tx. As long as we
1468          // check these two things, we don't need to track the coins spent.
1469          // If a package tx conflicts with a mempool tx, PackageRBFChecks() ensures later that any package RBF attempt
1470          // has *no* in-mempool ancestors, so we don't have to worry about subsequent transactions in
1471          // same package spending the same in-mempool outpoints. This needs to be revisited for general
1472          // package RBF.
1473          m_viewmempool.PackageAddTransaction(ws.m_ptx);
1474      }
1475  
1476      // At this point we have all in-mempool parents, and we know every transaction's vsize.
1477      // Run the TRUC checks on the package.
1478      for (Workspace& ws : workspaces) {
1479          if (auto err{PackageTRUCChecks(m_pool, ws.m_ptx, ws.m_vsize, txns, ws.m_parents)}) {
1480              package_state.Invalid(PackageValidationResult::PCKG_POLICY, "TRUC-violation", err.value());
1481              return PackageMempoolAcceptResult(package_state, {});
1482          }
1483      }
1484  
1485      // Transactions must meet two minimum feerates: the mempool minimum fee and min relay fee.
1486      // For transactions consisting of exactly one child and its parents, it suffices to use the
1487      // package feerate (total modified fees / total virtual size) to check this requirement.
1488      // Note that this is an aggregate feerate; this function has not checked that there are transactions
1489      // too low feerate to pay for themselves, or that the child transactions are higher feerate than
1490      // their parents. Using aggregate feerate may allow "parents pay for child" behavior and permit
1491      // a child that is below mempool minimum feerate. To avoid these behaviors, callers of
1492      // AcceptMultipleTransactions need to restrict txns topology (e.g. to ancestor sets) and check
1493      // the feerates of individuals and subsets.
1494      m_subpackage.m_total_vsize = std::accumulate(workspaces.cbegin(), workspaces.cend(), int64_t{0},
1495          [](int64_t sum, auto& ws) { return sum + ws.m_vsize; });
1496      m_subpackage.m_total_modified_fees = std::accumulate(workspaces.cbegin(), workspaces.cend(), CAmount{0},
1497          [](CAmount sum, auto& ws) { return sum + ws.m_modified_fees; });
1498      const CFeeRate package_feerate(m_subpackage.m_total_modified_fees, m_subpackage.m_total_vsize);
1499      std::vector<Wtxid> all_package_wtxids;
1500      all_package_wtxids.reserve(workspaces.size());
1501      std::transform(workspaces.cbegin(), workspaces.cend(), std::back_inserter(all_package_wtxids),
1502                     [](const auto& ws) { return ws.m_ptx->GetWitnessHash(); });
1503      TxValidationState placeholder_state;
1504      if (args.m_package_feerates &&
1505          !CheckFeeRate(m_subpackage.m_total_vsize, m_subpackage.m_total_modified_fees, placeholder_state)) {
1506          package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1507          return PackageMempoolAcceptResult(package_state, {{workspaces.back().m_ptx->GetWitnessHash(),
1508              MempoolAcceptResult::FeeFailure(placeholder_state, CFeeRate(m_subpackage.m_total_modified_fees, m_subpackage.m_total_vsize), all_package_wtxids)}});
1509      }
1510  
1511      // Apply package mempool RBF checks.
1512      if (m_subpackage.m_rbf && !PackageRBFChecks(txns, workspaces, m_subpackage.m_total_vsize, package_state)) {
1513          return PackageMempoolAcceptResult(package_state, std::move(results));
1514      }
1515  
1516      // Check if the transactions would exceed the cluster size limit.
1517      if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1518          package_state.Invalid(PackageValidationResult::PCKG_POLICY, "too-large-cluster", "");
1519          return PackageMempoolAcceptResult(package_state, std::move(results));
1520      }
1521  
1522      // Now that we've bounded the resulting possible ancestry count, check package for dust spends
1523      if (m_pool.m_opts.require_standard) {
1524          TxValidationState child_state;
1525          Wtxid child_wtxid;
1526          if (!CheckEphemeralSpends(txns, m_pool.m_opts.dust_relay_feerate, m_pool, child_state, child_wtxid)) {
1527              package_state.Invalid(PackageValidationResult::PCKG_TX, "unspent-dust");
1528              results.emplace(child_wtxid, MempoolAcceptResult::Failure(child_state));
1529              return PackageMempoolAcceptResult(package_state, std::move(results));
1530          }
1531      }
1532  
1533      for (Workspace& ws : workspaces) {
1534          ws.m_package_feerate = package_feerate;
1535          if (!PolicyScriptChecks(args, ws)) {
1536              // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
1537              package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1538              results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1539              return PackageMempoolAcceptResult(package_state, std::move(results));
1540          }
1541          if (args.m_test_accept) {
1542              const auto effective_feerate = args.m_package_feerates ? ws.m_package_feerate :
1543                  CFeeRate{ws.m_modified_fees, static_cast<int32_t>(ws.m_vsize)};
1544              const auto effective_feerate_wtxids = args.m_package_feerates ? all_package_wtxids :
1545                  std::vector<Wtxid>{ws.m_ptx->GetWitnessHash()};
1546              results.emplace(ws.m_ptx->GetWitnessHash(),
1547                              MempoolAcceptResult::Success(std::move(m_subpackage.m_replaced_transactions),
1548                                                           ws.m_vsize, ws.m_base_fees, effective_feerate,
1549                                                           effective_feerate_wtxids));
1550          }
1551      }
1552  
1553      if (args.m_test_accept) return PackageMempoolAcceptResult(package_state, std::move(results));
1554  
1555      if (!SubmitPackage(args, workspaces, package_state, results)) {
1556          // PackageValidationState filled in by SubmitPackage().
1557          return PackageMempoolAcceptResult(package_state, std::move(results));
1558      }
1559  
1560      return PackageMempoolAcceptResult(package_state, std::move(results));
1561  }
1562  
1563  void MemPoolAccept::CleanupTemporaryCoins()
1564  {
1565      // There are 3 kinds of coins in m_view:
1566      // (1) Temporary coins from the transactions in subpackage, constructed by m_viewmempool.
1567      // (2) Mempool coins from transactions in the mempool, constructed by m_viewmempool.
1568      // (3) Confirmed coins fetched from our current UTXO set.
1569      //
1570      // (1) Temporary coins need to be removed, regardless of whether the transaction was submitted.
1571      // If the transaction was submitted to the mempool, m_viewmempool will be able to fetch them from
1572      // there. If it wasn't submitted to mempool, it is incorrect to keep them - future calls may try
1573      // to spend those coins that don't actually exist.
1574      // (2) Mempool coins also need to be removed. If the mempool contents have changed as a result
1575      // of submitting or replacing transactions, coins previously fetched from mempool may now be
1576      // spent or nonexistent. Those coins need to be deleted from m_view.
1577      // (3) Confirmed coins don't need to be removed. The chainstate has not changed (we are
1578      // holding cs_main and no blocks have been processed) so the confirmed tx cannot disappear like
1579      // a mempool tx can. The coin may now be spent after we submitted a tx to mempool, but
1580      // we have already checked that the package does not have 2 transactions spending the same coin
1581      // and we check whether a mempool transaction spends conflicting coins (CTxMemPool::GetConflictTx).
1582      // Keeping them in m_view is an optimization to not re-fetch confirmed coins if we later look up
1583      // inputs for this transaction again.
1584      for (const auto& outpoint : m_viewmempool.GetNonBaseCoins()) {
1585          // In addition to resetting m_viewmempool, we also need to manually delete these coins from
1586          // m_view because it caches copies of the coins it fetched from m_viewmempool previously.
1587          m_view.Uncache(outpoint);
1588      }
1589      // This deletes the temporary and mempool coins.
1590      m_viewmempool.Reset();
1591  }
1592  
1593  PackageMempoolAcceptResult MemPoolAccept::AcceptSubPackage(const std::vector<CTransactionRef>& subpackage, ATMPArgs& args)
1594  {
1595      AssertLockHeld(::cs_main);
1596      AssertLockHeld(m_pool.cs);
1597      auto result = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_pool.cs) {
1598          if (subpackage.size() > 1) {
1599              return AcceptMultipleTransactionsInternal(subpackage, args);
1600          }
1601          const auto& tx = subpackage.front();
1602          ATMPArgs single_args = ATMPArgs::SingleInPackageAccept(args);
1603          const auto single_res = AcceptSingleTransactionInternal(tx, single_args);
1604          PackageValidationState package_state_wrapped;
1605          if (single_res.m_result_type != MempoolAcceptResult::ResultType::VALID) {
1606              package_state_wrapped.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1607          }
1608          return PackageMempoolAcceptResult(package_state_wrapped, {{tx->GetWitnessHash(), single_res}});
1609      }();
1610  
1611      // Clean up m_view and m_viewmempool so that other subpackage evaluations don't have access to
1612      // coins they shouldn't. Keep some coins in order to minimize re-fetching coins from the UTXO set.
1613      // Clean up package feerate and rbf calculations
1614      ClearSubPackageState();
1615  
1616      return result;
1617  }
1618  
1619  PackageMempoolAcceptResult MemPoolAccept::AcceptPackage(const Package& package, ATMPArgs& args)
1620  {
1621      Assert(!package.empty());
1622      AssertLockHeld(cs_main);
1623      // Used if returning a PackageMempoolAcceptResult directly from this function.
1624      PackageValidationState package_state_quit_early;
1625  
1626      // There are two topologies we are able to handle through this function:
1627      // (1) A single transaction
1628      // (2) A child-with-parents package.
1629      // Check that the package is well-formed. If it isn't, we won't try to validate any of the
1630      // transactions and thus won't return any MempoolAcceptResults, just a package-wide error.
1631  
1632      // Context-free package checks.
1633      if (!IsWellFormedPackage(package, package_state_quit_early)) {
1634          return PackageMempoolAcceptResult(package_state_quit_early, {});
1635      }
1636  
1637      if (package.size() > 1 && !IsChildWithParents(package)) {
1638          // All transactions in the package must be a parent of the last transaction. This is just an
1639          // opportunity for us to fail fast on a context-free check without taking the mempool lock.
1640          package_state_quit_early.Invalid(PackageValidationResult::PCKG_POLICY, "package-not-child-with-parents");
1641          return PackageMempoolAcceptResult(package_state_quit_early, {});
1642      }
1643  
1644      LOCK(m_pool.cs);
1645      // Stores results from which we will create the returned PackageMempoolAcceptResult.
1646      // A result may be changed if a mempool transaction is evicted later due to LimitMempoolSize().
1647      std::map<Wtxid, MempoolAcceptResult> results_final;
1648      // Results from individual validation which will be returned if no other result is available for
1649      // this transaction. "Nonfinal" because if a transaction fails by itself but succeeds later
1650      // (i.e. when evaluated with a fee-bumping child), the result in this map may be discarded.
1651      std::map<Wtxid, MempoolAcceptResult> individual_results_nonfinal;
1652      // Tracks whether we think package submission could result in successful entry to the mempool
1653      bool quit_early{false};
1654      std::vector<CTransactionRef> txns_package_eval;
1655      for (const auto& tx : package) {
1656          const auto& wtxid = tx->GetWitnessHash();
1657          const auto& txid = tx->GetHash();
1658          // There are 3 possibilities: already in mempool, same-txid-diff-wtxid already in mempool,
1659          // or not in mempool. An already confirmed tx is treated as one not in mempool, because all
1660          // we know is that the inputs aren't available.
1661          if (m_pool.exists(wtxid)) {
1662              // Exact transaction already exists in the mempool.
1663              // Node operators are free to set their mempool policies however they please, nodes may receive
1664              // transactions in different orders, and malicious counterparties may try to take advantage of
1665              // policy differences to pin or delay propagation of transactions. As such, it's possible for
1666              // some package transaction(s) to already be in the mempool, and we don't want to reject the
1667              // entire package in that case (as that could be a censorship vector). De-duplicate the
1668              // transactions that are already in the mempool, and only call AcceptMultipleTransactions() with
1669              // the new transactions. This ensures we don't double-count transaction counts and sizes when
1670              // checking ancestor/descendant limits, or double-count transaction fees for fee-related policy.
1671              const auto& entry{*Assert(m_pool.GetEntry(txid))};
1672              results_final.emplace(wtxid, MempoolAcceptResult::MempoolTx(entry.GetTxSize(), entry.GetFee()));
1673          } else if (m_pool.exists(txid)) {
1674              // Transaction with the same non-witness data but different witness (same txid,
1675              // different wtxid) already exists in the mempool.
1676              //
1677              // We don't allow replacement transactions right now, so just swap the package
1678              // transaction for the mempool one. Note that we are ignoring the validity of the
1679              // package transaction passed in.
1680              // TODO: allow witness replacement in packages.
1681              const auto& entry{*Assert(m_pool.GetEntry(txid))};
1682              // Provide the wtxid of the mempool tx so that the caller can look it up in the mempool.
1683              results_final.emplace(wtxid, MempoolAcceptResult::MempoolTxDifferentWitness(entry.GetTx().GetWitnessHash()));
1684          } else {
1685              // Transaction does not already exist in the mempool.
1686              // Try submitting the transaction on its own.
1687              const auto single_package_res = AcceptSubPackage({tx}, args);
1688              const auto& single_res = single_package_res.m_tx_results.at(wtxid);
1689              if (single_res.m_result_type == MempoolAcceptResult::ResultType::VALID) {
1690                  // The transaction succeeded on its own and is now in the mempool. Don't include it
1691                  // in package validation, because its fees should only be "used" once.
1692                  assert(m_pool.exists(wtxid));
1693                  results_final.emplace(wtxid, single_res);
1694              } else if (package.size() == 1 || // If there is only one transaction, no need to retry it "as a package"
1695                         (single_res.m_state.GetResult() != TxValidationResult::TX_RECONSIDERABLE &&
1696                         single_res.m_state.GetResult() != TxValidationResult::TX_MISSING_INPUTS)) {
1697                  // Package validation policy only differs from individual policy in its evaluation
1698                  // of feerate. For example, if a transaction fails here due to violation of a
1699                  // consensus rule, the result will not change when it is submitted as part of a
1700                  // package. To minimize the amount of repeated work, unless the transaction fails
1701                  // due to feerate or missing inputs (its parent is a previous transaction in the
1702                  // package that failed due to feerate), don't run package validation. Note that this
1703                  // decision might not make sense if different types of packages are allowed in the
1704                  // future.  Continue individually validating the rest of the transactions, because
1705                  // some of them may still be valid.
1706                  quit_early = true;
1707                  package_state_quit_early.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1708                  individual_results_nonfinal.emplace(wtxid, single_res);
1709              } else {
1710                  individual_results_nonfinal.emplace(wtxid, single_res);
1711                  txns_package_eval.push_back(tx);
1712              }
1713          }
1714      }
1715  
1716      auto multi_submission_result = quit_early || txns_package_eval.empty() ? PackageMempoolAcceptResult(package_state_quit_early, {}) :
1717          AcceptSubPackage(txns_package_eval, args);
1718      PackageValidationState& package_state_final = multi_submission_result.m_state;
1719  
1720      // This is invoked by AcceptSubPackage() already, so this is just here for
1721      // clarity (since it's not permitted to invoke LimitMempoolSize() while a
1722      // changeset is outstanding).
1723      ClearSubPackageState();
1724  
1725      // Make sure we haven't exceeded max mempool size.
1726      // Package transactions that were submitted to mempool or already in mempool may be evicted.
1727      // If mempool contents change, then the m_view cache is dirty. It has already been cleared above.
1728      LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip());
1729  
1730      for (const auto& tx : package) {
1731          const auto& wtxid = tx->GetWitnessHash();
1732          if (multi_submission_result.m_tx_results.contains(wtxid)) {
1733              // We shouldn't have re-submitted if the tx result was already in results_final.
1734              Assume(!results_final.contains(wtxid));
1735              // If it was submitted, check to see if the tx is still in the mempool. It could have
1736              // been evicted due to LimitMempoolSize() above.
1737              const auto& txresult = multi_submission_result.m_tx_results.at(wtxid);
1738              if (txresult.m_result_type == MempoolAcceptResult::ResultType::VALID && !m_pool.exists(wtxid)) {
1739                  package_state_final.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1740                  TxValidationState mempool_full_state;
1741                  mempool_full_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
1742                  results_final.emplace(wtxid, MempoolAcceptResult::Failure(mempool_full_state));
1743              } else {
1744                  results_final.emplace(wtxid, txresult);
1745              }
1746          } else if (const auto it{results_final.find(wtxid)}; it != results_final.end()) {
1747              // Already-in-mempool transaction. Check to see if it's still there, as it could have
1748              // been evicted when LimitMempoolSize() was called.
1749              Assume(it->second.m_result_type != MempoolAcceptResult::ResultType::INVALID);
1750              Assume(!individual_results_nonfinal.contains(wtxid));
1751              // Query by txid to include the same-txid-different-witness ones.
1752              if (!m_pool.exists(tx->GetHash())) {
1753                  package_state_final.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1754                  TxValidationState mempool_full_state;
1755                  mempool_full_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
1756                  // Replace the previous result.
1757                  results_final.erase(wtxid);
1758                  results_final.emplace(wtxid, MempoolAcceptResult::Failure(mempool_full_state));
1759              }
1760          } else if (const auto it{individual_results_nonfinal.find(wtxid)}; it != individual_results_nonfinal.end()) {
1761              Assume(it->second.m_result_type == MempoolAcceptResult::ResultType::INVALID);
1762              // Interesting result from previous processing.
1763              results_final.emplace(wtxid, it->second);
1764          }
1765      }
1766      Assume(results_final.size() == package.size());
1767      return PackageMempoolAcceptResult(package_state_final, std::move(results_final));
1768  }
1769  
1770  } // anon namespace
1771  
1772  MempoolAcceptResult AcceptToMemoryPool(Chainstate& active_chainstate, const CTransactionRef& tx,
1773                                         int64_t accept_time, bool bypass_limits, bool test_accept)
1774  {
1775      AssertLockHeld(::cs_main);
1776      const CChainParams& chainparams{active_chainstate.m_chainman.GetParams()};
1777      assert(active_chainstate.GetMempool() != nullptr);
1778      CTxMemPool& pool{*active_chainstate.GetMempool()};
1779  
1780      std::vector<COutPoint> coins_to_uncache;
1781  
1782      auto args = MemPoolAccept::ATMPArgs::SingleAccept(chainparams, accept_time, bypass_limits, coins_to_uncache, test_accept);
1783      MempoolAcceptResult result = MemPoolAccept(pool, active_chainstate).AcceptSingleTransactionAndCleanup(tx, args);
1784  
1785      if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {
1786          // Remove coins that were not present in the coins cache before calling
1787          // AcceptSingleTransaction(); this is to prevent memory DoS in case we receive a large
1788          // number of invalid transactions that attempt to overrun the in-memory coins cache
1789          // (`CCoinsViewCache::cacheCoins`).
1790  
1791          for (const COutPoint& hashTx : coins_to_uncache)
1792              active_chainstate.CoinsTip().Uncache(hashTx);
1793          TRACEPOINT(mempool, rejected,
1794                  tx->GetHash().data(),
1795                  result.m_state.GetRejectReason().c_str()
1796          );
1797      }
1798      // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
1799      BlockValidationState state_dummy;
1800      active_chainstate.FlushStateToDisk(state_dummy, FlushStateMode::PERIODIC);
1801      return result;
1802  }
1803  
1804  PackageMempoolAcceptResult ProcessNewPackage(Chainstate& active_chainstate, CTxMemPool& pool,
1805                                                     const Package& package, bool test_accept, const std::optional<CFeeRate>& client_maxfeerate)
1806  {
1807      AssertLockHeld(cs_main);
1808      assert(!package.empty());
1809      assert(std::all_of(package.cbegin(), package.cend(), [](const auto& tx){return tx != nullptr;}));
1810  
1811      std::vector<COutPoint> coins_to_uncache;
1812      const CChainParams& chainparams = active_chainstate.m_chainman.GetParams();
1813      auto result = [&]() EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
1814          AssertLockHeld(cs_main);
1815          if (test_accept) {
1816              auto args = MemPoolAccept::ATMPArgs::PackageTestAccept(chainparams, GetTime(), coins_to_uncache);
1817              return MemPoolAccept(pool, active_chainstate).AcceptMultipleTransactionsAndCleanup(package, args);
1818          } else {
1819              auto args = MemPoolAccept::ATMPArgs::PackageChildWithParents(chainparams, GetTime(), coins_to_uncache, client_maxfeerate);
1820              return MemPoolAccept(pool, active_chainstate).AcceptPackage(package, args);
1821          }
1822      }();
1823  
1824      // Uncache coins pertaining to transactions that were not submitted to the mempool.
1825      if (test_accept || result.m_state.IsInvalid()) {
1826          for (const COutPoint& hashTx : coins_to_uncache) {
1827              active_chainstate.CoinsTip().Uncache(hashTx);
1828          }
1829      }
1830      // Ensure the coins cache is still within limits.
1831      BlockValidationState state_dummy;
1832      active_chainstate.FlushStateToDisk(state_dummy, FlushStateMode::PERIODIC);
1833      return result;
1834  }
1835  
1836  CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1837  {
1838      int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1839      // Force block reward to zero when right shift is undefined.
1840      if (halvings >= 64)
1841          return 0;
1842  
1843      CAmount nSubsidy = 50 * COIN;
1844      // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1845      nSubsidy >>= halvings;
1846      return nSubsidy;
1847  }
1848  
1849  CoinsViews::CoinsViews(DBParams db_params, CoinsViewOptions options)
1850      : m_dbview{std::move(db_params), std::move(options)},
1851        m_catcherview(&m_dbview) {}
1852  
1853  void CoinsViews::InitCache()
1854  {
1855      AssertLockHeld(::cs_main);
1856      m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
1857      m_connect_block_view = std::make_unique<CoinsViewOverlay>(&*m_cacheview);
1858  }
1859  
1860  Chainstate::Chainstate(
1861      CTxMemPool* mempool,
1862      BlockManager& blockman,
1863      ChainstateManager& chainman,
1864      std::optional<uint256> from_snapshot_blockhash)
1865      : m_mempool(mempool),
1866        m_blockman(blockman),
1867        m_chainman(chainman),
1868        m_assumeutxo(from_snapshot_blockhash ? Assumeutxo::UNVALIDATED : Assumeutxo::VALIDATED),
1869        m_from_snapshot_blockhash(from_snapshot_blockhash) {}
1870  
1871  fs::path Chainstate::StoragePath() const
1872  {
1873      fs::path path{m_chainman.m_options.datadir / "chainstate"};
1874      if (m_from_snapshot_blockhash) {
1875          path += node::SNAPSHOT_CHAINSTATE_SUFFIX;
1876      }
1877      return path;
1878  }
1879  
1880  const CBlockIndex* Chainstate::SnapshotBase() const
1881  {
1882      if (!m_from_snapshot_blockhash) return nullptr;
1883      if (!m_cached_snapshot_base) m_cached_snapshot_base = Assert(m_chainman.m_blockman.LookupBlockIndex(*m_from_snapshot_blockhash));
1884      return m_cached_snapshot_base;
1885  }
1886  
1887  const CBlockIndex* Chainstate::TargetBlock() const
1888  {
1889      if (!m_target_blockhash) return nullptr;
1890      if (!m_cached_target_block) m_cached_target_block = Assert(m_chainman.m_blockman.LookupBlockIndex(*m_target_blockhash));
1891      return m_cached_target_block;
1892  }
1893  
1894  void Chainstate::SetTargetBlock(CBlockIndex* block)
1895  {
1896      if (block) {
1897          m_target_blockhash = block->GetBlockHash();
1898      } else {
1899          m_target_blockhash.reset();
1900      }
1901      m_cached_target_block = block;
1902  }
1903  
1904  void Chainstate::SetTargetBlockHash(uint256 block_hash)
1905  {
1906      m_target_blockhash = block_hash;
1907      m_cached_target_block = nullptr;
1908  }
1909  
1910  void Chainstate::InitCoinsDB(
1911      size_t cache_size_bytes,
1912      bool in_memory,
1913      bool should_wipe)
1914  {
1915      m_coins_views = std::make_unique<CoinsViews>(
1916          DBParams{
1917              .path = StoragePath(),
1918              .cache_bytes = cache_size_bytes,
1919              .memory_only = in_memory,
1920              .wipe_data = should_wipe,
1921              .obfuscate = true,
1922              .options = m_chainman.m_options.coins_db},
1923          m_chainman.m_options.coins_view);
1924  
1925      m_coinsdb_cache_size_bytes = cache_size_bytes;
1926  }
1927  
1928  void Chainstate::InitCoinsCache(size_t cache_size_bytes)
1929  {
1930      AssertLockHeld(::cs_main);
1931      assert(m_coins_views != nullptr);
1932      m_coinstip_cache_size_bytes = cache_size_bytes;
1933      m_coins_views->InitCache();
1934  }
1935  
1936  // Lock-free: depends on `m_cached_is_ibd`, which is latched by `UpdateIBDStatus()`.
1937  bool ChainstateManager::IsInitialBlockDownload() const noexcept
1938  {
1939      return m_cached_is_ibd.load(std::memory_order_relaxed);
1940  }
1941  
1942  void Chainstate::CheckForkWarningConditions()
1943  {
1944      AssertLockHeld(cs_main);
1945  
1946      if (this->GetRole().historical) {
1947          return;
1948      }
1949  
1950      if (m_chainman.m_best_invalid && m_chainman.m_best_invalid->nChainWork > m_chain.Tip()->nChainWork + (GetBlockProof(*m_chain.Tip()) * 6)) {
1951          LogWarning("Found invalid chain more than 6 blocks longer than our best chain. This could be due to database corruption or consensus incompatibility with peers.");
1952          m_chainman.GetNotifications().warningSet(
1953              kernel::Warning::LARGE_WORK_INVALID_CHAIN,
1954              _("Warning: Found invalid chain more than 6 blocks longer than our best chain. This could be due to database corruption or consensus incompatibility with peers."));
1955      } else {
1956          m_chainman.GetNotifications().warningUnset(kernel::Warning::LARGE_WORK_INVALID_CHAIN);
1957      }
1958  }
1959  
1960  // Called both upon regular invalid block discovery *and* InvalidateBlock
1961  void Chainstate::InvalidChainFound(CBlockIndex* pindexNew)
1962  {
1963      AssertLockHeld(cs_main);
1964      if (!m_chainman.m_best_invalid || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork) {
1965          m_chainman.m_best_invalid = pindexNew;
1966      }
1967      SetBlockFailureFlags(pindexNew);
1968      if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindexNew->nHeight) == pindexNew) {
1969          m_chainman.RecalculateBestHeader();
1970      }
1971  
1972      LogInfo("%s: invalid block=%s  height=%d  log2_work=%f  date=%s\n", __func__,
1973        pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1974        log(pindexNew->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(pindexNew->GetBlockTime()));
1975      CBlockIndex *tip = m_chain.Tip();
1976      assert (tip);
1977      LogInfo("%s:  current best=%s  height=%d  log2_work=%f  date=%s\n", __func__,
1978        tip->GetBlockHash().ToString(), m_chain.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1979        FormatISO8601DateTime(tip->GetBlockTime()));
1980      CheckForkWarningConditions();
1981  }
1982  
1983  // Same as InvalidChainFound, above, except not called directly from InvalidateBlock,
1984  // which does its own setBlockIndexCandidates management.
1985  void Chainstate::InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state)
1986  {
1987      AssertLockHeld(cs_main);
1988      if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
1989          pindex->nStatus |= BLOCK_FAILED_VALID;
1990          m_blockman.m_dirty_blockindex.insert(pindex);
1991          setBlockIndexCandidates.erase(pindex);
1992          InvalidChainFound(pindex);
1993      }
1994  }
1995  
1996  void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1997  {
1998      // mark inputs spent
1999      if (!tx.IsCoinBase()) {
2000          txundo.vprevout.reserve(tx.vin.size());
2001          for (const CTxIn &txin : tx.vin) {
2002              txundo.vprevout.emplace_back();
2003              bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
2004              assert(is_spent);
2005          }
2006      }
2007      // add outputs
2008      AddCoins(inputs, tx, nHeight);
2009  }
2010  
2011  std::optional<std::pair<ScriptError, std::string>> CScriptCheck::operator()() {
2012      const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
2013      const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
2014      ScriptError error{SCRIPT_ERR_UNKNOWN_ERROR};
2015      if (VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, m_flags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *m_signature_cache, *txdata), &error)) {
2016          return std::nullopt;
2017      } else {
2018          auto debug_str = strprintf("input %i of %s (wtxid %s), spending %s:%i", nIn, ptxTo->GetHash().ToString(), ptxTo->GetWitnessHash().ToString(), ptxTo->vin[nIn].prevout.hash.ToString(), ptxTo->vin[nIn].prevout.n);
2019          return std::make_pair(error, std::move(debug_str));
2020      }
2021  }
2022  
2023  ValidationCache::ValidationCache(const size_t script_execution_cache_bytes, const size_t signature_cache_bytes)
2024      : m_signature_cache{signature_cache_bytes}
2025  {
2026      // Setup the salted hasher
2027      uint256 nonce = GetRandHash();
2028      // We want the nonce to be 64 bytes long to force the hasher to process
2029      // this chunk, which makes later hash computations more efficient. We
2030      // just write our 32-byte entropy twice to fill the 64 bytes.
2031      m_script_execution_cache_hasher.Write(nonce.begin(), 32);
2032      m_script_execution_cache_hasher.Write(nonce.begin(), 32);
2033  
2034      const auto [num_elems, approx_size_bytes] = m_script_execution_cache.setup_bytes(script_execution_cache_bytes);
2035      LogInfo("Using %zu MiB out of %zu MiB requested for script execution cache, able to store %zu elements",
2036                approx_size_bytes >> 20, script_execution_cache_bytes >> 20, num_elems);
2037  }
2038  
2039  /**
2040   * Check whether all of this transaction's input scripts succeed.
2041   *
2042   * This involves ECDSA signature checks so can be computationally intensive. This function should
2043   * only be called after the cheap sanity checks in CheckTxInputs passed.
2044   *
2045   * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
2046   * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
2047   * not pushed onto pvChecks/run.
2048   *
2049   * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
2050   * which are matched. This is useful for checking blocks where we will likely never need the cache
2051   * entry again.
2052   *
2053   * Note that we may set state.reason to NOT_STANDARD for extra soft-fork flags in flags, block-checking
2054   * callers should probably reset it to CONSENSUS in such cases.
2055   *
2056   * Non-static (and redeclared) in src/test/txvalidationcache_tests.cpp
2057   */
2058  bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
2059                         const CCoinsViewCache& inputs, script_verify_flags flags, bool cacheSigStore,
2060                         bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
2061                         ValidationCache& validation_cache,
2062                         std::vector<CScriptCheck>* pvChecks)
2063  {
2064      if (tx.IsCoinBase()) return true;
2065  
2066      if (pvChecks) {
2067          pvChecks->reserve(tx.vin.size());
2068      }
2069  
2070      // First check if script executions have been cached with the same
2071      // flags. Note that this assumes that the inputs provided are
2072      // correct (ie that the transaction hash which is in tx's prevouts
2073      // properly commits to the scriptPubKey in the inputs view of that
2074      // transaction).
2075      uint256 hashCacheEntry;
2076      CSHA256 hasher = validation_cache.ScriptExecutionCacheHasher();
2077      hasher.Write(UCharCast(tx.GetWitnessHash().begin()), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
2078      AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
2079      if (validation_cache.m_script_execution_cache.contains(hashCacheEntry, !cacheFullScriptStore)) {
2080          return true;
2081      }
2082  
2083      if (!txdata.m_spent_outputs_ready) {
2084          std::vector<CTxOut> spent_outputs;
2085          spent_outputs.reserve(tx.vin.size());
2086  
2087          for (const auto& txin : tx.vin) {
2088              const COutPoint& prevout = txin.prevout;
2089              const Coin& coin = inputs.AccessCoin(prevout);
2090              assert(!coin.IsSpent());
2091              spent_outputs.emplace_back(coin.out);
2092          }
2093          txdata.Init(tx, std::move(spent_outputs));
2094      }
2095      assert(txdata.m_spent_outputs.size() == tx.vin.size());
2096  
2097      for (unsigned int i = 0; i < tx.vin.size(); i++) {
2098  
2099          // We very carefully only pass in things to CScriptCheck which
2100          // are clearly committed to by tx' witness hash. This provides
2101          // a sanity check that our caching is not introducing consensus
2102          // failures through additional data in, eg, the coins being
2103          // spent being checked as a part of CScriptCheck.
2104  
2105          // Verify signature
2106          CScriptCheck check(txdata.m_spent_outputs[i], tx, validation_cache.m_signature_cache, i, flags, cacheSigStore, &txdata);
2107          if (pvChecks) {
2108              pvChecks->emplace_back(std::move(check));
2109          } else if (auto result = check(); result.has_value()) {
2110              // Tx failures never trigger disconnections/bans.
2111              // This is so that network splits aren't triggered
2112              // either due to non-consensus relay policies (such as
2113              // non-standard DER encodings or non-null dummy
2114              // arguments) or due to new consensus rules introduced in
2115              // soft forks.
2116              if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
2117                  return state.Invalid(TxValidationResult::TX_NOT_STANDARD, strprintf("mempool-script-verify-flag-failed (%s)", ScriptErrorString(result->first)), result->second);
2118              } else {
2119                  return state.Invalid(TxValidationResult::TX_CONSENSUS, strprintf("block-script-verify-flag-failed (%s)", ScriptErrorString(result->first)), result->second);
2120              }
2121          }
2122      }
2123  
2124      if (cacheFullScriptStore && !pvChecks) {
2125          // We executed all of the provided scripts, and were told to
2126          // cache the result. Do so now.
2127          validation_cache.m_script_execution_cache.insert(hashCacheEntry);
2128      }
2129  
2130      return true;
2131  }
2132  
2133  bool FatalError(Notifications& notifications, BlockValidationState& state, const bilingual_str& message)
2134  {
2135      notifications.fatalError(message);
2136      return state.Error(message.original);
2137  }
2138  
2139  /**
2140   * Restore the UTXO in a Coin at a given COutPoint
2141   * @param undo The Coin to be restored.
2142   * @param view The coins view to which to apply the changes.
2143   * @param out The out point that corresponds to the tx input.
2144   * @return A DisconnectResult as an int
2145   */
2146  int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
2147  {
2148      bool fClean = true;
2149  
2150      if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
2151  
2152      if (undo.nHeight == 0) {
2153          // Missing undo metadata (height and coinbase). Older versions included this
2154          // information only in undo records for the last spend of a transactions'
2155          // outputs. This implies that it must be present for some other output of the same tx.
2156          const Coin& alternate = AccessByTxid(view, out.hash);
2157          if (!alternate.IsSpent()) {
2158              undo.nHeight = alternate.nHeight;
2159              undo.fCoinBase = alternate.fCoinBase;
2160          } else {
2161              return DISCONNECT_FAILED; // adding output for transaction without known metadata
2162          }
2163      }
2164      // If the coin already exists as an unspent coin in the cache, then the
2165      // possible_overwrite parameter to AddCoin must be set to true. We have
2166      // already checked whether an unspent coin exists above using HaveCoin, so
2167      // we don't need to guess. When fClean is false, an unspent coin already
2168      // existed and it is an overwrite.
2169      view.AddCoin(out, std::move(undo), !fClean);
2170  
2171      return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
2172  }
2173  
2174  /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
2175   *  When FAILED is returned, view is left in an indeterminate state. */
2176  DisconnectResult Chainstate::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
2177  {
2178      AssertLockHeld(::cs_main);
2179      bool fClean = true;
2180  
2181      CBlockUndo blockUndo;
2182      if (!m_blockman.ReadBlockUndo(blockUndo, *pindex)) {
2183          LogError("DisconnectBlock(): failure reading undo data\n");
2184          return DISCONNECT_FAILED;
2185      }
2186  
2187      if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
2188          LogError("DisconnectBlock(): block and undo data inconsistent\n");
2189          return DISCONNECT_FAILED;
2190      }
2191  
2192      // Ignore blocks that contain transactions which are 'overwritten' by later transactions,
2193      // unless those are already completely spent.
2194      // See https://github.com/bitcoin/bitcoin/issues/22596 for additional information.
2195      // Note: the blocks specified here are different than the ones used in ConnectBlock because DisconnectBlock
2196      // unwinds the blocks in reverse. As a result, the inconsistency is not discovered until the earlier
2197      // blocks with the duplicate coinbase transactions are disconnected.
2198      bool fEnforceBIP30 = !((pindex->nHeight==91722 && pindex->GetBlockHash() == uint256{"00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"}) ||
2199                             (pindex->nHeight==91812 && pindex->GetBlockHash() == uint256{"00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"}));
2200  
2201      // undo transactions in reverse order
2202      for (int i = block.vtx.size() - 1; i >= 0; i--) {
2203          const CTransaction &tx = *(block.vtx[i]);
2204          Txid hash = tx.GetHash();
2205          bool is_coinbase = tx.IsCoinBase();
2206          bool is_bip30_exception = (is_coinbase && !fEnforceBIP30);
2207  
2208          // Check that all outputs are available and match the outputs in the block itself
2209          // exactly.
2210          for (size_t o = 0; o < tx.vout.size(); o++) {
2211              if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
2212                  COutPoint out(hash, o);
2213                  Coin coin;
2214                  bool is_spent = view.SpendCoin(out, &coin);
2215                  if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
2216                      if (!is_bip30_exception) {
2217                          fClean = false; // transaction output mismatch
2218                      }
2219                  }
2220              }
2221          }
2222  
2223          // restore inputs
2224          if (i > 0) { // not coinbases
2225              CTxUndo &txundo = blockUndo.vtxundo[i-1];
2226              if (txundo.vprevout.size() != tx.vin.size()) {
2227                  LogError("DisconnectBlock(): transaction and undo data inconsistent\n");
2228                  return DISCONNECT_FAILED;
2229              }
2230              for (unsigned int j = tx.vin.size(); j > 0;) {
2231                  --j;
2232                  const COutPoint& out = tx.vin[j].prevout;
2233                  int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
2234                  if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
2235                  fClean = fClean && res != DISCONNECT_UNCLEAN;
2236              }
2237              // At this point, all of txundo.vprevout should have been moved out.
2238          }
2239      }
2240  
2241      // move best block pointer to prevout block
2242      view.SetBestBlock(pindex->pprev->GetBlockHash());
2243  
2244      return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
2245  }
2246  
2247  script_verify_flags GetBlockScriptFlags(const CBlockIndex& block_index, const ChainstateManager& chainman)
2248  {
2249      const Consensus::Params& consensusparams = chainman.GetConsensus();
2250  
2251      // BIP16 didn't become active until Apr 1 2012 (on mainnet, and
2252      // retroactively applied to testnet)
2253      // However, only one historical block violated the P2SH rules (on both
2254      // mainnet and testnet).
2255      // Similarly, only one historical block violated the TAPROOT rules on
2256      // mainnet.
2257      // For simplicity, always leave P2SH+WITNESS+TAPROOT on except for the two
2258      // violating blocks.
2259      script_verify_flags flags{SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_TAPROOT};
2260      const auto it{consensusparams.script_flag_exceptions.find(*Assert(block_index.phashBlock))};
2261      if (it != consensusparams.script_flag_exceptions.end()) {
2262          flags = it->second;
2263      }
2264  
2265      // Enforce the DERSIG (BIP66) rule
2266      if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_DERSIG)) {
2267          flags |= SCRIPT_VERIFY_DERSIG;
2268      }
2269  
2270      // Enforce CHECKLOCKTIMEVERIFY (BIP65)
2271      if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_CLTV)) {
2272          flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2273      }
2274  
2275      // Enforce CHECKSEQUENCEVERIFY (BIP112)
2276      if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_CSV)) {
2277          flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
2278      }
2279  
2280      // Enforce BIP147 NULLDUMMY (activated simultaneously with segwit)
2281      if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_SEGWIT)) {
2282          flags |= SCRIPT_VERIFY_NULLDUMMY;
2283      }
2284  
2285      return flags;
2286  }
2287  
2288  
2289  /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
2290   *  Validity checks that depend on the UTXO set are also done; ConnectBlock()
2291   *  can fail if those validity checks fail (among other reasons). */
2292  bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
2293                                 CCoinsViewCache& view, bool fJustCheck)
2294  {
2295      AssertLockHeld(cs_main);
2296      assert(pindex);
2297  
2298      uint256 block_hash{block.GetHash()};
2299      assert(*pindex->phashBlock == block_hash);
2300  
2301      const auto time_start{SteadyClock::now()};
2302      const CChainParams& params{m_chainman.GetParams()};
2303  
2304      // Check it again in case a previous version let a bad block in
2305      // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
2306      // ContextualCheckBlockHeader() here. This means that if we add a new
2307      // consensus rule that is enforced in one of those two functions, then we
2308      // may have let in a block that violates the rule prior to updating the
2309      // software, and we would NOT be enforcing the rule here. Fully solving
2310      // upgrade from one software version to the next after a consensus rule
2311      // change is potentially tricky and issue-specific (see NeedsRedownload()
2312      // for one approach that was used for BIP 141 deployment).
2313      // Also, currently the rule against blocks more than 2 hours in the future
2314      // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
2315      // re-enforce that rule here (at least until we make it impossible for
2316      // the clock to go backward).
2317      if (!CheckBlock(block, state, params.GetConsensus(), !fJustCheck, !fJustCheck)) {
2318          if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED) {
2319              // We don't write down blocks to disk if they may have been
2320              // corrupted, so this should be impossible unless we're having hardware
2321              // problems.
2322              return FatalError(m_chainman.GetNotifications(), state, _("Corrupt block found indicating potential hardware failure."));
2323          }
2324          LogError("%s: Consensus::CheckBlock: %s\n", __func__, state.ToString());
2325          return false;
2326      }
2327  
2328      // verify that the view's current state corresponds to the previous block
2329      uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
2330      assert(hashPrevBlock == view.GetBestBlock());
2331  
2332      m_chainman.num_blocks_total++;
2333  
2334      // Special case for the genesis block, skipping connection of its transactions
2335      // (its coinbase is unspendable)
2336      if (block_hash == params.GetConsensus().hashGenesisBlock) {
2337          if (!fJustCheck)
2338              view.SetBestBlock(pindex->GetBlockHash());
2339          return true;
2340      }
2341  
2342      const char* script_check_reason;
2343      if (m_chainman.AssumedValidBlock().IsNull()) {
2344          script_check_reason = "assumevalid=0 (always verify)";
2345      } else {
2346          constexpr int64_t TWO_WEEKS_IN_SECONDS{60 * 60 * 24 * 7 * 2};
2347          // We've been configured with the hash of a block which has been externally verified to have a valid history.
2348          // A suitable default value is included with the software and updated from time to time.  Because validity
2349          //  relative to a piece of software is an objective fact these defaults can be easily reviewed.
2350          // This setting doesn't force the selection of any particular chain but makes validating some faster by
2351          //  effectively caching the result of part of the verification.
2352          BlockMap::const_iterator it{m_blockman.m_block_index.find(m_chainman.AssumedValidBlock())};
2353          if (it == m_blockman.m_block_index.end()) {
2354              script_check_reason = "assumevalid hash not in headers";
2355          } else if (it->second.GetAncestor(pindex->nHeight) != pindex) {
2356              script_check_reason = (pindex->nHeight > it->second.nHeight) ? "block height above assumevalid height" : "block not in assumevalid chain";
2357          } else if (m_chainman.m_best_header->GetAncestor(pindex->nHeight) != pindex) {
2358              script_check_reason = "block not in best header chain";
2359          } else if (m_chainman.m_best_header->nChainWork < m_chainman.MinimumChainWork()) {
2360              script_check_reason = "best header chainwork below minimumchainwork";
2361          } else if (GetBlockProofEquivalentTime(*m_chainman.m_best_header, *pindex, *m_chainman.m_best_header, params.GetConsensus()) <= TWO_WEEKS_IN_SECONDS) {
2362              script_check_reason = "block too recent relative to best header";
2363          } else {
2364              // This block is a member of the assumed verified chain and an ancestor of the best header.
2365              // Script verification is skipped when connecting blocks under the
2366              //  assumevalid block. Assuming the assumevalid block is valid this
2367              //  is safe because block merkle hashes are still computed and checked,
2368              // Of course, if an assumed valid block is invalid due to false scriptSigs
2369              //  this optimization would allow an invalid chain to be accepted.
2370              // The equivalent time check discourages hash power from extorting the network via DOS attack
2371              //  into accepting an invalid block through telling users they must manually set assumevalid.
2372              //  Requiring a software change or burying the invalid block, regardless of the setting, makes
2373              //  it hard to hide the implication of the demand. This also avoids having release candidates
2374              //  that are hardly doing any signature verification at all in testing without having to
2375              //  artificially set the default assumed verified block further back.
2376              // The test against the minimum chain work prevents the skipping when denied access to any chain at
2377              //  least as good as the expected chain.
2378              script_check_reason = nullptr;
2379          }
2380      }
2381  
2382      const auto time_1{SteadyClock::now()};
2383      m_chainman.time_check += time_1 - time_start;
2384      LogDebug(BCLog::BENCH, "    - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n",
2385               Ticks<MillisecondsDouble>(time_1 - time_start),
2386               Ticks<SecondsDouble>(m_chainman.time_check),
2387               Ticks<MillisecondsDouble>(m_chainman.time_check) / m_chainman.num_blocks_total);
2388  
2389      // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2390      // unless those are already completely spent.
2391      // If such overwrites are allowed, coinbases and transactions depending upon those
2392      // can be duplicated to remove the ability to spend the first instance -- even after
2393      // being sent to another address.
2394      // See BIP30, CVE-2012-1909, and https://r6.ca/blog/20120206T005236Z.html for more information.
2395      // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
2396      // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
2397      // two in the chain that violate it. This prevents exploiting the issue against nodes during their
2398      // initial block download.
2399      bool fEnforceBIP30 = !IsBIP30Repeat(*pindex);
2400  
2401      // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
2402      // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs.  But by the
2403      // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
2404      // before the first had been spent.  Since those coinbases are sufficiently buried it's no longer possible to create further
2405      // duplicate transactions descending from the known pairs either.
2406      // If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
2407  
2408      // BIP34 requires that a block at height X (block X) has its coinbase
2409      // scriptSig start with a CScriptNum of X (indicated height X).  The above
2410      // logic of no longer requiring BIP30 once BIP34 activates is flawed in the
2411      // case that there is a block X before the BIP34 height of 227,931 which has
2412      // an indicated height Y where Y is greater than X.  The coinbase for block
2413      // X would also be a valid coinbase for block Y, which could be a BIP30
2414      // violation.  An exhaustive search of all mainnet coinbases before the
2415      // BIP34 height which have an indicated height greater than the block height
2416      // reveals many occurrences. The 3 lowest indicated heights found are
2417      // 209,921, 490,897, and 1,983,702 and thus coinbases for blocks at these 3
2418      // heights would be the first opportunity for BIP30 to be violated.
2419  
2420      // The search reveals a great many blocks which have an indicated height
2421      // greater than 1,983,702, so we simply remove the optimization to skip
2422      // BIP30 checking for blocks at height 1,983,702 or higher.  Before we reach
2423      // that block in another 25 years or so, we should take advantage of a
2424      // future consensus change to do a new and improved version of BIP34 that
2425      // will actually prevent ever creating any duplicate coinbases in the
2426      // future.
2427      static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
2428  
2429      // There is no potential to create a duplicate coinbase at block 209,921
2430      // because this is still before the BIP34 height and so explicit BIP30
2431      // checking is still active.
2432  
2433      // The final case is block 176,684 which has an indicated height of
2434      // 490,897. Unfortunately, this issue was not discovered until about 2 weeks
2435      // before block 490,897 so there was not much opportunity to address this
2436      // case other than to carefully analyze it and determine it would not be a
2437      // problem. Block 490,897 was, in fact, mined with a different coinbase than
2438      // block 176,684, but it is important to note that even if it hadn't been or
2439      // is remined on an alternate fork with a duplicate coinbase, we would still
2440      // not run into a BIP30 violation.  This is because the coinbase for 176,684
2441      // is spent in block 185,956 in transaction
2442      // d4f7fbbf92f4a3014a230b2dc70b8058d02eb36ac06b4a0736d9d60eaa9e8781.  This
2443      // spending transaction can't be duplicated because it also spends coinbase
2444      // 0328dd85c331237f18e781d692c92de57649529bd5edf1d01036daea32ffde29.  This
2445      // coinbase has an indicated height of over 4.2 billion, and wouldn't be
2446      // duplicatable until that height, and it's currently impossible to create a
2447      // chain that long. Nevertheless we may wish to consider a future soft fork
2448      // which retroactively prevents block 490,897 from creating a duplicate
2449      // coinbase. The two historical BIP30 violations often provide a confusing
2450      // edge case when manipulating the UTXO and it would be simpler not to have
2451      // another edge case to deal with.
2452  
2453      // testnet3 has no blocks before the BIP34 height with indicated heights
2454      // post BIP34 before approximately height 486,000,000. After block
2455      // 1,983,702 testnet3 starts doing unnecessary BIP30 checking again.
2456      assert(pindex->pprev);
2457      CBlockIndex* pindexBIP34height = pindex->pprev->GetAncestor(params.GetConsensus().BIP34Height);
2458      //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
2459      fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == params.GetConsensus().BIP34Hash));
2460  
2461      // TODO: Remove BIP30 checking from block height 1,983,702 on, once we have a
2462      // consensus change that ensures coinbases at those heights cannot
2463      // duplicate earlier coinbases.
2464      if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
2465          for (const auto& tx : block.vtx) {
2466              for (size_t o = 0; o < tx->vout.size(); o++) {
2467                  if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
2468                      state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-BIP30",
2469                                    "tried to overwrite transaction");
2470                  }
2471              }
2472          }
2473      }
2474  
2475      // Enforce BIP68 (sequence locks)
2476      int nLockTimeFlags = 0;
2477      if (DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_CSV)) {
2478          nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
2479      }
2480  
2481      // Get the script flags for this block
2482      script_verify_flags flags{GetBlockScriptFlags(*pindex, m_chainman)};
2483  
2484      const auto time_2{SteadyClock::now()};
2485      m_chainman.time_forks += time_2 - time_1;
2486      LogDebug(BCLog::BENCH, "    - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n",
2487               Ticks<MillisecondsDouble>(time_2 - time_1),
2488               Ticks<SecondsDouble>(m_chainman.time_forks),
2489               Ticks<MillisecondsDouble>(m_chainman.time_forks) / m_chainman.num_blocks_total);
2490  
2491      const bool fScriptChecks{!!script_check_reason};
2492      const kernel::ChainstateRole role{GetRole()};
2493      if (script_check_reason != m_last_script_check_reason_logged && role.validated && !role.historical) {
2494          if (fScriptChecks) {
2495              LogInfo("Enabling script verification at block #%d (%s): %s.",
2496                      pindex->nHeight, block_hash.ToString(), script_check_reason);
2497          } else {
2498              LogInfo("Disabling script verification at block #%d (%s).",
2499                      pindex->nHeight, block_hash.ToString());
2500          }
2501          m_last_script_check_reason_logged = script_check_reason;
2502      }
2503  
2504      CBlockUndo blockundo;
2505  
2506      // Precomputed transaction data pointers must not be invalidated
2507      // until after `control` has run the script checks (potentially
2508      // in multiple threads). Preallocate the vector size so a new allocation
2509      // doesn't invalidate pointers into the vector, and keep txsdata in scope
2510      // for as long as `control`.
2511      std::optional<CCheckQueueControl<CScriptCheck>> control;
2512      if (auto& queue = m_chainman.GetCheckQueue(); queue.HasThreads() && fScriptChecks) control.emplace(queue);
2513  
2514      std::vector<PrecomputedTransactionData> txsdata(block.vtx.size());
2515  
2516      std::vector<int> prevheights;
2517      CAmount nFees = 0;
2518      int nInputs = 0;
2519      int64_t nSigOpsCost = 0;
2520      blockundo.vtxundo.reserve(block.vtx.size() - 1);
2521      for (unsigned int i = 0; i < block.vtx.size(); i++)
2522      {
2523          if (!state.IsValid()) break;
2524          const CTransaction &tx = *(block.vtx[i]);
2525  
2526          nInputs += tx.vin.size();
2527  
2528          if (!tx.IsCoinBase())
2529          {
2530              CAmount txfee = 0;
2531              TxValidationState tx_state;
2532              if (!Consensus::CheckTxInputs(tx, tx_state, view, pindex->nHeight, txfee)) {
2533                  // Any transaction validation failure in ConnectBlock is a block consensus failure
2534                  state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,
2535                                tx_state.GetRejectReason(),
2536                                tx_state.GetDebugMessage() + " in transaction " + tx.GetHash().ToString());
2537                  break;
2538              }
2539              nFees += txfee;
2540              if (!MoneyRange(nFees)) {
2541                  state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-accumulated-fee-outofrange",
2542                                "accumulated fee in the block out of range");
2543                  break;
2544              }
2545  
2546              // Check that transaction is BIP68 final
2547              // BIP68 lock checks (as opposed to nLockTime checks) must
2548              // be in ConnectBlock because they require the UTXO set
2549              prevheights.resize(tx.vin.size());
2550              for (size_t j = 0; j < tx.vin.size(); j++) {
2551                  prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
2552              }
2553  
2554              if (!SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
2555                  state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal",
2556                                "contains a non-BIP68-final transaction " + tx.GetHash().ToString());
2557                  break;
2558              }
2559          }
2560  
2561          // GetTransactionSigOpCost counts 3 types of sigops:
2562          // * legacy (always)
2563          // * p2sh (when P2SH enabled in flags and excludes coinbase)
2564          // * witness (when witness enabled in flags and excludes coinbase)
2565          nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
2566          if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST) {
2567              state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "too many sigops");
2568              break;
2569          }
2570  
2571          if (!tx.IsCoinBase() && fScriptChecks)
2572          {
2573              bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
2574              bool tx_ok;
2575              TxValidationState tx_state;
2576              // If CheckInputScripts is called with a pointer to a checks vector, the resulting checks are appended to it. In that case
2577              // they need to be added to control which runs them asynchronously. Otherwise, CheckInputScripts runs the checks before returning.
2578              if (control) {
2579                  std::vector<CScriptCheck> vChecks;
2580                  tx_ok = CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], m_chainman.m_validation_cache, &vChecks);
2581                  if (tx_ok) control->Add(std::move(vChecks));
2582              } else {
2583                  tx_ok = CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], m_chainman.m_validation_cache);
2584              }
2585              if (!tx_ok) {
2586                  // Any transaction validation failure in ConnectBlock is a block consensus failure
2587                  state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,
2588                                tx_state.GetRejectReason(), tx_state.GetDebugMessage());
2589                  break;
2590              }
2591          }
2592  
2593          CTxUndo undoDummy;
2594          if (i > 0) {
2595              blockundo.vtxundo.emplace_back();
2596          }
2597          UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2598      }
2599      const auto time_3{SteadyClock::now()};
2600      m_chainman.time_connect += time_3 - time_2;
2601      LogDebug(BCLog::BENCH, "      - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(),
2602               Ticks<MillisecondsDouble>(time_3 - time_2), Ticks<MillisecondsDouble>(time_3 - time_2) / block.vtx.size(),
2603               nInputs <= 1 ? 0 : Ticks<MillisecondsDouble>(time_3 - time_2) / (nInputs - 1),
2604               Ticks<SecondsDouble>(m_chainman.time_connect),
2605               Ticks<MillisecondsDouble>(m_chainman.time_connect) / m_chainman.num_blocks_total);
2606  
2607      CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, params.GetConsensus());
2608      if (block.vtx[0]->GetValueOut() > blockReward && state.IsValid()) {
2609          state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-amount",
2610                        strprintf("coinbase pays too much (actual=%d vs limit=%d)", block.vtx[0]->GetValueOut(), blockReward));
2611      }
2612      if (control) {
2613          auto parallel_result = control->Complete();
2614          if (parallel_result.has_value() && state.IsValid()) {
2615              state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, strprintf("block-script-verify-flag-failed (%s)", ScriptErrorString(parallel_result->first)), parallel_result->second);
2616          }
2617      }
2618      if (!state.IsValid()) {
2619          LogInfo("Block validation error: %s", state.ToString());
2620          return false;
2621      }
2622      const auto time_4{SteadyClock::now()};
2623      m_chainman.time_verify += time_4 - time_2;
2624      LogDebug(BCLog::BENCH, "    - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1,
2625               Ticks<MillisecondsDouble>(time_4 - time_2),
2626               nInputs <= 1 ? 0 : Ticks<MillisecondsDouble>(time_4 - time_2) / (nInputs - 1),
2627               Ticks<SecondsDouble>(m_chainman.time_verify),
2628               Ticks<MillisecondsDouble>(m_chainman.time_verify) / m_chainman.num_blocks_total);
2629  
2630      if (fJustCheck) {
2631          return true;
2632      }
2633  
2634      if (!m_blockman.WriteBlockUndo(blockundo, state, *pindex)) {
2635          return false;
2636      }
2637  
2638      const auto time_5{SteadyClock::now()};
2639      m_chainman.time_undo += time_5 - time_4;
2640      LogDebug(BCLog::BENCH, "    - Write undo data: %.2fms [%.2fs (%.2fms/blk)]\n",
2641               Ticks<MillisecondsDouble>(time_5 - time_4),
2642               Ticks<SecondsDouble>(m_chainman.time_undo),
2643               Ticks<MillisecondsDouble>(m_chainman.time_undo) / m_chainman.num_blocks_total);
2644  
2645      if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
2646          pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2647          m_blockman.m_dirty_blockindex.insert(pindex);
2648      }
2649  
2650      // add this block to the view's block chain
2651      view.SetBestBlock(pindex->GetBlockHash());
2652  
2653      const auto time_6{SteadyClock::now()};
2654      m_chainman.time_index += time_6 - time_5;
2655      LogDebug(BCLog::BENCH, "    - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n",
2656               Ticks<MillisecondsDouble>(time_6 - time_5),
2657               Ticks<SecondsDouble>(m_chainman.time_index),
2658               Ticks<MillisecondsDouble>(m_chainman.time_index) / m_chainman.num_blocks_total);
2659  
2660      TRACEPOINT(validation, block_connected,
2661          block_hash.data(),
2662          pindex->nHeight,
2663          block.vtx.size(),
2664          nInputs,
2665          nSigOpsCost,
2666          Ticks<std::chrono::nanoseconds>(time_5 - time_start)
2667      );
2668  
2669      return true;
2670  }
2671  
2672  CoinsCacheSizeState Chainstate::GetCoinsCacheSizeState()
2673  {
2674      AssertLockHeld(::cs_main);
2675      return this->GetCoinsCacheSizeState(
2676          m_coinstip_cache_size_bytes,
2677          m_mempool ? m_mempool->m_opts.max_size_bytes : 0);
2678  }
2679  
2680  CoinsCacheSizeState Chainstate::GetCoinsCacheSizeState(
2681      size_t max_coins_cache_size_bytes,
2682      size_t max_mempool_size_bytes)
2683  {
2684      AssertLockHeld(::cs_main);
2685      const int64_t nMempoolUsage = m_mempool ? m_mempool->DynamicMemoryUsage() : 0;
2686      int64_t cacheSize = CoinsTip().DynamicMemoryUsage();
2687      int64_t nTotalSpace =
2688          max_coins_cache_size_bytes + std::max<int64_t>(int64_t(max_mempool_size_bytes) - nMempoolUsage, 0);
2689  
2690      if (cacheSize > nTotalSpace) {
2691          LogInfo("Cache size (%s) exceeds total space (%s)\n", cacheSize, nTotalSpace);
2692          return CoinsCacheSizeState::CRITICAL;
2693      } else if (cacheSize > LargeCoinsCacheThreshold(nTotalSpace)) {
2694          return CoinsCacheSizeState::LARGE;
2695      }
2696      return CoinsCacheSizeState::OK;
2697  }
2698  
2699  bool Chainstate::FlushStateToDisk(
2700      BlockValidationState &state,
2701      FlushStateMode mode,
2702      int nManualPruneHeight)
2703  {
2704      LOCK(cs_main);
2705      assert(this->CanFlushToDisk());
2706      std::set<int> setFilesToPrune;
2707      bool full_flush_completed = false;
2708  
2709      [[maybe_unused]] const size_t coins_count{CoinsTip().GetCacheSize()};
2710      [[maybe_unused]] const size_t coins_mem_usage{CoinsTip().DynamicMemoryUsage()};
2711  
2712      try {
2713      {
2714          bool fFlushForPrune = false;
2715  
2716          CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
2717          LOCK(m_blockman.cs_LastBlockFile);
2718          if (m_blockman.IsPruneMode() && (m_blockman.m_check_for_pruning || nManualPruneHeight > 0) && m_chainman.m_blockman.m_blockfiles_indexed) {
2719              // make sure we don't prune above any of the prune locks bestblocks
2720              // pruning is height-based
2721              int last_prune{m_chain.Height()}; // last height we can prune
2722              std::optional<std::string> limiting_lock; // prune lock that actually was the limiting factor, only used for logging
2723  
2724              for (const auto& prune_lock : m_blockman.m_prune_locks) {
2725                  if (prune_lock.second.height_first == std::numeric_limits<int>::max()) continue;
2726                  // Remove the buffer and one additional block here to get actual height that is outside of the buffer
2727                  const int lock_height{prune_lock.second.height_first - PRUNE_LOCK_BUFFER - 1};
2728                  last_prune = std::max(1, std::min(last_prune, lock_height));
2729                  if (last_prune == lock_height) {
2730                      limiting_lock = prune_lock.first;
2731                  }
2732              }
2733  
2734              if (limiting_lock) {
2735                  LogDebug(BCLog::PRUNE, "%s limited pruning to height %d\n", limiting_lock.value(), last_prune);
2736              }
2737  
2738              if (nManualPruneHeight > 0) {
2739                  LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune (manual)", BCLog::BENCH);
2740  
2741                  m_blockman.FindFilesToPruneManual(
2742                      setFilesToPrune,
2743                      std::min(last_prune, nManualPruneHeight),
2744                      *this);
2745              } else {
2746                  LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune", BCLog::BENCH);
2747  
2748                  m_blockman.FindFilesToPrune(setFilesToPrune, last_prune, *this, m_chainman);
2749                  m_blockman.m_check_for_pruning = false;
2750              }
2751              if (!setFilesToPrune.empty()) {
2752                  fFlushForPrune = true;
2753                  if (!m_blockman.m_have_pruned) {
2754                      m_blockman.m_block_tree_db->WriteFlag("prunedblockfiles", true);
2755                      m_blockman.m_have_pruned = true;
2756                  }
2757              }
2758          }
2759          const auto nNow{NodeClock::now()};
2760          // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
2761          bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
2762          // The cache is over the limit, we have to write now.
2763          bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
2764          // It's been a while since we wrote the block index and chain state to disk. Do this frequently, so we don't need to redownload or reindex after a crash.
2765          bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow >= m_next_write;
2766          const auto empty_cache{(mode == FlushStateMode::FORCE_FLUSH) || fCacheLarge || fCacheCritical};
2767          // Combine all conditions that result in a write to disk.
2768          bool should_write = (mode == FlushStateMode::FORCE_SYNC) || empty_cache || fPeriodicWrite || fFlushForPrune;
2769          // Write blocks, block index and best chain related state to disk.
2770          if (should_write) {
2771              LogDebug(BCLog::COINDB, "Writing chainstate to disk: flush mode=%s, prune=%d, large=%d, critical=%d, periodic=%d",
2772                       FlushStateModeNames[size_t(mode)], fFlushForPrune, fCacheLarge, fCacheCritical, fPeriodicWrite);
2773  
2774              // Ensure we can write block index
2775              if (!CheckDiskSpace(m_blockman.m_opts.blocks_dir)) {
2776                  return FatalError(m_chainman.GetNotifications(), state, _("Disk space is too low!"));
2777              }
2778              {
2779                  LOG_TIME_MILLIS_WITH_CATEGORY("write block and undo data to disk", BCLog::BENCH);
2780  
2781                  // First make sure all block and undo data is flushed to disk.
2782                  // TODO: Handle return error, or add detailed comment why it is
2783                  // safe to not return an error upon failure.
2784                  if (!m_blockman.FlushChainstateBlockFile(m_chain.Height())) {
2785                      LogWarning("%s: Failed to flush block file.\n", __func__);
2786                  }
2787              }
2788  
2789              // Then update all block file information (which may refer to block and undo files).
2790              {
2791                  LOG_TIME_MILLIS_WITH_CATEGORY("write block index to disk", BCLog::BENCH);
2792  
2793                  m_blockman.WriteBlockIndexDB();
2794              }
2795              // Finally remove any pruned files
2796              if (fFlushForPrune) {
2797                  LOG_TIME_MILLIS_WITH_CATEGORY("unlink pruned files", BCLog::BENCH);
2798  
2799                  m_blockman.UnlinkPrunedFiles(setFilesToPrune);
2800              }
2801  
2802              if (!CoinsTip().GetBestBlock().IsNull()) {
2803                  // Typical Coin structures on disk are around 48 bytes in size.
2804                  // Pushing a new one to the database can cause it to be written
2805                  // twice (once in the log, and once in the tables). This is already
2806                  // an overestimation, as most will delete an existing entry or
2807                  // overwrite one. Still, use a conservative safety factor of 2.
2808                  if (!CheckDiskSpace(m_chainman.m_options.datadir, 48 * 2 * 2 * CoinsTip().GetDirtyCount())) {
2809                      return FatalError(m_chainman.GetNotifications(), state, _("Disk space is too low!"));
2810                  }
2811                  // Flush the chainstate (which may refer to block index entries).
2812                  empty_cache ? CoinsTip().Flush() : CoinsTip().Sync();
2813                  full_flush_completed = true;
2814                  TRACEPOINT(utxocache, flush,
2815                      int64_t{Ticks<std::chrono::microseconds>(NodeClock::now() - nNow)},
2816                      (uint32_t)mode,
2817                      (uint64_t)coins_count,
2818                      (uint64_t)coins_mem_usage,
2819                      (bool)fFlushForPrune);
2820              }
2821          }
2822  
2823          if (should_write || m_next_write == NodeClock::time_point::max()) {
2824              constexpr auto range{DATABASE_WRITE_INTERVAL_MAX - DATABASE_WRITE_INTERVAL_MIN};
2825              m_next_write = FastRandomContext().rand_uniform_delay(NodeClock::now() + DATABASE_WRITE_INTERVAL_MIN, range);
2826          }
2827      }
2828      if (full_flush_completed && m_chainman.m_options.signals) {
2829          // Update best block in wallet (so we can detect restored wallets).
2830          m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(m_chain.Tip()));
2831      }
2832      } catch (const std::runtime_error& e) {
2833          return FatalError(m_chainman.GetNotifications(), state, strprintf(_("System error while flushing: %s"), e.what()));
2834      }
2835      return true;
2836  }
2837  
2838  void Chainstate::ForceFlushStateToDisk(bool wipe_cache)
2839  {
2840      BlockValidationState state;
2841      if (!this->FlushStateToDisk(state, wipe_cache ? FlushStateMode::FORCE_FLUSH : FlushStateMode::FORCE_SYNC)) {
2842          LogWarning("Failed to force flush state (%s)", state.ToString());
2843      }
2844  }
2845  
2846  void Chainstate::PruneAndFlush()
2847  {
2848      BlockValidationState state;
2849      m_blockman.m_check_for_pruning = true;
2850      if (!this->FlushStateToDisk(state, FlushStateMode::NONE)) {
2851          LogWarning("Failed to flush state (%s)", state.ToString());
2852      }
2853  }
2854  
2855  static void UpdateTipLog(
2856      const ChainstateManager& chainman,
2857      const CCoinsViewCache& coins_tip,
2858      const CBlockIndex* tip,
2859      const std::string& func_name,
2860      const std::string& prefix,
2861      const std::string& warning_messages) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
2862  {
2863  
2864      AssertLockHeld(::cs_main);
2865  
2866      // Disable rate limiting in LogPrintLevel_ so this source location may log during IBD.
2867      LogPrintLevel_(BCLog::LogFlags::ALL, util::log::Level::Info, /*should_ratelimit=*/false, "%s%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)%s\n",
2868                     prefix, func_name,
2869                     tip->GetBlockHash().ToString(), tip->nHeight, tip->nVersion,
2870                     log(tip->nChainWork.getdouble()) / log(2.0), tip->m_chain_tx_count,
2871                     FormatISO8601DateTime(tip->GetBlockTime()),
2872                     chainman.GuessVerificationProgress(tip),
2873                     coins_tip.DynamicMemoryUsage() * (1.0 / (1 << 20)),
2874                     coins_tip.GetCacheSize(),
2875                     !warning_messages.empty() ? strprintf(" warning='%s'", warning_messages) : "");
2876  }
2877  
2878  void Chainstate::UpdateTip(const CBlockIndex* pindexNew)
2879  {
2880      AssertLockHeld(::cs_main);
2881      const auto& coins_tip = this->CoinsTip();
2882  
2883      // The remainder of the function isn't relevant if we are not acting on
2884      // the active chainstate, so return if need be.
2885      if (this != &m_chainman.ActiveChainstate()) {
2886          // Only log every so often so that we don't bury log messages at the tip.
2887          constexpr int BACKGROUND_LOG_INTERVAL = 2000;
2888          if (pindexNew->nHeight % BACKGROUND_LOG_INTERVAL == 0) {
2889              UpdateTipLog(m_chainman, coins_tip, pindexNew, __func__, "[background validation] ", "");
2890          }
2891          return;
2892      }
2893  
2894      // New best block
2895      if (m_mempool) {
2896          m_mempool->AddTransactionsUpdated(1);
2897      }
2898  
2899      std::vector<bilingual_str> warning_messages;
2900      if (!m_chainman.IsInitialBlockDownload()) {
2901          auto bits = m_chainman.m_versionbitscache.CheckUnknownActivations(pindexNew, m_chainman.GetParams());
2902          for (auto [bit, active] : bits) {
2903              const bilingual_str warning = strprintf(_("Unknown new rules activated (versionbit %i)"), bit);
2904              if (active) {
2905                  m_chainman.GetNotifications().warningSet(kernel::Warning::UNKNOWN_NEW_RULES_ACTIVATED, warning);
2906              } else {
2907                  warning_messages.push_back(warning);
2908              }
2909          }
2910      }
2911      UpdateTipLog(m_chainman, coins_tip, pindexNew, __func__, "",
2912                   util::Join(warning_messages, Untranslated(", ")).original);
2913  }
2914  
2915  /** Disconnect m_chain's tip.
2916    * After calling, the mempool will be in an inconsistent state, with
2917    * transactions from disconnected blocks being added to disconnectpool.  You
2918    * should make the mempool consistent again by calling MaybeUpdateMempoolForReorg.
2919    * with cs_main held.
2920    *
2921    * If disconnectpool is nullptr, then no disconnected transactions are added to
2922    * disconnectpool (note that the caller is responsible for mempool consistency
2923    * in any case).
2924    */
2925  bool Chainstate::DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool)
2926  {
2927      AssertLockHeld(cs_main);
2928      if (m_mempool) AssertLockHeld(m_mempool->cs);
2929  
2930      CBlockIndex *pindexDelete = m_chain.Tip();
2931      assert(pindexDelete);
2932      assert(pindexDelete->pprev);
2933      // Read block from disk.
2934      std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2935      CBlock& block = *pblock;
2936      if (!m_blockman.ReadBlock(block, *pindexDelete)) {
2937          LogError("DisconnectTip(): Failed to read block\n");
2938          return false;
2939      }
2940      // Apply the block atomically to the chain state.
2941      const auto time_start{SteadyClock::now()};
2942      {
2943          CCoinsViewCache view(&CoinsTip());
2944          assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2945          if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK) {
2946              LogError("DisconnectTip(): DisconnectBlock %s failed\n", pindexDelete->GetBlockHash().ToString());
2947              return false;
2948          }
2949          view.Flush(/*reallocate_cache=*/false); // local CCoinsViewCache goes out of scope
2950      }
2951      LogDebug(BCLog::BENCH, "- Disconnect block: %.2fms\n",
2952               Ticks<MillisecondsDouble>(SteadyClock::now() - time_start));
2953  
2954      {
2955          // Prune locks that began at or after the tip should be moved backward so they get a chance to reorg
2956          const int max_height_first{pindexDelete->nHeight - 1};
2957          for (auto& prune_lock : m_blockman.m_prune_locks) {
2958              if (prune_lock.second.height_first <= max_height_first) continue;
2959  
2960              prune_lock.second.height_first = max_height_first;
2961              LogDebug(BCLog::PRUNE, "%s prune lock moved back to %d\n", prune_lock.first, max_height_first);
2962          }
2963      }
2964  
2965      // Write the chain state to disk, if necessary.
2966      if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
2967          return false;
2968      }
2969  
2970      if (disconnectpool && m_mempool) {
2971          // Save transactions to re-add to mempool at end of reorg. If any entries are evicted for
2972          // exceeding memory limits, remove them and their descendants from the mempool.
2973          for (auto&& evicted_tx : disconnectpool->AddTransactionsFromBlock(block.vtx)) {
2974              m_mempool->removeRecursive(*evicted_tx, MemPoolRemovalReason::REORG);
2975          }
2976      }
2977  
2978      m_chain.SetTip(*pindexDelete->pprev);
2979      m_chainman.UpdateIBDStatus();
2980  
2981      UpdateTip(pindexDelete->pprev);
2982      // Let wallets know transactions went from 1-confirmed to
2983      // 0-confirmed or conflicted:
2984      if (m_chainman.m_options.signals) {
2985          m_chainman.m_options.signals->BlockDisconnected(pblock, pindexDelete);
2986      }
2987      return true;
2988  }
2989  
2990  struct PerBlockConnectTrace {
2991      CBlockIndex* pindex = nullptr;
2992      std::shared_ptr<const CBlock> pblock;
2993      PerBlockConnectTrace() = default;
2994  };
2995  /**
2996   * Used to track blocks whose transactions were applied to the UTXO state as a
2997   * part of a single ActivateBestChainStep call.
2998   *
2999   * This class is single-use, once you call GetBlocksConnected() you have to throw
3000   * it away and make a new one.
3001   */
3002  class ConnectTrace {
3003  private:
3004      std::vector<PerBlockConnectTrace> blocksConnected;
3005  
3006  public:
3007      explicit ConnectTrace() : blocksConnected(1) {}
3008  
3009      void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
3010          assert(!blocksConnected.back().pindex);
3011          assert(pindex);
3012          assert(pblock);
3013          blocksConnected.back().pindex = pindex;
3014          blocksConnected.back().pblock = std::move(pblock);
3015          blocksConnected.emplace_back();
3016      }
3017  
3018      std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
3019          // We always keep one extra block at the end of our list because
3020          // blocks are added after all the conflicted transactions have
3021          // been filled in. Thus, the last entry should always be an empty
3022          // one waiting for the transactions from the next block. We pop
3023          // the last entry here to make sure the list we return is sane.
3024          assert(!blocksConnected.back().pindex);
3025          blocksConnected.pop_back();
3026          return blocksConnected;
3027      }
3028  };
3029  
3030  /**
3031   * Connect a new block to m_chain. block_to_connect is either nullptr or a pointer to a CBlock
3032   * corresponding to pindexNew, to bypass loading it again from disk.
3033   *
3034   * The block is added to connectTrace if connection succeeds.
3035   */
3036  bool Chainstate::ConnectTip(
3037      BlockValidationState& state,
3038      CBlockIndex* pindexNew,
3039      std::shared_ptr<const CBlock> block_to_connect,
3040      ConnectTrace& connectTrace,
3041      DisconnectedBlockTransactions& disconnectpool)
3042  {
3043      AssertLockHeld(cs_main);
3044      if (m_mempool) AssertLockHeld(m_mempool->cs);
3045  
3046      assert(pindexNew->pprev == m_chain.Tip());
3047      // Read block from disk.
3048      const auto time_1{SteadyClock::now()};
3049      if (!block_to_connect) {
3050          std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
3051          if (!m_blockman.ReadBlock(*pblockNew, *pindexNew)) {
3052              return FatalError(m_chainman.GetNotifications(), state, _("Failed to read block."));
3053          }
3054          block_to_connect = std::move(pblockNew);
3055      } else {
3056          LogDebug(BCLog::BENCH, "  - Using cached block\n");
3057      }
3058      // Apply the block atomically to the chain state.
3059      const auto time_2{SteadyClock::now()};
3060      SteadyClock::time_point time_3;
3061      // When adding aggregate statistics in the future, keep in mind that
3062      // num_blocks_total may be zero until the ConnectBlock() call below.
3063      LogDebug(BCLog::BENCH, "  - Load block from disk: %.2fms\n",
3064               Ticks<MillisecondsDouble>(time_2 - time_1));
3065      {
3066          CCoinsViewCache& view{*m_coins_views->m_connect_block_view};
3067          const auto reset_guard{view.CreateResetGuard()};
3068          bool rv = ConnectBlock(*block_to_connect, state, pindexNew, view);
3069          if (m_chainman.m_options.signals) {
3070              m_chainman.m_options.signals->BlockChecked(block_to_connect, state);
3071          }
3072          if (!rv) {
3073              if (state.IsInvalid())
3074                  InvalidBlockFound(pindexNew, state);
3075              LogError("%s: ConnectBlock %s failed, %s\n", __func__, pindexNew->GetBlockHash().ToString(), state.ToString());
3076              return false;
3077          }
3078          time_3 = SteadyClock::now();
3079          m_chainman.time_connect_total += time_3 - time_2;
3080          assert(m_chainman.num_blocks_total > 0);
3081          LogDebug(BCLog::BENCH, "  - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n",
3082                   Ticks<MillisecondsDouble>(time_3 - time_2),
3083                   Ticks<SecondsDouble>(m_chainman.time_connect_total),
3084                   Ticks<MillisecondsDouble>(m_chainman.time_connect_total) / m_chainman.num_blocks_total);
3085          view.Flush(/*reallocate_cache=*/false); // No need to reallocate since it only has capacity for 1 block
3086      }
3087      const auto time_4{SteadyClock::now()};
3088      m_chainman.time_flush += time_4 - time_3;
3089      LogDebug(BCLog::BENCH, "  - Flush: %.2fms [%.2fs (%.2fms/blk)]\n",
3090               Ticks<MillisecondsDouble>(time_4 - time_3),
3091               Ticks<SecondsDouble>(m_chainman.time_flush),
3092               Ticks<MillisecondsDouble>(m_chainman.time_flush) / m_chainman.num_blocks_total);
3093      // Write the chain state to disk, if necessary.
3094      if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
3095          return false;
3096      }
3097      const auto time_5{SteadyClock::now()};
3098      m_chainman.time_chainstate += time_5 - time_4;
3099      LogDebug(BCLog::BENCH, "  - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n",
3100               Ticks<MillisecondsDouble>(time_5 - time_4),
3101               Ticks<SecondsDouble>(m_chainman.time_chainstate),
3102               Ticks<MillisecondsDouble>(m_chainman.time_chainstate) / m_chainman.num_blocks_total);
3103      // Remove conflicting transactions from the mempool.;
3104      if (m_mempool) {
3105          m_mempool->removeForBlock(block_to_connect->vtx, pindexNew->nHeight);
3106          disconnectpool.removeForBlock(block_to_connect->vtx);
3107      }
3108      // Update m_chain & related variables.
3109      m_chain.SetTip(*pindexNew);
3110      m_chainman.UpdateIBDStatus();
3111      UpdateTip(pindexNew);
3112  
3113      const auto time_6{SteadyClock::now()};
3114      m_chainman.time_post_connect += time_6 - time_5;
3115      m_chainman.time_total += time_6 - time_1;
3116      LogDebug(BCLog::BENCH, "  - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n",
3117               Ticks<MillisecondsDouble>(time_6 - time_5),
3118               Ticks<SecondsDouble>(m_chainman.time_post_connect),
3119               Ticks<MillisecondsDouble>(m_chainman.time_post_connect) / m_chainman.num_blocks_total);
3120      LogDebug(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n",
3121               Ticks<MillisecondsDouble>(time_6 - time_1),
3122               Ticks<SecondsDouble>(m_chainman.time_total),
3123               Ticks<MillisecondsDouble>(m_chainman.time_total) / m_chainman.num_blocks_total);
3124  
3125      // See if this chainstate has reached a target block and can be used to
3126      // validate an assumeutxo snapshot. If it can, hashing the UTXO database
3127      // will be slow, and cs_main could remain locked here for several minutes.
3128      // If the snapshot is validated, the UTXO hash will be saved to
3129      // this->m_target_utxohash, causing HistoricalChainstate() to return null
3130      // and this chainstate to no longer be used. ActivateBestChain() will also
3131      // stop connecting blocks to this chainstate because this->ReachedTarget()
3132      // will be true and this->setBlockIndexCandidates will not have additional
3133      // blocks.
3134      Chainstate& current_cs{m_chainman.CurrentChainstate()};
3135      m_chainman.MaybeValidateSnapshot(*this, current_cs);
3136  
3137      connectTrace.BlockConnected(pindexNew, std::move(block_to_connect));
3138      return true;
3139  }
3140  
3141  /**
3142   * Return the tip of the chain with the most work in it, that isn't
3143   * known to be invalid (it's however far from certain to be valid).
3144   */
3145  CBlockIndex* Chainstate::FindMostWorkChain()
3146  {
3147      AssertLockHeld(::cs_main);
3148      do {
3149          CBlockIndex *pindexNew = nullptr;
3150  
3151          // Find the best candidate header.
3152          {
3153              std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
3154              if (it == setBlockIndexCandidates.rend())
3155                  return nullptr;
3156              pindexNew = *it;
3157          }
3158  
3159          // Check whether all blocks on the path between the currently active chain and the candidate are valid.
3160          // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
3161          CBlockIndex *pindexTest = pindexNew;
3162          bool fInvalidAncestor = false;
3163          while (pindexTest && !m_chain.Contains(pindexTest)) {
3164              assert(pindexTest->HaveNumChainTxs() || pindexTest->nHeight == 0);
3165  
3166              // Pruned nodes may have entries in setBlockIndexCandidates for
3167              // which block files have been deleted.  Remove those as candidates
3168              // for the most work chain if we come across them; we can't switch
3169              // to a chain unless we have all the non-active-chain parent blocks.
3170              bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_VALID;
3171              bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
3172              if (fFailedChain || fMissingData) {
3173                  // Candidate chain is not usable (either invalid or missing data)
3174                  if (fFailedChain && (m_chainman.m_best_invalid == nullptr || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork)) {
3175                      m_chainman.m_best_invalid = pindexNew;
3176                  }
3177                  CBlockIndex *pindexFailed = pindexNew;
3178                  // Remove the entire chain from the set.
3179                  while (pindexTest != pindexFailed) {
3180                      if (fFailedChain) {
3181                          pindexFailed->nStatus |= BLOCK_FAILED_VALID;
3182                          m_blockman.m_dirty_blockindex.insert(pindexFailed);
3183                      } else if (fMissingData) {
3184                          // If we're missing data, then add back to m_blocks_unlinked,
3185                          // so that if the block arrives in the future we can try adding
3186                          // to setBlockIndexCandidates again.
3187                          m_blockman.m_blocks_unlinked.insert(
3188                              std::make_pair(pindexFailed->pprev, pindexFailed));
3189                      }
3190                      setBlockIndexCandidates.erase(pindexFailed);
3191                      pindexFailed = pindexFailed->pprev;
3192                  }
3193                  setBlockIndexCandidates.erase(pindexTest);
3194                  fInvalidAncestor = true;
3195                  break;
3196              }
3197              pindexTest = pindexTest->pprev;
3198          }
3199          if (!fInvalidAncestor)
3200              return pindexNew;
3201      } while(true);
3202  }
3203  
3204  /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
3205  void Chainstate::PruneBlockIndexCandidates() {
3206      // Note that we can't delete the current block itself, as we may need to return to it later in case a
3207      // reorganization to a better block fails.
3208      std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
3209      while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) {
3210          setBlockIndexCandidates.erase(it++);
3211      }
3212      // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
3213      assert(!setBlockIndexCandidates.empty());
3214  }
3215  
3216  /**
3217   * Try to make some progress towards making pindexMostWork the active block.
3218   * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
3219   *
3220   * @returns true unless a system error occurred
3221   */
3222  bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
3223  {
3224      AssertLockHeld(cs_main);
3225      if (m_mempool) AssertLockHeld(m_mempool->cs);
3226  
3227      const CBlockIndex* pindexOldTip = m_chain.Tip();
3228      const CBlockIndex* pindexFork = m_chain.FindFork(pindexMostWork);
3229  
3230      // Disconnect active blocks which are no longer in the best chain.
3231      bool fBlocksDisconnected = false;
3232      DisconnectedBlockTransactions disconnectpool{MAX_DISCONNECTED_TX_POOL_BYTES};
3233      while (m_chain.Tip() && m_chain.Tip() != pindexFork) {
3234          if (!DisconnectTip(state, &disconnectpool)) {
3235              // This is likely a fatal error, but keep the mempool consistent,
3236              // just in case. Only remove from the mempool in this case.
3237              MaybeUpdateMempoolForReorg(disconnectpool, false);
3238  
3239              // If we're unable to disconnect a block during normal operation,
3240              // then that is a failure of our local system -- we should abort
3241              // rather than stay on a less work chain.
3242              FatalError(m_chainman.GetNotifications(), state, _("Failed to disconnect block."));
3243              return false;
3244          }
3245          fBlocksDisconnected = true;
3246      }
3247  
3248      // Build list of new blocks to connect (in descending height order).
3249      std::vector<CBlockIndex*> vpindexToConnect;
3250      bool fContinue = true;
3251      int nHeight = pindexFork ? pindexFork->nHeight : -1;
3252      while (fContinue && nHeight != pindexMostWork->nHeight) {
3253          // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
3254          // a few blocks along the way.
3255          int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
3256          vpindexToConnect.clear();
3257          vpindexToConnect.reserve(nTargetHeight - nHeight);
3258          CBlockIndex* pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
3259          while (pindexIter && pindexIter->nHeight != nHeight) {
3260              vpindexToConnect.push_back(pindexIter);
3261              pindexIter = pindexIter->pprev;
3262          }
3263          nHeight = nTargetHeight;
3264  
3265          // Connect new blocks.
3266          for (CBlockIndex* pindexConnect : vpindexToConnect | std::views::reverse) {
3267              if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
3268                  if (state.IsInvalid()) {
3269                      // The block violates a consensus rule.
3270                      if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
3271                          InvalidChainFound(vpindexToConnect.front());
3272                      }
3273                      state = BlockValidationState();
3274                      fInvalidFound = true;
3275                      fContinue = false;
3276                      break;
3277                  } else {
3278                      // A system error occurred (disk space, database error, ...).
3279                      // Make the mempool consistent with the current tip, just in case
3280                      // any observers try to use it before shutdown.
3281                      MaybeUpdateMempoolForReorg(disconnectpool, false);
3282                      return false;
3283                  }
3284              } else {
3285                  PruneBlockIndexCandidates();
3286                  if (!pindexOldTip || m_chain.Tip()->nChainWork > pindexOldTip->nChainWork) {
3287                      // We're in a better position than we were. Return temporarily to release the lock.
3288                      fContinue = false;
3289                      break;
3290                  }
3291              }
3292          }
3293      }
3294  
3295      if (fBlocksDisconnected) {
3296          // If any blocks were disconnected, disconnectpool may be non empty.  Add
3297          // any disconnected transactions back to the mempool.
3298          MaybeUpdateMempoolForReorg(disconnectpool, true);
3299      }
3300      if (m_mempool) m_mempool->check(this->CoinsTip(), this->m_chain.Height() + 1);
3301  
3302      CheckForkWarningConditions();
3303  
3304      return true;
3305  }
3306  
3307  static SynchronizationState GetSynchronizationState(bool init, bool blockfiles_indexed)
3308  {
3309      if (!init) return SynchronizationState::POST_INIT;
3310      if (!blockfiles_indexed) return SynchronizationState::INIT_REINDEX;
3311      return SynchronizationState::INIT_DOWNLOAD;
3312  }
3313  
3314  void ChainstateManager::UpdateIBDStatus()
3315  {
3316      AssertLockHeld(cs_main);
3317      if (!m_cached_is_ibd.load(std::memory_order_relaxed)) return;
3318      if (m_blockman.LoadingBlocks()) return;
3319      if (!CurrentChainstate().m_chain.IsTipRecent(MinimumChainWork(), m_options.max_tip_age)) return;
3320      LogInfo("Leaving InitialBlockDownload (latching to false)");
3321      m_cached_is_ibd.store(false, std::memory_order_relaxed);
3322  }
3323  
3324  bool ChainstateManager::NotifyHeaderTip()
3325  {
3326      bool fNotify = false;
3327      bool fInitialBlockDownload = false;
3328      CBlockIndex* pindexHeader = nullptr;
3329      {
3330          LOCK(GetMutex());
3331          pindexHeader = m_best_header;
3332  
3333          if (pindexHeader != m_last_notified_header) {
3334              fNotify = true;
3335              fInitialBlockDownload = IsInitialBlockDownload();
3336              m_last_notified_header = pindexHeader;
3337          }
3338      }
3339      // Send block tip changed notifications without the lock held
3340      if (fNotify) {
3341          GetNotifications().headerTip(GetSynchronizationState(fInitialBlockDownload, m_blockman.m_blockfiles_indexed), pindexHeader->nHeight, pindexHeader->nTime, false);
3342      }
3343      return fNotify;
3344  }
3345  
3346  static void LimitValidationInterfaceQueue(ValidationSignals& signals) LOCKS_EXCLUDED(cs_main) {
3347      AssertLockNotHeld(cs_main);
3348  
3349      if (signals.CallbacksPending() > 10) {
3350          signals.SyncWithValidationInterfaceQueue();
3351      }
3352  }
3353  
3354  bool Chainstate::ActivateBestChain(BlockValidationState& state, std::shared_ptr<const CBlock> pblock)
3355  {
3356      AssertLockNotHeld(m_chainstate_mutex);
3357  
3358      // Note that while we're often called here from ProcessNewBlock, this is
3359      // far from a guarantee. Things in the P2P/RPC will often end up calling
3360      // us in the middle of ProcessNewBlock - do not assume pblock is set
3361      // sanely for performance or correctness!
3362      AssertLockNotHeld(::cs_main);
3363  
3364      // ABC maintains a fair degree of expensive-to-calculate internal state
3365      // because this function periodically releases cs_main so that it does not lock up other threads for too long
3366      // during large connects - and to allow for e.g. the callback queue to drain
3367      // we use m_chainstate_mutex to enforce mutual exclusion so that only one caller may execute this function at a time
3368      LOCK(m_chainstate_mutex);
3369  
3370      // Belt-and-suspenders check that we aren't attempting to advance the
3371      // chainstate past the target block.
3372      if (WITH_LOCK(::cs_main, return m_target_utxohash)) {
3373          LogError("%s", STR_INTERNAL_BUG("m_target_utxohash is set - this chainstate should not be in operation."));
3374          return Assume(false);
3375      }
3376  
3377      CBlockIndex *pindexMostWork = nullptr;
3378      CBlockIndex *pindexNewTip = nullptr;
3379      bool exited_ibd{false};
3380      do {
3381          // Block until the validation queue drains. This should largely
3382          // never happen in normal operation, however may happen during
3383          // reindex, causing memory blowup if we run too far ahead.
3384          // Note that if a validationinterface callback ends up calling
3385          // ActivateBestChain this may lead to a deadlock! We should
3386          // probably have a DEBUG_LOCKORDER test for this in the future.
3387          if (m_chainman.m_options.signals) LimitValidationInterfaceQueue(*m_chainman.m_options.signals);
3388  
3389          {
3390              LOCK(cs_main);
3391              {
3392              // Lock transaction pool for at least as long as it takes for connectTrace to be consumed
3393              LOCK(MempoolMutex());
3394              const bool was_in_ibd = m_chainman.IsInitialBlockDownload();
3395              CBlockIndex* starting_tip = m_chain.Tip();
3396              bool blocks_connected = false;
3397              do {
3398                  // We absolutely may not unlock cs_main until we've made forward progress
3399                  // (with the exception of shutdown due to hardware issues, low disk space, etc).
3400                  ConnectTrace connectTrace; // Destructed before cs_main is unlocked
3401  
3402                  if (pindexMostWork == nullptr) {
3403                      pindexMostWork = FindMostWorkChain();
3404                  }
3405  
3406                  // Whether we have anything to do at all.
3407                  if (pindexMostWork == nullptr || pindexMostWork == m_chain.Tip()) {
3408                      break;
3409                  }
3410  
3411                  bool fInvalidFound = false;
3412                  std::shared_ptr<const CBlock> nullBlockPtr;
3413                  // BlockConnected signals must be sent for the original role;
3414                  // in case snapshot validation is completed during ActivateBestChainStep, the
3415                  // result of GetRole() changes from BACKGROUND to NORMAL.
3416                 const ChainstateRole chainstate_role{this->GetRole()};
3417                  if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace)) {
3418                      // A system error occurred
3419                      return false;
3420                  }
3421                  blocks_connected = true;
3422  
3423                  if (fInvalidFound) {
3424                      // Wipe cache, we may need another branch now.
3425                      pindexMostWork = nullptr;
3426                  }
3427                  pindexNewTip = m_chain.Tip();
3428  
3429                  for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
3430                      assert(trace.pblock && trace.pindex);
3431                      if (m_chainman.m_options.signals) {
3432                          m_chainman.m_options.signals->BlockConnected(chainstate_role, trace.pblock, trace.pindex);
3433                      }
3434                  }
3435  
3436                  // Break this do-while to ensure we don't advance past the target block.
3437                  if (ReachedTarget()) {
3438                      break;
3439                  }
3440              } while (!m_chain.Tip() || (starting_tip && CBlockIndexWorkComparator()(m_chain.Tip(), starting_tip)));
3441              if (!blocks_connected) return true;
3442  
3443              const CBlockIndex* pindexFork = m_chain.FindFork(starting_tip);
3444              bool still_in_ibd = m_chainman.IsInitialBlockDownload();
3445  
3446              if (was_in_ibd && !still_in_ibd) {
3447                  // Active chainstate has exited IBD.
3448                  exited_ibd = true;
3449              }
3450  
3451              // Notify external listeners about the new tip.
3452              // Enqueue while holding cs_main to ensure that UpdatedBlockTip is called in the order in which blocks are connected
3453              if (this == &m_chainman.ActiveChainstate() && pindexFork != pindexNewTip) {
3454                  // Notify ValidationInterface subscribers
3455                  if (m_chainman.m_options.signals) {
3456                      m_chainman.m_options.signals->UpdatedBlockTip(pindexNewTip, pindexFork, still_in_ibd);
3457                  }
3458  
3459                  if (kernel::IsInterrupted(m_chainman.GetNotifications().blockTip(
3460                          /*state=*/GetSynchronizationState(still_in_ibd, m_chainman.m_blockman.m_blockfiles_indexed),
3461                          /*index=*/*pindexNewTip,
3462                          /*verification_progress=*/m_chainman.GuessVerificationProgress(pindexNewTip))))
3463                  {
3464                      // Just breaking and returning success for now. This could
3465                      // be changed to bubble up the kernel::Interrupted value to
3466                      // the caller so the caller could distinguish between
3467                      // completed and interrupted operations.
3468                      break;
3469                  }
3470              }
3471              } // release MempoolMutex
3472              // Notify external listeners about the new tip, even if pindexFork == pindexNewTip.
3473              if (m_chainman.m_options.signals && this == &m_chainman.ActiveChainstate()) {
3474                  m_chainman.m_options.signals->ActiveTipChange(*Assert(pindexNewTip), m_chainman.IsInitialBlockDownload());
3475              }
3476          } // release cs_main
3477          // When we reach this point, we switched to a new tip (stored in pindexNewTip).
3478  
3479          bool reached_target;
3480          {
3481              LOCK(m_chainman.GetMutex());
3482              if (exited_ibd) {
3483                  // If a background chainstate is in use, we may need to rebalance our
3484                  // allocation of caches once a chainstate exits initial block download.
3485                  m_chainman.MaybeRebalanceCaches();
3486              }
3487  
3488              // Write changes periodically to disk, after relay.
3489              if (!FlushStateToDisk(state, FlushStateMode::PERIODIC)) {
3490                  return false;
3491              }
3492  
3493              reached_target = ReachedTarget();
3494          }
3495  
3496          if (reached_target) {
3497              // Chainstate has reached the target block, so exit.
3498              //
3499              // Restart indexes so indexes can resync and index new blocks after
3500              // the target block.
3501              //
3502              // This cannot be done while holding cs_main (within
3503              // MaybeValidateSnapshot) or a cs_main deadlock will occur.
3504              if (m_chainman.snapshot_download_completed) {
3505                  m_chainman.snapshot_download_completed();
3506              }
3507              break;
3508          }
3509  
3510          // We check interrupt only after giving ActivateBestChainStep a chance to run once so that we
3511          // never interrupt before connecting the genesis block during LoadChainTip(). Previously this
3512          // caused an assert() failure during interrupt in such cases as the UTXO DB flushing checks
3513          // that the best block hash is non-null.
3514          if (m_chainman.m_interrupt) break;
3515      } while (pindexNewTip != pindexMostWork);
3516  
3517      m_chainman.CheckBlockIndex();
3518  
3519      return true;
3520  }
3521  
3522  bool Chainstate::PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
3523  {
3524      AssertLockNotHeld(m_chainstate_mutex);
3525      AssertLockNotHeld(::cs_main);
3526      {
3527          LOCK(cs_main);
3528          if (pindex->nChainWork < m_chain.Tip()->nChainWork) {
3529              // Nothing to do, this block is not at the tip.
3530              return true;
3531          }
3532          if (m_chain.Tip()->nChainWork > m_chainman.nLastPreciousChainwork) {
3533              // The chain has been extended since the last call, reset the counter.
3534              m_chainman.nBlockReverseSequenceId = -1;
3535          }
3536          m_chainman.nLastPreciousChainwork = m_chain.Tip()->nChainWork;
3537          setBlockIndexCandidates.erase(pindex);
3538          pindex->nSequenceId = m_chainman.nBlockReverseSequenceId;
3539          if (m_chainman.nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
3540              // We can't keep reducing the counter if somebody really wants to
3541              // call preciousblock 2**31-1 times on the same set of tips...
3542              m_chainman.nBlockReverseSequenceId--;
3543          }
3544          if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->HaveNumChainTxs()) {
3545              setBlockIndexCandidates.insert(pindex);
3546              PruneBlockIndexCandidates();
3547          }
3548      }
3549  
3550      return ActivateBestChain(state, std::shared_ptr<const CBlock>());
3551  }
3552  
3553  bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex)
3554  {
3555      AssertLockNotHeld(m_chainstate_mutex);
3556      AssertLockNotHeld(::cs_main);
3557  
3558      // Genesis block can't be invalidated
3559      assert(pindex);
3560      if (pindex->nHeight == 0) return false;
3561  
3562      // We do not allow ActivateBestChain() to run while InvalidateBlock() is
3563      // running, as that could cause the tip to change while we disconnect
3564      // blocks.
3565      LOCK(m_chainstate_mutex);
3566  
3567      // We'll be acquiring and releasing cs_main below, to allow the validation
3568      // callbacks to run. However, we should keep the block index in a
3569      // consistent state as we disconnect blocks -- in particular we need to
3570      // add equal-work blocks to setBlockIndexCandidates as we disconnect.
3571      // To avoid walking the block index repeatedly in search of candidates,
3572      // build a map once so that we can look up candidate blocks by chain
3573      // work as we go.
3574      std::multimap<const arith_uint256, CBlockIndex*> highpow_outofchain_headers;
3575  
3576      {
3577          LOCK(cs_main);
3578          for (auto& entry : m_blockman.m_block_index) {
3579              CBlockIndex* candidate = &entry.second;
3580              // We don't need to put anything in our active chain into the
3581              // multimap, because those candidates will be found and considered
3582              // as we disconnect.
3583              // Instead, consider only non-active-chain blocks that score
3584              // at least as good with CBlockIndexWorkComparator as the new tip.
3585              if (!m_chain.Contains(candidate) &&
3586                  !CBlockIndexWorkComparator()(candidate, pindex->pprev) &&
3587                  !(candidate->nStatus & BLOCK_FAILED_VALID)) {
3588                  highpow_outofchain_headers.insert({candidate->nChainWork, candidate});
3589              }
3590          }
3591      }
3592  
3593      CBlockIndex* to_mark_failed = pindex;
3594      bool pindex_was_in_chain = false;
3595      int disconnected = 0;
3596  
3597      // Disconnect (descendants of) pindex, and mark them invalid.
3598      while (true) {
3599          if (m_chainman.m_interrupt) break;
3600  
3601          // Make sure the queue of validation callbacks doesn't grow unboundedly.
3602          if (m_chainman.m_options.signals) LimitValidationInterfaceQueue(*m_chainman.m_options.signals);
3603  
3604          LOCK(cs_main);
3605          // Lock for as long as disconnectpool is in scope to make sure MaybeUpdateMempoolForReorg is
3606          // called after DisconnectTip without unlocking in between
3607          LOCK(MempoolMutex());
3608          if (!m_chain.Contains(pindex)) break;
3609          pindex_was_in_chain = true;
3610          CBlockIndex* disconnected_tip{m_chain.Tip()};
3611  
3612          // ActivateBestChain considers blocks already in m_chain
3613          // unconditionally valid already, so force disconnect away from it.
3614          DisconnectedBlockTransactions disconnectpool{MAX_DISCONNECTED_TX_POOL_BYTES};
3615          bool ret = DisconnectTip(state, &disconnectpool);
3616          // DisconnectTip will add transactions to disconnectpool.
3617          // Adjust the mempool to be consistent with the new tip, adding
3618          // transactions back to the mempool if disconnecting was successful,
3619          // and we're not doing a very deep invalidation (in which case
3620          // keeping the mempool up to date is probably futile anyway).
3621          MaybeUpdateMempoolForReorg(disconnectpool, /* fAddToMempool = */ (++disconnected <= 10) && ret);
3622          if (!ret) return false;
3623          CBlockIndex* new_tip{m_chain.Tip()};
3624          assert(disconnected_tip->pprev == new_tip);
3625  
3626          // We immediately mark the disconnected blocks as invalid.
3627          // This prevents a case where pruned nodes may fail to invalidateblock
3628          // and be left unable to start as they have no tip candidates (as there
3629          // are no blocks that meet the "have data and are not invalid per
3630          // nStatus" criteria for inclusion in setBlockIndexCandidates).
3631          disconnected_tip->nStatus |= BLOCK_FAILED_VALID;
3632          m_blockman.m_dirty_blockindex.insert(disconnected_tip);
3633          setBlockIndexCandidates.erase(disconnected_tip);
3634          setBlockIndexCandidates.insert(new_tip);
3635  
3636          // Mark out-of-chain descendants of the invalidated block as invalid
3637          // Add any equal or more work headers that are not invalidated to setBlockIndexCandidates
3638          // Recalculate m_best_header if it became invalid.
3639          auto candidate_it = highpow_outofchain_headers.lower_bound(new_tip->nChainWork);
3640  
3641          const bool best_header_needs_update{m_chainman.m_best_header->GetAncestor(disconnected_tip->nHeight) == disconnected_tip};
3642          if (best_header_needs_update) {
3643              // new_tip is definitely still valid at this point, but there may be better ones
3644              m_chainman.m_best_header = new_tip;
3645          }
3646  
3647          while (candidate_it != highpow_outofchain_headers.end()) {
3648              CBlockIndex* candidate{candidate_it->second};
3649              if (candidate->GetAncestor(disconnected_tip->nHeight) == disconnected_tip) {
3650                  // Children of failed blocks are marked as BLOCK_FAILED_VALID.
3651                  candidate->nStatus |= BLOCK_FAILED_VALID;
3652                  m_blockman.m_dirty_blockindex.insert(candidate);
3653                  // If invalidated, the block is irrelevant for setBlockIndexCandidates
3654                  // and for m_best_header and can be removed from the cache.
3655                  candidate_it = highpow_outofchain_headers.erase(candidate_it);
3656                  continue;
3657              }
3658              if (!CBlockIndexWorkComparator()(candidate, new_tip) &&
3659                  candidate->IsValid(BLOCK_VALID_TRANSACTIONS) &&
3660                  candidate->HaveNumChainTxs()) {
3661                  setBlockIndexCandidates.insert(candidate);
3662                  // Do not remove candidate from the highpow_outofchain_headers cache, because it might be a descendant of the block being invalidated
3663                  // which needs to be marked failed later.
3664              }
3665              if (best_header_needs_update &&
3666                  m_chainman.m_best_header->nChainWork < candidate->nChainWork) {
3667                  m_chainman.m_best_header = candidate;
3668              }
3669              ++candidate_it;
3670          }
3671  
3672          // Track the last disconnected block to call InvalidChainFound on it.
3673          to_mark_failed = disconnected_tip;
3674      }
3675  
3676      m_chainman.CheckBlockIndex();
3677  
3678      {
3679          LOCK(cs_main);
3680          if (m_chain.Contains(to_mark_failed)) {
3681              // If the to-be-marked invalid block is in the active chain, something is interfering and we can't proceed.
3682              return false;
3683          }
3684  
3685          // Mark pindex as invalid if it never was in the main chain
3686          if (!pindex_was_in_chain && !(pindex->nStatus & BLOCK_FAILED_VALID)) {
3687              pindex->nStatus |= BLOCK_FAILED_VALID;
3688              m_blockman.m_dirty_blockindex.insert(pindex);
3689              setBlockIndexCandidates.erase(pindex);
3690          }
3691  
3692          // If any new blocks somehow arrived while we were disconnecting
3693          // (above), then the pre-calculation of what should go into
3694          // setBlockIndexCandidates may have missed entries. This would
3695          // technically be an inconsistency in the block index, but if we clean
3696          // it up here, this should be an essentially unobservable error.
3697          // Loop back over all block index entries and add any missing entries
3698          // to setBlockIndexCandidates.
3699          for (auto& [_, block_index] : m_blockman.m_block_index) {
3700              if (block_index.IsValid(BLOCK_VALID_TRANSACTIONS) && block_index.HaveNumChainTxs() && !setBlockIndexCandidates.value_comp()(&block_index, m_chain.Tip())) {
3701                  setBlockIndexCandidates.insert(&block_index);
3702              }
3703          }
3704  
3705          InvalidChainFound(to_mark_failed);
3706      }
3707  
3708      // Only notify about a new block tip if the active chain was modified.
3709      if (pindex_was_in_chain) {
3710          // Ignoring return value for now, this could be changed to bubble up
3711          // kernel::Interrupted value to the caller so the caller could
3712          // distinguish between completed and interrupted operations. It might
3713          // also make sense for the blockTip notification to have an enum
3714          // parameter indicating the source of the tip change so hooks can
3715          // distinguish user-initiated invalidateblock changes from other
3716          // changes.
3717          (void)m_chainman.GetNotifications().blockTip(
3718              /*state=*/GetSynchronizationState(m_chainman.IsInitialBlockDownload(), m_chainman.m_blockman.m_blockfiles_indexed),
3719              /*index=*/*to_mark_failed->pprev,
3720              /*verification_progress=*/WITH_LOCK(m_chainman.GetMutex(), return m_chainman.GuessVerificationProgress(to_mark_failed->pprev)));
3721  
3722          // Fire ActiveTipChange now for the current chain tip to make sure clients are notified.
3723          // ActivateBestChain may call this as well, but not necessarily.
3724          if (m_chainman.m_options.signals) {
3725              m_chainman.m_options.signals->ActiveTipChange(*Assert(m_chain.Tip()), m_chainman.IsInitialBlockDownload());
3726          }
3727      }
3728      return true;
3729  }
3730  
3731  void Chainstate::SetBlockFailureFlags(CBlockIndex* invalid_block)
3732  {
3733      AssertLockHeld(cs_main);
3734  
3735      for (auto& [_, block_index] : m_blockman.m_block_index) {
3736          if (invalid_block != &block_index && block_index.GetAncestor(invalid_block->nHeight) == invalid_block) {
3737              block_index.nStatus |= BLOCK_FAILED_VALID;
3738              m_blockman.m_dirty_blockindex.insert(&block_index);
3739          }
3740      }
3741  }
3742  
3743  void Chainstate::ResetBlockFailureFlags(CBlockIndex *pindex) {
3744      AssertLockHeld(cs_main);
3745  
3746      int nHeight = pindex->nHeight;
3747  
3748      // Remove the invalidity flag from this block and all its descendants and ancestors.
3749      for (auto& [_, block_index] : m_blockman.m_block_index) {
3750          if ((block_index.nStatus & BLOCK_FAILED_VALID) && (block_index.GetAncestor(nHeight) == pindex || pindex->GetAncestor(block_index.nHeight) == &block_index)) {
3751              block_index.nStatus &= ~BLOCK_FAILED_VALID;
3752              m_blockman.m_dirty_blockindex.insert(&block_index);
3753              if (block_index.IsValid(BLOCK_VALID_TRANSACTIONS) && block_index.HaveNumChainTxs() && setBlockIndexCandidates.value_comp()(m_chain.Tip(), &block_index)) {
3754                  setBlockIndexCandidates.insert(&block_index);
3755              }
3756              if (&block_index == m_chainman.m_best_invalid) {
3757                  // Reset invalid block marker if it was pointing to one of those.
3758                  m_chainman.m_best_invalid = nullptr;
3759              }
3760          }
3761      }
3762  }
3763  
3764  void Chainstate::TryAddBlockIndexCandidate(CBlockIndex* pindex)
3765  {
3766      AssertLockHeld(cs_main);
3767  
3768      // Do not continue building a chainstate that is based on an invalid
3769      // snapshot. This is a belt-and-suspenders type of check because if an
3770      // invalid snapshot is loaded, the node will shut down to force a manual
3771      // intervention. But it is good to handle this case correctly regardless.
3772      if (m_assumeutxo == Assumeutxo::INVALID) {
3773          return;
3774      }
3775  
3776      // The block only is a candidate for the most-work-chain if it has the same
3777      // or more work than our current tip.
3778      if (m_chain.Tip() != nullptr && setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) {
3779          return;
3780      }
3781  
3782      const CBlockIndex* target_block{TargetBlock()};
3783      if (!target_block) {
3784          // If no specific target block, add all entries that have more
3785          // work than the tip.
3786          setBlockIndexCandidates.insert(pindex);
3787      } else {
3788          // If there is a target block, only consider connecting blocks
3789          // towards the target block.
3790          if (target_block->GetAncestor(pindex->nHeight) == pindex) {
3791              setBlockIndexCandidates.insert(pindex);
3792          }
3793      }
3794  }
3795  
3796  /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
3797  void ChainstateManager::ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos)
3798  {
3799      AssertLockHeld(cs_main);
3800      pindexNew->nTx = block.vtx.size();
3801      // Typically m_chain_tx_count will be 0 at this point, but it can be nonzero if this
3802      // is a pruned block which is being downloaded again, or if this is an
3803      // assumeutxo snapshot block which has a hardcoded m_chain_tx_count value from the
3804      // snapshot metadata. If the pindex is not the snapshot block and the
3805      // m_chain_tx_count value is not zero, assert that value is actually correct.
3806      auto prev_tx_sum = [](CBlockIndex& block) { return block.nTx + (block.pprev ? block.pprev->m_chain_tx_count : 0); };
3807      if (!Assume(pindexNew->m_chain_tx_count == 0 || pindexNew->m_chain_tx_count == prev_tx_sum(*pindexNew) ||
3808                  std::ranges::any_of(m_chainstates, [&](const auto& cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->SnapshotBase() == pindexNew; }))) {
3809          LogWarning("Internal bug detected: block %d has unexpected m_chain_tx_count %i that should be %i (%s %s). Please report this issue here: %s\n",
3810              pindexNew->nHeight, pindexNew->m_chain_tx_count, prev_tx_sum(*pindexNew), CLIENT_NAME, FormatFullVersion(), CLIENT_BUGREPORT);
3811          pindexNew->m_chain_tx_count = 0;
3812      }
3813      pindexNew->nFile = pos.nFile;
3814      pindexNew->nDataPos = pos.nPos;
3815      pindexNew->nUndoPos = 0;
3816      pindexNew->nStatus |= BLOCK_HAVE_DATA;
3817      if (DeploymentActiveAt(*pindexNew, *this, Consensus::DEPLOYMENT_SEGWIT)) {
3818          pindexNew->nStatus |= BLOCK_OPT_WITNESS;
3819      }
3820      pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
3821      m_blockman.m_dirty_blockindex.insert(pindexNew);
3822  
3823      if (pindexNew->pprev == nullptr || pindexNew->pprev->HaveNumChainTxs()) {
3824          // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3825          std::deque<CBlockIndex*> queue;
3826          queue.push_back(pindexNew);
3827  
3828          // Recursively process any descendant blocks that now may be eligible to be connected.
3829          while (!queue.empty()) {
3830              CBlockIndex *pindex = queue.front();
3831              queue.pop_front();
3832              // Before setting m_chain_tx_count, assert that it is 0 or already set to
3833              // the correct value. This assert will fail after receiving the
3834              // assumeutxo snapshot block if assumeutxo snapshot metadata has an
3835              // incorrect hardcoded AssumeutxoData::m_chain_tx_count value.
3836              if (!Assume(pindex->m_chain_tx_count == 0 || pindex->m_chain_tx_count == prev_tx_sum(*pindex))) {
3837                  LogWarning("Internal bug detected: block %d has unexpected m_chain_tx_count %i that should be %i (%s %s). Please report this issue here: %s\n",
3838                     pindex->nHeight, pindex->m_chain_tx_count, prev_tx_sum(*pindex), CLIENT_NAME, FormatFullVersion(), CLIENT_BUGREPORT);
3839              }
3840              pindex->m_chain_tx_count = prev_tx_sum(*pindex);
3841              pindex->nSequenceId = nBlockSequenceId++;
3842              for (const auto& c : m_chainstates) {
3843                  c->TryAddBlockIndexCandidate(pindex);
3844              }
3845              std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = m_blockman.m_blocks_unlinked.equal_range(pindex);
3846              while (range.first != range.second) {
3847                  std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3848                  queue.push_back(it->second);
3849                  range.first++;
3850                  m_blockman.m_blocks_unlinked.erase(it);
3851              }
3852          }
3853      } else {
3854          if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3855              m_blockman.m_blocks_unlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3856          }
3857      }
3858  }
3859  
3860  static bool CheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
3861  {
3862      // Check proof of work matches claimed amount
3863      if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
3864          return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "high-hash", "proof of work failed");
3865  
3866      return true;
3867  }
3868  
3869  static bool CheckMerkleRoot(const CBlock& block, BlockValidationState& state)
3870  {
3871      if (block.m_checked_merkle_root) return true;
3872  
3873      bool mutated;
3874      uint256 merkle_root = BlockMerkleRoot(block, &mutated);
3875      if (block.hashMerkleRoot != merkle_root) {
3876          return state.Invalid(
3877              /*result=*/BlockValidationResult::BLOCK_MUTATED,
3878              /*reject_reason=*/"bad-txnmrklroot",
3879              /*debug_message=*/"hashMerkleRoot mismatch");
3880      }
3881  
3882      // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3883      // of transactions in a block without affecting the merkle root of a block,
3884      // while still invalidating it.
3885      if (mutated) {
3886          return state.Invalid(
3887              /*result=*/BlockValidationResult::BLOCK_MUTATED,
3888              /*reject_reason=*/"bad-txns-duplicate",
3889              /*debug_message=*/"duplicate transaction");
3890      }
3891  
3892      block.m_checked_merkle_root = true;
3893      return true;
3894  }
3895  
3896  /** CheckWitnessMalleation performs checks for block malleation with regard to
3897   * its witnesses.
3898   *
3899   * Note: If the witness commitment is expected (i.e. `expect_witness_commitment
3900   * = true`), then the block is required to have at least one transaction and the
3901   * first transaction needs to have at least one input. */
3902  static bool CheckWitnessMalleation(const CBlock& block, bool expect_witness_commitment, BlockValidationState& state)
3903  {
3904      if (expect_witness_commitment) {
3905          if (block.m_checked_witness_commitment) return true;
3906  
3907          int commitpos = GetWitnessCommitmentIndex(block);
3908          if (commitpos != NO_WITNESS_COMMITMENT) {
3909              assert(!block.vtx.empty() && !block.vtx[0]->vin.empty());
3910              const auto& witness_stack{block.vtx[0]->vin[0].scriptWitness.stack};
3911  
3912              if (witness_stack.size() != 1 || witness_stack[0].size() != 32) {
3913                  return state.Invalid(
3914                      /*result=*/BlockValidationResult::BLOCK_MUTATED,
3915                      /*reject_reason=*/"bad-witness-nonce-size",
3916                      /*debug_message=*/strprintf("%s : invalid witness reserved value size", __func__));
3917              }
3918  
3919              // The malleation check is ignored; as the transaction tree itself
3920              // already does not permit it, it is impossible to trigger in the
3921              // witness tree.
3922              uint256 hash_witness = BlockWitnessMerkleRoot(block);
3923  
3924              CHash256().Write(hash_witness).Write(witness_stack[0]).Finalize(hash_witness);
3925              if (memcmp(hash_witness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3926                  return state.Invalid(
3927                      /*result=*/BlockValidationResult::BLOCK_MUTATED,
3928                      /*reject_reason=*/"bad-witness-merkle-match",
3929                      /*debug_message=*/strprintf("%s : witness merkle commitment mismatch", __func__));
3930              }
3931  
3932              block.m_checked_witness_commitment = true;
3933              return true;
3934          }
3935      }
3936  
3937      // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3938      for (const auto& tx : block.vtx) {
3939          if (tx->HasWitness()) {
3940              return state.Invalid(
3941                  /*result=*/BlockValidationResult::BLOCK_MUTATED,
3942                  /*reject_reason=*/"unexpected-witness",
3943                  /*debug_message=*/strprintf("%s : unexpected witness data found", __func__));
3944          }
3945      }
3946  
3947      return true;
3948  }
3949  
3950  bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
3951  {
3952      // These are checks that are independent of context.
3953  
3954      if (block.fChecked)
3955          return true;
3956  
3957      // Check that the header is valid (particularly PoW).  This is mostly
3958      // redundant with the call in AcceptBlockHeader.
3959      if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
3960          return false;
3961  
3962      // Signet only: check block solution
3963      if (consensusParams.signet_blocks && fCheckPOW && !CheckSignetBlockSolution(block, consensusParams)) {
3964          return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-signet-blksig", "signet block signature validation failure");
3965      }
3966  
3967      // Check the merkle root.
3968      if (fCheckMerkleRoot && !CheckMerkleRoot(block, state)) {
3969          return false;
3970      }
3971  
3972      // All potential-corruption validation must be done before we do any
3973      // transaction validation, as otherwise we may mark the header as invalid
3974      // because we receive the wrong transactions for it.
3975      // Note that witness malleability is checked in ContextualCheckBlock, so no
3976      // checks that use witness data may be performed here.
3977  
3978      // Size limits
3979      if (block.vtx.empty() || block.vtx.size() * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT || ::GetSerializeSize(TX_NO_WITNESS(block)) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)
3980          return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-length", "size limits failed");
3981  
3982      // First transaction must be coinbase, the rest must not be
3983      if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
3984          return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-missing", "first tx is not coinbase");
3985      for (unsigned int i = 1; i < block.vtx.size(); i++)
3986          if (block.vtx[i]->IsCoinBase())
3987              return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple", "more than one coinbase");
3988  
3989      // Check transactions
3990      // Must check for duplicate inputs (see CVE-2018-17144)
3991      for (const auto& tx : block.vtx) {
3992          TxValidationState tx_state;
3993          if (!CheckTransaction(*tx, tx_state)) {
3994              // CheckBlock() does context-free validation checks. The only
3995              // possible failures are consensus failures.
3996              assert(tx_state.GetResult() == TxValidationResult::TX_CONSENSUS);
3997              return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, tx_state.GetRejectReason(),
3998                                   strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), tx_state.GetDebugMessage()));
3999          }
4000      }
4001      // This underestimates the number of sigops, because unlike ConnectBlock it
4002      // does not count witness and p2sh sigops.
4003      unsigned int nSigOps = 0;
4004      for (const auto& tx : block.vtx)
4005      {
4006          nSigOps += GetLegacySigOpCount(*tx);
4007      }
4008      if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
4009          return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "out-of-bounds SigOpCount");
4010  
4011      if (fCheckPOW && fCheckMerkleRoot)
4012          block.fChecked = true;
4013  
4014      return true;
4015  }
4016  
4017  void ChainstateManager::UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const
4018  {
4019      int commitpos = GetWitnessCommitmentIndex(block);
4020      static const std::vector<unsigned char> nonce(32, 0x00);
4021      if (commitpos != NO_WITNESS_COMMITMENT && DeploymentActiveAfter(pindexPrev, *this, Consensus::DEPLOYMENT_SEGWIT) && !block.vtx[0]->HasWitness()) {
4022          CMutableTransaction tx(*block.vtx[0]);
4023          tx.vin[0].scriptWitness.stack.resize(1);
4024          tx.vin[0].scriptWitness.stack[0] = nonce;
4025          block.vtx[0] = MakeTransactionRef(std::move(tx));
4026      }
4027  }
4028  
4029  void ChainstateManager::GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const
4030  {
4031      int commitpos = GetWitnessCommitmentIndex(block);
4032      std::vector<unsigned char> ret(32, 0x00);
4033      if (commitpos == NO_WITNESS_COMMITMENT) {
4034          uint256 witnessroot = BlockWitnessMerkleRoot(block);
4035          CHash256().Write(witnessroot).Write(ret).Finalize(witnessroot);
4036          CTxOut out;
4037          out.nValue = 0;
4038          out.scriptPubKey.resize(MINIMUM_WITNESS_COMMITMENT);
4039          out.scriptPubKey[0] = OP_RETURN;
4040          out.scriptPubKey[1] = 0x24;
4041          out.scriptPubKey[2] = 0xaa;
4042          out.scriptPubKey[3] = 0x21;
4043          out.scriptPubKey[4] = 0xa9;
4044          out.scriptPubKey[5] = 0xed;
4045          memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
4046          CMutableTransaction tx(*block.vtx[0]);
4047          tx.vout.push_back(out);
4048          block.vtx[0] = MakeTransactionRef(std::move(tx));
4049      }
4050      UpdateUncommittedBlockStructures(block, pindexPrev);
4051  }
4052  
4053  bool HasValidProofOfWork(std::span<const CBlockHeader> headers, const Consensus::Params& consensusParams)
4054  {
4055      return std::ranges::all_of(headers,
4056                                 [&](const auto& header) { return CheckProofOfWork(header.GetHash(), header.nBits, consensusParams); });
4057  }
4058  
4059  bool IsBlockMutated(const CBlock& block, bool check_witness_root)
4060  {
4061      BlockValidationState state;
4062      if (!CheckMerkleRoot(block, state)) {
4063          LogDebug(BCLog::VALIDATION, "Block mutated: %s\n", state.ToString());
4064          return true;
4065      }
4066  
4067      if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
4068          // Consider the block mutated if any transaction is 64 bytes in size (see 3.1
4069          // in "Weaknesses in Bitcoin’s Merkle Root Construction":
4070          // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/attachments/20190225/a27d8837/attachment-0001.pdf).
4071          //
4072          // Note: This is not a consensus change as this only applies to blocks that
4073          // don't have a coinbase transaction and would therefore already be invalid.
4074          return std::any_of(block.vtx.begin(), block.vtx.end(),
4075                             [](auto& tx) { return GetSerializeSize(TX_NO_WITNESS(tx)) == 64; });
4076      } else {
4077          // Theoretically it is still possible for a block with a 64 byte
4078          // coinbase transaction to be mutated but we neglect that possibility
4079          // here as it requires at least 224 bits of work.
4080      }
4081  
4082      if (!CheckWitnessMalleation(block, check_witness_root, state)) {
4083          LogDebug(BCLog::VALIDATION, "Block mutated: %s\n", state.ToString());
4084          return true;
4085      }
4086  
4087      return false;
4088  }
4089  
4090  arith_uint256 CalculateClaimedHeadersWork(std::span<const CBlockHeader> headers)
4091  {
4092      arith_uint256 total_work{0};
4093      for (const CBlockHeader& header : headers) {
4094          total_work += GetBlockProof(header);
4095      }
4096      return total_work;
4097  }
4098  
4099  /** Context-dependent validity checks.
4100   *  By "context", we mean only the previous block headers, but not the UTXO
4101   *  set; UTXO-related validity checks are done in ConnectBlock().
4102   *  NOTE: This function is not currently invoked by ConnectBlock(), so we
4103   *  should consider upgrade issues if we change which consensus rules are
4104   *  enforced in this function (eg by adding a new consensus rule). See comment
4105   *  in ConnectBlock().
4106   *  Note that -reindex-chainstate skips the validation that happens here!
4107   *
4108   *  NOTE: failing to check the header's height against the last checkpoint's opened a DoS vector between
4109   *  v0.12 and v0.15 (when no additional protection was in place) whereby an attacker could unboundedly
4110   *  grow our in-memory block index. See https://bitcoincore.org/en/2024/07/03/disclose-header-spam.
4111   */
4112  static bool ContextualCheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, BlockManager& blockman, const ChainstateManager& chainman, const CBlockIndex* pindexPrev) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
4113  {
4114      AssertLockHeld(::cs_main);
4115      assert(pindexPrev != nullptr);
4116      const int nHeight = pindexPrev->nHeight + 1;
4117  
4118      // Check proof of work
4119      const Consensus::Params& consensusParams = chainman.GetConsensus();
4120      if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
4121          return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits", "incorrect proof of work");
4122  
4123      // Check timestamp against prev
4124      if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
4125          return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-too-old", "block's timestamp is too early");
4126  
4127      // Testnet4 and regtest only: Check timestamp against prev for difficulty-adjustment
4128      // blocks to prevent timewarp attacks (see https://github.com/bitcoin/bitcoin/pull/15482).
4129      if (consensusParams.enforce_BIP94) {
4130          // Check timestamp for the first block of each difficulty adjustment
4131          // interval, except the genesis block.
4132          if (nHeight % consensusParams.DifficultyAdjustmentInterval() == 0) {
4133              if (block.GetBlockTime() < pindexPrev->GetBlockTime() - MAX_TIMEWARP) {
4134                  return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-timewarp-attack", "block's timestamp is too early on diff adjustment block");
4135              }
4136          }
4137      }
4138  
4139      // Check timestamp
4140      if (block.Time() > NodeClock::now() + std::chrono::seconds{MAX_FUTURE_BLOCK_TIME}) {
4141          return state.Invalid(BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new", "block timestamp too far in the future");
4142      }
4143  
4144      // Reject blocks with outdated version
4145      if ((block.nVersion < 2 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_HEIGHTINCB)) ||
4146          (block.nVersion < 3 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_DERSIG)) ||
4147          (block.nVersion < 4 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_CLTV))) {
4148              return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, strprintf("bad-version(0x%08x)", block.nVersion),
4149                                   strprintf("rejected nVersion=0x%08x block", block.nVersion));
4150      }
4151  
4152      return true;
4153  }
4154  
4155  /** NOTE: This function is not currently invoked by ConnectBlock(), so we
4156   *  should consider upgrade issues if we change which consensus rules are
4157   *  enforced in this function (eg by adding a new consensus rule). See comment
4158   *  in ConnectBlock().
4159   *  Note that -reindex-chainstate skips the validation that happens here!
4160   */
4161  static bool ContextualCheckBlock(const CBlock& block, BlockValidationState& state, const ChainstateManager& chainman, const CBlockIndex* pindexPrev)
4162  {
4163      const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
4164  
4165      // Enforce BIP113 (Median Time Past).
4166      bool enforce_locktime_median_time_past{false};
4167      if (DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_CSV)) {
4168          assert(pindexPrev != nullptr);
4169          enforce_locktime_median_time_past = true;
4170      }
4171  
4172      const int64_t nLockTimeCutoff{enforce_locktime_median_time_past ?
4173                                        pindexPrev->GetMedianTimePast() :
4174                                        block.GetBlockTime()};
4175  
4176      // Check that all transactions are finalized
4177      for (const auto& tx : block.vtx) {
4178          if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
4179              return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal", "non-final transaction");
4180          }
4181      }
4182  
4183      // Enforce rule that the coinbase starts with serialized block height
4184      if (DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_HEIGHTINCB))
4185      {
4186          CScript expect = CScript() << nHeight;
4187          if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
4188              !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
4189              return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-height", "block height mismatch in coinbase");
4190          }
4191      }
4192  
4193      // Validation for witness commitments.
4194      // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
4195      //   coinbase (where 0x0000....0000 is used instead).
4196      // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness reserved value (unconstrained).
4197      // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
4198      // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
4199      //   {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness reserved value). In case there are
4200      //   multiple, the last one is used.
4201      if (!CheckWitnessMalleation(block, DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_SEGWIT), state)) {
4202          return false;
4203      }
4204  
4205      // After the coinbase witness reserved value and commitment are verified,
4206      // we can check if the block weight passes (before we've checked the
4207      // coinbase witness, it would be possible for the weight to be too
4208      // large by filling up the coinbase witness, which doesn't change
4209      // the block hash, so we couldn't mark the block as permanently
4210      // failed).
4211      if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
4212          return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-weight", strprintf("%s : weight limit failed", __func__));
4213      }
4214  
4215      return true;
4216  }
4217  
4218  bool ChainstateManager::AcceptBlockHeader(const CBlockHeader& block, BlockValidationState& state, CBlockIndex** ppindex, bool min_pow_checked)
4219  {
4220      AssertLockHeld(cs_main);
4221  
4222      // Check for duplicate
4223      uint256 hash = block.GetHash();
4224      BlockMap::iterator miSelf{m_blockman.m_block_index.find(hash)};
4225      if (hash != GetConsensus().hashGenesisBlock) {
4226          if (miSelf != m_blockman.m_block_index.end()) {
4227              // Block header is already known.
4228              CBlockIndex* pindex = &(miSelf->second);
4229              if (ppindex)
4230                  *ppindex = pindex;
4231              if (pindex->nStatus & BLOCK_FAILED_VALID) {
4232                  LogDebug(BCLog::VALIDATION, "%s: block %s is marked invalid\n", __func__, hash.ToString());
4233                  return state.Invalid(BlockValidationResult::BLOCK_CACHED_INVALID, "duplicate-invalid",
4234                                       strprintf("block %s was previously marked invalid", hash.ToString()));
4235              }
4236              return true;
4237          }
4238  
4239          if (!CheckBlockHeader(block, state, GetConsensus())) {
4240              LogDebug(BCLog::VALIDATION, "%s: Consensus::CheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
4241              return false;
4242          }
4243  
4244          // Get prev block index
4245          CBlockIndex* pindexPrev = nullptr;
4246          BlockMap::iterator mi{m_blockman.m_block_index.find(block.hashPrevBlock)};
4247          if (mi == m_blockman.m_block_index.end()) {
4248              LogDebug(BCLog::VALIDATION, "header %s has prev block not found: %s\n", hash.ToString(), block.hashPrevBlock.ToString());
4249              return state.Invalid(BlockValidationResult::BLOCK_MISSING_PREV, "prev-blk-not-found");
4250          }
4251          pindexPrev = &((*mi).second);
4252          if (pindexPrev->nStatus & BLOCK_FAILED_VALID) {
4253              LogDebug(BCLog::VALIDATION, "header %s has prev block invalid: %s\n", hash.ToString(), block.hashPrevBlock.ToString());
4254              return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
4255          }
4256          if (!ContextualCheckBlockHeader(block, state, m_blockman, *this, pindexPrev)) {
4257              LogDebug(BCLog::VALIDATION, "%s: Consensus::ContextualCheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
4258              return false;
4259          }
4260      }
4261      if (!min_pow_checked) {
4262          LogDebug(BCLog::VALIDATION, "%s: not adding new block header %s, missing anti-dos proof-of-work validation\n", __func__, hash.ToString());
4263          return state.Invalid(BlockValidationResult::BLOCK_HEADER_LOW_WORK, "too-little-chainwork");
4264      }
4265      CBlockIndex* pindex{m_blockman.AddToBlockIndex(block, m_best_header)};
4266  
4267      if (ppindex)
4268          *ppindex = pindex;
4269  
4270      return true;
4271  }
4272  
4273  // Exposed wrapper for AcceptBlockHeader
4274  bool ChainstateManager::ProcessNewBlockHeaders(std::span<const CBlockHeader> headers, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex)
4275  {
4276      AssertLockNotHeld(cs_main);
4277      {
4278          LOCK(cs_main);
4279          for (const CBlockHeader& header : headers) {
4280              CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
4281              bool accepted{AcceptBlockHeader(header, state, &pindex, min_pow_checked)};
4282              CheckBlockIndex();
4283  
4284              if (!accepted) {
4285                  return false;
4286              }
4287              if (ppindex) {
4288                  *ppindex = pindex;
4289              }
4290          }
4291      }
4292      if (NotifyHeaderTip()) {
4293          if (IsInitialBlockDownload() && ppindex && *ppindex) {
4294              const CBlockIndex& last_accepted{**ppindex};
4295              int64_t blocks_left{(NodeClock::now() - last_accepted.Time()) / GetConsensus().PowTargetSpacing()};
4296              blocks_left = std::max<int64_t>(0, blocks_left);
4297              const double progress{100.0 * last_accepted.nHeight / (last_accepted.nHeight + blocks_left)};
4298              LogInfo("Synchronizing blockheaders, height: %d (~%.2f%%)\n", last_accepted.nHeight, progress);
4299          }
4300      }
4301      return true;
4302  }
4303  
4304  void ChainstateManager::ReportHeadersPresync(int64_t height, int64_t timestamp)
4305  {
4306      AssertLockNotHeld(GetMutex());
4307      {
4308          LOCK(GetMutex());
4309          // Don't report headers presync progress if we already have a post-minchainwork header chain.
4310          // This means we lose reporting for potentially legitimate, but unlikely, deep reorgs, but
4311          // prevent attackers that spam low-work headers from filling our logs.
4312          if (m_best_header->nChainWork >= UintToArith256(GetConsensus().nMinimumChainWork)) return;
4313          // Rate limit headers presync updates to 4 per second, as these are not subject to DoS
4314          // protection.
4315          auto now = MockableSteadyClock::now();
4316          if (now < m_last_presync_update + std::chrono::milliseconds{250}) return;
4317          m_last_presync_update = now;
4318      }
4319      bool initial_download = IsInitialBlockDownload();
4320      GetNotifications().headerTip(GetSynchronizationState(initial_download, m_blockman.m_blockfiles_indexed), height, timestamp, /*presync=*/true);
4321      if (initial_download) {
4322          int64_t blocks_left{(NodeClock::now() - NodeSeconds{std::chrono::seconds{timestamp}}) / GetConsensus().PowTargetSpacing()};
4323          blocks_left = std::max<int64_t>(0, blocks_left);
4324          const double progress{100.0 * height / (height + blocks_left)};
4325          LogInfo("Pre-synchronizing blockheaders, height: %d (~%.2f%%)\n", height, progress);
4326      }
4327  }
4328  
4329  /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
4330  bool ChainstateManager::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock, bool min_pow_checked)
4331  {
4332      const CBlock& block = *pblock;
4333  
4334      if (fNewBlock) *fNewBlock = false;
4335      AssertLockHeld(cs_main);
4336  
4337      CBlockIndex *pindexDummy = nullptr;
4338      CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
4339  
4340      bool accepted_header{AcceptBlockHeader(block, state, &pindex, min_pow_checked)};
4341      CheckBlockIndex();
4342  
4343      if (!accepted_header)
4344          return false;
4345  
4346      // Check all requested blocks that we do not already have for validity and
4347      // save them to disk. Skip processing of unrequested blocks as an anti-DoS
4348      // measure, unless the blocks have more work than the active chain tip, and
4349      // aren't too far ahead of it, so are likely to be attached soon.
4350      bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
4351      bool fHasMoreOrSameWork = (ActiveTip() ? pindex->nChainWork >= ActiveTip()->nChainWork : true);
4352      // Blocks that are too out-of-order needlessly limit the effectiveness of
4353      // pruning, because pruning will not delete block files that contain any
4354      // blocks which are too close in height to the tip.  Apply this test
4355      // regardless of whether pruning is enabled; it should generally be safe to
4356      // not process unrequested blocks.
4357      bool fTooFarAhead{pindex->nHeight > ActiveHeight() + int(MIN_BLOCKS_TO_KEEP)};
4358  
4359      // TODO: Decouple this function from the block download logic by removing fRequested
4360      // This requires some new chain data structure to efficiently look up if a
4361      // block is in a chain leading to a candidate for best tip, despite not
4362      // being such a candidate itself.
4363      // Note that this would break the getblockfrompeer RPC
4364  
4365      // TODO: deal better with return value and error conditions for duplicate
4366      // and unrequested blocks.
4367      if (fAlreadyHave) return true;
4368      if (!fRequested) {  // If we didn't ask for it:
4369          if (pindex->nTx != 0) return true;    // This is a previously-processed block that was pruned
4370          if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
4371          if (fTooFarAhead) return true;        // Block height is too high
4372  
4373          // Protect against DoS attacks from low-work chains.
4374          // If our tip is behind, a peer could try to send us
4375          // low-work blocks on a fake chain that we would never
4376          // request; don't process these.
4377          if (pindex->nChainWork < MinimumChainWork()) return true;
4378      }
4379  
4380      const CChainParams& params{GetParams()};
4381  
4382      if (!CheckBlock(block, state, params.GetConsensus()) ||
4383          !ContextualCheckBlock(block, state, *this, pindex->pprev)) {
4384          if (Assume(state.IsInvalid())) {
4385              ActiveChainstate().InvalidBlockFound(pindex, state);
4386          }
4387          LogError("%s: %s\n", __func__, state.ToString());
4388          return false;
4389      }
4390  
4391      // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
4392      // (but if it does not build on our best tip, let the SendMessages loop relay it)
4393      if (!IsInitialBlockDownload() && ActiveTip() == pindex->pprev && m_options.signals) {
4394          m_options.signals->NewPoWValidBlock(pindex, pblock);
4395      }
4396  
4397      // Write block to history file
4398      if (fNewBlock) *fNewBlock = true;
4399      try {
4400          FlatFilePos blockPos{};
4401          if (dbp) {
4402              blockPos = *dbp;
4403              m_blockman.UpdateBlockInfo(block, pindex->nHeight, blockPos);
4404          } else {
4405              blockPos = m_blockman.WriteBlock(block, pindex->nHeight);
4406              if (blockPos.IsNull()) {
4407                  state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
4408                  return false;
4409              }
4410          }
4411          ReceivedBlockTransactions(block, pindex, blockPos);
4412      } catch (const std::runtime_error& e) {
4413          return FatalError(GetNotifications(), state, strprintf(_("System error while saving block to disk: %s"), e.what()));
4414      }
4415  
4416      // TODO: FlushStateToDisk() handles flushing of both block and chainstate
4417      // data, so we should move this to ChainstateManager so that we can be more
4418      // intelligent about how we flush.
4419      // For now, since FlushStateMode::NONE is used, all that can happen is that
4420      // the block files may be pruned, so we can just call this on one
4421      // chainstate (particularly if we haven't implemented pruning with
4422      // background validation yet).
4423      ActiveChainstate().FlushStateToDisk(state, FlushStateMode::NONE);
4424  
4425      CheckBlockIndex();
4426  
4427      return true;
4428  }
4429  
4430  bool ChainstateManager::ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block)
4431  {
4432      AssertLockNotHeld(cs_main);
4433  
4434      {
4435          CBlockIndex *pindex = nullptr;
4436          if (new_block) *new_block = false;
4437          BlockValidationState state;
4438  
4439          // CheckBlock() does not support multi-threaded block validation because CBlock::fChecked can cause data race.
4440          // Therefore, the following critical section must include the CheckBlock() call as well.
4441          LOCK(cs_main);
4442  
4443          // Skipping AcceptBlock() for CheckBlock() failures means that we will never mark a block as invalid if
4444          // CheckBlock() fails.  This is protective against consensus failure if there are any unknown forms of block
4445          // malleability that cause CheckBlock() to fail; see e.g. CVE-2012-2459 and
4446          // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-February/016697.html.  Because CheckBlock() is
4447          // not very expensive, the anti-DoS benefits of caching failure (of a definitely-invalid block) are not substantial.
4448          bool ret = CheckBlock(*block, state, GetConsensus());
4449          if (ret) {
4450              // Store to disk
4451              ret = AcceptBlock(block, state, &pindex, force_processing, nullptr, new_block, min_pow_checked);
4452          }
4453          if (!ret) {
4454              if (m_options.signals) {
4455                  m_options.signals->BlockChecked(block, state);
4456              }
4457              LogError("%s: AcceptBlock FAILED (%s)\n", __func__, state.ToString());
4458              return false;
4459          }
4460      }
4461  
4462      NotifyHeaderTip();
4463  
4464      BlockValidationState state; // Only used to report errors, not invalidity - ignore it
4465      if (!ActiveChainstate().ActivateBestChain(state, block)) {
4466          LogError("%s: ActivateBestChain failed (%s)\n", __func__, state.ToString());
4467          return false;
4468      }
4469  
4470      Chainstate* bg_chain{WITH_LOCK(cs_main, return HistoricalChainstate())};
4471      BlockValidationState bg_state;
4472      if (bg_chain && !bg_chain->ActivateBestChain(bg_state, block)) {
4473          LogError("%s: [background] ActivateBestChain failed (%s)\n", __func__, bg_state.ToString());
4474          return false;
4475       }
4476  
4477      return true;
4478  }
4479  
4480  MempoolAcceptResult ChainstateManager::ProcessTransaction(const CTransactionRef& tx, bool test_accept)
4481  {
4482      AssertLockHeld(cs_main);
4483      Chainstate& active_chainstate = ActiveChainstate();
4484      if (!active_chainstate.GetMempool()) {
4485          TxValidationState state;
4486          state.Invalid(TxValidationResult::TX_NO_MEMPOOL, "no-mempool");
4487          return MempoolAcceptResult::Failure(state);
4488      }
4489      auto result = AcceptToMemoryPool(active_chainstate, tx, GetTime(), /*bypass_limits=*/ false, test_accept);
4490      active_chainstate.GetMempool()->check(active_chainstate.CoinsTip(), active_chainstate.m_chain.Height() + 1);
4491      return result;
4492  }
4493  
4494  
4495  BlockValidationState TestBlockValidity(
4496      Chainstate& chainstate,
4497      const CBlock& block,
4498      const bool check_pow,
4499      const bool check_merkle_root)
4500  {
4501      // Lock must be held throughout this function for two reasons:
4502      // 1. We don't want the tip to change during several of the validation steps
4503      // 2. To prevent a CheckBlock() race condition for fChecked, see ProcessNewBlock()
4504      AssertLockHeld(chainstate.m_chainman.GetMutex());
4505  
4506      BlockValidationState state;
4507      CBlockIndex* tip{Assert(chainstate.m_chain.Tip())};
4508  
4509      if (block.hashPrevBlock != *Assert(tip->phashBlock)) {
4510          state.Invalid({}, "inconclusive-not-best-prevblk");
4511          return state;
4512      }
4513  
4514      // For signets CheckBlock() verifies the challenge iff fCheckPow is set.
4515      if (!CheckBlock(block, state, chainstate.m_chainman.GetConsensus(), /*fCheckPow=*/check_pow, /*fCheckMerkleRoot=*/check_merkle_root)) {
4516          // This should never happen, but belt-and-suspenders don't approve the
4517          // block if it does.
4518          if (state.IsValid()) NONFATAL_UNREACHABLE();
4519          return state;
4520      }
4521  
4522      /**
4523       * At this point ProcessNewBlock would call AcceptBlock(), but we
4524       * don't want to store the block or its header. Run individual checks
4525       * instead:
4526       * - skip AcceptBlockHeader() because:
4527       *   - we don't want to update the block index
4528       *   - we do not care about duplicates
4529       *   - we already ran CheckBlockHeader() via CheckBlock()
4530       *   - we already checked for prev-blk-not-found
4531       *   - we know the tip is valid, so no need to check bad-prevblk
4532       * - we already ran CheckBlock()
4533       * - do run ContextualCheckBlockHeader()
4534       * - do run ContextualCheckBlock()
4535       */
4536  
4537      if (!ContextualCheckBlockHeader(block, state, chainstate.m_blockman, chainstate.m_chainman, tip)) {
4538          if (state.IsValid()) NONFATAL_UNREACHABLE();
4539          return state;
4540      }
4541  
4542      if (!ContextualCheckBlock(block, state, chainstate.m_chainman, tip)) {
4543          if (state.IsValid()) NONFATAL_UNREACHABLE();
4544          return state;
4545      }
4546  
4547      // We don't want ConnectBlock to update the actual chainstate, so create
4548      // a cache on top of it, along with a dummy block index.
4549      CBlockIndex index_dummy{block};
4550      uint256 block_hash(block.GetHash());
4551      index_dummy.pprev = tip;
4552      index_dummy.nHeight = tip->nHeight + 1;
4553      index_dummy.phashBlock = &block_hash;
4554      CCoinsViewCache view_dummy(&chainstate.CoinsTip());
4555  
4556      // Set fJustCheck to true in order to update, and not clear, validation caches.
4557      if(!chainstate.ConnectBlock(block, state, &index_dummy, view_dummy, /*fJustCheck=*/true)) {
4558          if (state.IsValid()) NONFATAL_UNREACHABLE();
4559          return state;
4560      }
4561  
4562      // Ensure no check returned successfully while also setting an invalid state.
4563      if (!state.IsValid()) NONFATAL_UNREACHABLE();
4564  
4565      return state;
4566  }
4567  
4568  /* This function is called from the RPC code for pruneblockchain */
4569  void PruneBlockFilesManual(Chainstate& active_chainstate, int nManualPruneHeight)
4570  {
4571      BlockValidationState state;
4572      if (!active_chainstate.FlushStateToDisk(
4573              state, FlushStateMode::NONE, nManualPruneHeight)) {
4574          LogWarning("Failed to flush state after manual prune (%s)", state.ToString());
4575      }
4576  }
4577  
4578  bool Chainstate::LoadChainTip()
4579  {
4580      AssertLockHeld(cs_main);
4581      const CCoinsViewCache& coins_cache = CoinsTip();
4582      assert(!coins_cache.GetBestBlock().IsNull()); // Never called when the coins view is empty
4583      CBlockIndex* tip = m_chain.Tip();
4584  
4585      if (tip && tip->GetBlockHash() == coins_cache.GetBestBlock()) {
4586          return true;
4587      }
4588  
4589      // Load pointer to end of best chain
4590      CBlockIndex* pindex = m_blockman.LookupBlockIndex(coins_cache.GetBestBlock());
4591      if (!pindex) {
4592          return false;
4593      }
4594      m_chain.SetTip(*pindex);
4595      m_chainman.UpdateIBDStatus();
4596      tip = m_chain.Tip();
4597  
4598      // nSequenceId is one of the keys used to sort setBlockIndexCandidates. Ensure all
4599      // candidate sets are empty to avoid UB, as nSequenceId is about to be modified.
4600      for (const auto& cs : m_chainman.m_chainstates) {
4601          assert(cs->setBlockIndexCandidates.empty());
4602      }
4603  
4604      // Make sure our chain tip before shutting down scores better than any other candidate
4605      // to maintain a consistent best tip over reboots in case of a tie.
4606      auto target = tip;
4607      while (target) {
4608          target->nSequenceId = SEQ_ID_BEST_CHAIN_FROM_DISK;
4609          target = target->pprev;
4610      }
4611  
4612      LogInfo("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f",
4613                tip->GetBlockHash().ToString(),
4614                m_chain.Height(),
4615                FormatISO8601DateTime(tip->GetBlockTime()),
4616                m_chainman.GuessVerificationProgress(tip));
4617  
4618      // Ensure KernelNotifications m_tip_block is set even if no new block arrives.
4619      if (!this->GetRole().historical) {
4620          // Ignoring return value for now.
4621          (void)m_chainman.GetNotifications().blockTip(
4622              /*state=*/GetSynchronizationState(/*init=*/true, m_chainman.m_blockman.m_blockfiles_indexed),
4623              /*index=*/*pindex,
4624              /*verification_progress=*/m_chainman.GuessVerificationProgress(tip));
4625      }
4626  
4627      CheckForkWarningConditions();
4628  
4629      return true;
4630  }
4631  
4632  CVerifyDB::CVerifyDB(Notifications& notifications)
4633      : m_notifications{notifications}
4634  {
4635      m_notifications.progress(_("Verifying blocks…"), 0, false);
4636  }
4637  
4638  CVerifyDB::~CVerifyDB()
4639  {
4640      m_notifications.progress(bilingual_str{}, 100, false);
4641  }
4642  
4643  VerifyDBResult CVerifyDB::VerifyDB(
4644      Chainstate& chainstate,
4645      const Consensus::Params& consensus_params,
4646      CCoinsView& coinsview,
4647      int nCheckLevel, int nCheckDepth)
4648  {
4649      AssertLockHeld(cs_main);
4650  
4651      if (chainstate.m_chain.Tip() == nullptr || chainstate.m_chain.Tip()->pprev == nullptr) {
4652          return VerifyDBResult::SUCCESS;
4653      }
4654  
4655      // Verify blocks in the best chain
4656      if (nCheckDepth <= 0 || nCheckDepth > chainstate.m_chain.Height()) {
4657          nCheckDepth = chainstate.m_chain.Height();
4658      }
4659      nCheckLevel = std::max(0, std::min(4, nCheckLevel));
4660      LogInfo("Verifying last %i blocks at level %i", nCheckDepth, nCheckLevel);
4661      CCoinsViewCache coins(&coinsview);
4662      CBlockIndex* pindex;
4663      CBlockIndex* pindexFailure = nullptr;
4664      int nGoodTransactions = 0;
4665      BlockValidationState state;
4666      int reportDone = 0;
4667      bool skipped_no_block_data{false};
4668      bool skipped_l3_checks{false};
4669      LogInfo("Verification progress: 0%%");
4670  
4671      const bool is_snapshot_cs{chainstate.m_from_snapshot_blockhash};
4672  
4673      for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
4674          const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
4675          if (reportDone < percentageDone / 10) {
4676              // report every 10% step
4677              LogInfo("Verification progress: %d%%", percentageDone);
4678              reportDone = percentageDone / 10;
4679          }
4680          m_notifications.progress(_("Verifying blocks…"), percentageDone, false);
4681          if (pindex->nHeight <= chainstate.m_chain.Height() - nCheckDepth) {
4682              break;
4683          }
4684          if ((chainstate.m_blockman.IsPruneMode() || is_snapshot_cs) && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
4685              // If pruning or running under an assumeutxo snapshot, only go
4686              // back as far as we have data.
4687              LogInfo("Block verification stopping at height %d (no data). This could be due to pruning or use of an assumeutxo snapshot.", pindex->nHeight);
4688              skipped_no_block_data = true;
4689              break;
4690          }
4691          CBlock block;
4692          // check level 0: read from disk
4693          if (!chainstate.m_blockman.ReadBlock(block, *pindex)) {
4694              LogError("Verification error: ReadBlock failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4695              return VerifyDBResult::CORRUPTED_BLOCK_DB;
4696          }
4697          // check level 1: verify block validity
4698          if (nCheckLevel >= 1 && !CheckBlock(block, state, consensus_params)) {
4699              LogError("Verification error: found bad block at %d, hash=%s (%s)",
4700                        pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
4701              return VerifyDBResult::CORRUPTED_BLOCK_DB;
4702          }
4703          // check level 2: verify undo validity
4704          if (nCheckLevel >= 2 && pindex) {
4705              CBlockUndo undo;
4706              if (!pindex->GetUndoPos().IsNull()) {
4707                  if (!chainstate.m_blockman.ReadBlockUndo(undo, *pindex)) {
4708                      LogError("Verification error: found bad undo data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4709                      return VerifyDBResult::CORRUPTED_BLOCK_DB;
4710                  }
4711              }
4712          }
4713          // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
4714          size_t curr_coins_usage = coins.DynamicMemoryUsage() + chainstate.CoinsTip().DynamicMemoryUsage();
4715  
4716          if (nCheckLevel >= 3) {
4717              if (curr_coins_usage <= chainstate.m_coinstip_cache_size_bytes) {
4718                  assert(coins.GetBestBlock() == pindex->GetBlockHash());
4719                  DisconnectResult res = chainstate.DisconnectBlock(block, pindex, coins);
4720                  if (res == DISCONNECT_FAILED) {
4721                      LogError("Verification error: irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4722                      return VerifyDBResult::CORRUPTED_BLOCK_DB;
4723                  }
4724                  if (res == DISCONNECT_UNCLEAN) {
4725                      nGoodTransactions = 0;
4726                      pindexFailure = pindex;
4727                  } else {
4728                      nGoodTransactions += block.vtx.size();
4729                  }
4730              } else {
4731                  skipped_l3_checks = true;
4732              }
4733          }
4734          if (chainstate.m_chainman.m_interrupt) return VerifyDBResult::INTERRUPTED;
4735      }
4736      if (pindexFailure) {
4737          LogError("Verification error: coin database inconsistencies found (last %i blocks, %i good transactions before that)", chainstate.m_chain.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
4738          return VerifyDBResult::CORRUPTED_BLOCK_DB;
4739      }
4740      if (skipped_l3_checks) {
4741          LogWarning("Skipped verification of level >=3 (insufficient database cache size). Consider increasing -dbcache.");
4742      }
4743  
4744      // store block count as we move pindex at check level >= 4
4745      int block_count = chainstate.m_chain.Height() - pindex->nHeight;
4746  
4747      // check level 4: try reconnecting blocks
4748      if (nCheckLevel >= 4 && !skipped_l3_checks) {
4749          while (pindex != chainstate.m_chain.Tip()) {
4750              const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
4751              if (reportDone < percentageDone / 10) {
4752                  // report every 10% step
4753                  LogInfo("Verification progress: %d%%", percentageDone);
4754                  reportDone = percentageDone / 10;
4755              }
4756              m_notifications.progress(_("Verifying blocks…"), percentageDone, false);
4757              pindex = chainstate.m_chain.Next(pindex);
4758              CBlock block;
4759              if (!chainstate.m_blockman.ReadBlock(block, *pindex)) {
4760                  LogError("Verification error: ReadBlock failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4761                  return VerifyDBResult::CORRUPTED_BLOCK_DB;
4762              }
4763              if (!chainstate.ConnectBlock(block, state, pindex, coins)) {
4764                  LogError("Verification error: found unconnectable block at %d, hash=%s (%s)", pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
4765                  return VerifyDBResult::CORRUPTED_BLOCK_DB;
4766              }
4767              if (chainstate.m_chainman.m_interrupt) return VerifyDBResult::INTERRUPTED;
4768          }
4769      }
4770  
4771      LogInfo("Verification: No coin database inconsistencies in last %i blocks (%i transactions)", block_count, nGoodTransactions);
4772  
4773      if (skipped_l3_checks) {
4774          return VerifyDBResult::SKIPPED_L3_CHECKS;
4775      }
4776      if (skipped_no_block_data) {
4777          return VerifyDBResult::SKIPPED_MISSING_BLOCKS;
4778      }
4779      return VerifyDBResult::SUCCESS;
4780  }
4781  
4782  /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
4783  bool Chainstate::RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs)
4784  {
4785      AssertLockHeld(cs_main);
4786      // TODO: merge with ConnectBlock
4787      CBlock block;
4788      if (!m_blockman.ReadBlock(block, *pindex)) {
4789          LogError("ReplayBlock(): ReadBlock failed at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4790          return false;
4791      }
4792  
4793      for (const CTransactionRef& tx : block.vtx) {
4794          if (!tx->IsCoinBase()) {
4795              for (const CTxIn &txin : tx->vin) {
4796                  inputs.SpendCoin(txin.prevout);
4797              }
4798          }
4799          // Pass check = true as every addition may be an overwrite.
4800          AddCoins(inputs, *tx, pindex->nHeight, true);
4801      }
4802      return true;
4803  }
4804  
4805  bool Chainstate::ReplayBlocks()
4806  {
4807      LOCK(cs_main);
4808  
4809      CCoinsView& db = this->CoinsDB();
4810      CCoinsViewCache cache(&db);
4811  
4812      std::vector<uint256> hashHeads = db.GetHeadBlocks();
4813      if (hashHeads.empty()) return true; // We're already in a consistent state.
4814      if (hashHeads.size() != 2) {
4815          LogError("ReplayBlocks(): unknown inconsistent state\n");
4816          return false;
4817      }
4818  
4819      m_chainman.GetNotifications().progress(_("Replaying blocks…"), 0, false);
4820      LogInfo("Replaying blocks");
4821  
4822      const CBlockIndex* pindexOld = nullptr;  // Old tip during the interrupted flush.
4823      const CBlockIndex* pindexNew;            // New tip during the interrupted flush.
4824      const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
4825  
4826      if (!m_blockman.m_block_index.contains(hashHeads[0])) {
4827          LogError("ReplayBlocks(): reorganization to unknown block requested\n");
4828          return false;
4829      }
4830      pindexNew = &(m_blockman.m_block_index[hashHeads[0]]);
4831  
4832      if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
4833          if (!m_blockman.m_block_index.contains(hashHeads[1])) {
4834              LogError("ReplayBlocks(): reorganization from unknown block requested\n");
4835              return false;
4836          }
4837          pindexOld = &(m_blockman.m_block_index[hashHeads[1]]);
4838          pindexFork = LastCommonAncestor(pindexOld, pindexNew);
4839          assert(pindexFork != nullptr);
4840      }
4841  
4842      // Rollback along the old branch.
4843      const int nForkHeight{pindexFork ? pindexFork->nHeight : 0};
4844      if (pindexOld != pindexFork) {
4845          LogInfo("Rolling back from %s (%i to %i)", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight, nForkHeight);
4846          while (pindexOld != pindexFork) {
4847              if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
4848                  CBlock block;
4849                  if (!m_blockman.ReadBlock(block, *pindexOld)) {
4850                      LogError("RollbackBlock(): ReadBlock() failed at %d, hash=%s\n", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4851                      return false;
4852                  }
4853                  if (pindexOld->nHeight % 10'000 == 0) {
4854                      LogInfo("Rolling back %s (%i)", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
4855                  }
4856                  DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
4857                  if (res == DISCONNECT_FAILED) {
4858                      LogError("RollbackBlock(): DisconnectBlock failed at %d, hash=%s\n", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4859                      return false;
4860                  }
4861                  // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
4862                  // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
4863                  // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
4864                  // the result is still a version of the UTXO set with the effects of that block undone.
4865              }
4866              pindexOld = pindexOld->pprev;
4867          }
4868          LogInfo("Rolled back to %s", pindexFork->GetBlockHash().ToString());
4869      }
4870  
4871      // Roll forward from the forking point to the new tip.
4872      if (nForkHeight < pindexNew->nHeight) {
4873          LogInfo("Rolling forward to %s (%i to %i)", pindexNew->GetBlockHash().ToString(), nForkHeight, pindexNew->nHeight);
4874          for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
4875              const CBlockIndex& pindex{*Assert(pindexNew->GetAncestor(nHeight))};
4876  
4877              if (nHeight % 10'000 == 0) {
4878                  LogInfo("Rolling forward %s (%i)", pindex.GetBlockHash().ToString(), nHeight);
4879              }
4880              m_chainman.GetNotifications().progress(_("Replaying blocks…"), (int)((nHeight - nForkHeight) * 100.0 / (pindexNew->nHeight - nForkHeight)), false);
4881              if (!RollforwardBlock(&pindex, cache)) return false;
4882          }
4883          LogInfo("Rolled forward to %s", pindexNew->GetBlockHash().ToString());
4884      }
4885  
4886      cache.SetBestBlock(pindexNew->GetBlockHash());
4887      cache.Flush(/*reallocate_cache=*/false); // local CCoinsViewCache goes out of scope
4888      m_chainman.GetNotifications().progress(bilingual_str{}, 100, false);
4889      return true;
4890  }
4891  
4892  bool Chainstate::NeedsRedownload() const
4893  {
4894      AssertLockHeld(cs_main);
4895  
4896      // At and above m_params.SegwitHeight, segwit consensus rules must be validated
4897      CBlockIndex* block{m_chain.Tip()};
4898  
4899      while (block != nullptr && DeploymentActiveAt(*block, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) {
4900          if (!(block->nStatus & BLOCK_OPT_WITNESS)) {
4901              // block is insufficiently validated for a segwit client
4902              return true;
4903          }
4904          block = block->pprev;
4905      }
4906  
4907      return false;
4908  }
4909  
4910  void Chainstate::ClearBlockIndexCandidates()
4911  {
4912      AssertLockHeld(::cs_main);
4913      setBlockIndexCandidates.clear();
4914  }
4915  
4916  void Chainstate::PopulateBlockIndexCandidates()
4917  {
4918      AssertLockHeld(::cs_main);
4919  
4920      for (CBlockIndex* pindex : m_blockman.GetAllBlockIndices()) {
4921          // With assumeutxo, the snapshot block is a candidate for the tip, but it
4922          // may not have BLOCK_VALID_TRANSACTIONS (e.g. if we haven't yet downloaded
4923          // the block), so we special-case it here.
4924          if (pindex == SnapshotBase() || pindex == TargetBlock() ||
4925                  (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) &&
4926                   (pindex->HaveNumChainTxs() || pindex->pprev == nullptr))) {
4927              TryAddBlockIndexCandidate(pindex);
4928          }
4929      }
4930  }
4931  
4932  bool ChainstateManager::LoadBlockIndex()
4933  {
4934      AssertLockHeld(cs_main);
4935      // Load block index from databases
4936      if (m_blockman.m_blockfiles_indexed) {
4937          bool ret{m_blockman.LoadBlockIndexDB(CurrentChainstate().m_from_snapshot_blockhash)};
4938          if (!ret) return false;
4939  
4940          m_blockman.ScanAndUnlinkAlreadyPrunedFiles();
4941  
4942          std::vector<CBlockIndex*> vSortedByHeight{m_blockman.GetAllBlockIndices()};
4943          std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
4944                    CBlockIndexHeightOnlyComparator());
4945  
4946          for (CBlockIndex* pindex : vSortedByHeight) {
4947              if (m_interrupt) return false;
4948              if (pindex->nStatus & BLOCK_FAILED_VALID && (!m_best_invalid || pindex->nChainWork > m_best_invalid->nChainWork)) {
4949                  m_best_invalid = pindex;
4950              }
4951              if (pindex->IsValid(BLOCK_VALID_TREE) && (m_best_header == nullptr || CBlockIndexWorkComparator()(m_best_header, pindex)))
4952                  m_best_header = pindex;
4953          }
4954      }
4955      return true;
4956  }
4957  
4958  bool Chainstate::LoadGenesisBlock()
4959  {
4960      LOCK(cs_main);
4961  
4962      const CChainParams& params{m_chainman.GetParams()};
4963  
4964      // Check whether we're already initialized by checking for genesis in
4965      // m_blockman.m_block_index. Note that we can't use m_chain here, since it is
4966      // set based on the coins db, not the block index db, which is the only
4967      // thing loaded at this point.
4968      if (m_blockman.m_block_index.contains(params.GenesisBlock().GetHash()))
4969          return true;
4970  
4971      try {
4972          const CBlock& block = params.GenesisBlock();
4973          FlatFilePos blockPos{m_blockman.WriteBlock(block, 0)};
4974          if (blockPos.IsNull()) {
4975              LogError("%s: writing genesis block to disk failed\n", __func__);
4976              return false;
4977          }
4978          CBlockIndex* pindex = m_blockman.AddToBlockIndex(block, m_chainman.m_best_header);
4979          m_chainman.ReceivedBlockTransactions(block, pindex, blockPos);
4980      } catch (const std::runtime_error& e) {
4981          LogError("%s: failed to write genesis block: %s\n", __func__, e.what());
4982          return false;
4983      }
4984  
4985      return true;
4986  }
4987  
4988  void ChainstateManager::LoadExternalBlockFile(
4989      AutoFile& file_in,
4990      FlatFilePos* dbp,
4991      std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent)
4992  {
4993      // Either both should be specified (-reindex), or neither (-loadblock).
4994      assert(!dbp == !blocks_with_unknown_parent);
4995  
4996      const auto start{SteadyClock::now()};
4997      const CChainParams& params{GetParams()};
4998  
4999      int nLoaded = 0;
5000      try {
5001          BufferedFile blkdat{file_in, 2 * MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE + 8};
5002          // nRewind indicates where to resume scanning in case something goes wrong,
5003          // such as a block fails to deserialize.
5004          uint64_t nRewind = blkdat.GetPos();
5005          while (!blkdat.eof()) {
5006              if (m_interrupt) return;
5007  
5008              blkdat.SetPos(nRewind);
5009              nRewind++; // start one byte further next time, in case of failure
5010              blkdat.SetLimit(); // remove former limit
5011              unsigned int nSize = 0;
5012              try {
5013                  // locate a header
5014                  MessageStartChars buf;
5015                  blkdat.FindByte(std::byte(params.MessageStart()[0]));
5016                  nRewind = blkdat.GetPos() + 1;
5017                  blkdat >> buf;
5018                  if (buf != params.MessageStart()) {
5019                      continue;
5020                  }
5021                  // read size
5022                  blkdat >> nSize;
5023                  if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
5024                      continue;
5025              } catch (const std::exception&) {
5026                  // no valid block header found; don't complain
5027                  // (this happens at the end of every blk.dat file)
5028                  break;
5029              }
5030              try {
5031                  // read block header
5032                  const uint64_t nBlockPos{blkdat.GetPos()};
5033                  if (dbp)
5034                      dbp->nPos = nBlockPos;
5035                  blkdat.SetLimit(nBlockPos + nSize);
5036                  CBlockHeader header;
5037                  blkdat >> header;
5038                  const uint256 hash{header.GetHash()};
5039                  // Skip the rest of this block (this may read from disk into memory); position to the marker before the
5040                  // next block, but it's still possible to rewind to the start of the current block (without a disk read).
5041                  nRewind = nBlockPos + nSize;
5042                  blkdat.SkipTo(nRewind);
5043  
5044                  std::shared_ptr<CBlock> pblock{}; // needs to remain available after the cs_main lock is released to avoid duplicate reads from disk
5045  
5046                  {
5047                      LOCK(cs_main);
5048                      // detect out of order blocks, and store them for later
5049                      if (hash != params.GetConsensus().hashGenesisBlock && !m_blockman.LookupBlockIndex(header.hashPrevBlock)) {
5050                          LogDebug(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
5051                                   header.hashPrevBlock.ToString());
5052                          if (dbp && blocks_with_unknown_parent) {
5053                              blocks_with_unknown_parent->emplace(header.hashPrevBlock, *dbp);
5054                          }
5055                          continue;
5056                      }
5057  
5058                      // process in case the block isn't known yet
5059                      const CBlockIndex* pindex = m_blockman.LookupBlockIndex(hash);
5060                      if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) {
5061                          // This block can be processed immediately; rewind to its start, read and deserialize it.
5062                          blkdat.SetPos(nBlockPos);
5063                          pblock = std::make_shared<CBlock>();
5064                          blkdat >> TX_WITH_WITNESS(*pblock);
5065                          nRewind = blkdat.GetPos();
5066  
5067                          BlockValidationState state;
5068                          if (AcceptBlock(pblock, state, nullptr, true, dbp, nullptr, true)) {
5069                              nLoaded++;
5070                          }
5071                          if (state.IsError()) {
5072                              break;
5073                          }
5074                      } else if (hash != params.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
5075                          LogDebug(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
5076                      }
5077                  }
5078  
5079                  // Activate the genesis block so normal node progress can continue
5080                  // During first -reindex, this will only connect Genesis since
5081                  // ActivateBestChain only connects blocks which are in the block tree db,
5082                  // which only contains blocks whose parents are in it.
5083                  // But do this only if genesis isn't activated yet, to avoid connecting many blocks
5084                  // without assumevalid in the case of a continuation of a reindex that
5085                  // was interrupted by the user.
5086                  if (hash == params.GetConsensus().hashGenesisBlock && WITH_LOCK(::cs_main, return ActiveHeight()) == -1) {
5087                      BlockValidationState state;
5088                      if (!ActiveChainstate().ActivateBestChain(state, nullptr)) {
5089                          break;
5090                      }
5091                  }
5092  
5093                  if (m_blockman.IsPruneMode() && m_blockman.m_blockfiles_indexed && pblock) {
5094                      // must update the tip for pruning to work while importing with -loadblock.
5095                      // this is a tradeoff to conserve disk space at the expense of time
5096                      // spent updating the tip to be able to prune.
5097                      // otherwise, ActivateBestChain won't be called by the import process
5098                      // until after all of the block files are loaded. ActivateBestChain can be
5099                      // called by concurrent network message processing. but, that is not
5100                      // reliable for the purpose of pruning while importing.
5101                      if (auto result{ActivateBestChains()}; !result) {
5102                          LogDebug(BCLog::REINDEX, "%s\n", util::ErrorString(result).original);
5103                          break;
5104                      }
5105                  }
5106  
5107                  NotifyHeaderTip();
5108  
5109                  if (!blocks_with_unknown_parent) continue;
5110  
5111                  // Recursively process earlier encountered successors of this block
5112                  std::deque<uint256> queue;
5113                  queue.push_back(hash);
5114                  while (!queue.empty()) {
5115                      uint256 head = queue.front();
5116                      queue.pop_front();
5117                      auto range = blocks_with_unknown_parent->equal_range(head);
5118                      while (range.first != range.second) {
5119                          std::multimap<uint256, FlatFilePos>::iterator it = range.first;
5120                          std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
5121                          if (m_blockman.ReadBlock(*pblockrecursive, it->second, {})) {
5122                              const auto& block_hash{pblockrecursive->GetHash()};
5123                              LogDebug(BCLog::REINDEX, "%s: Processing out of order child %s of %s", __func__, block_hash.ToString(), head.ToString());
5124                              LOCK(cs_main);
5125                              BlockValidationState dummy;
5126                              if (AcceptBlock(pblockrecursive, dummy, nullptr, true, &it->second, nullptr, true)) {
5127                                  nLoaded++;
5128                                  queue.push_back(block_hash);
5129                              }
5130                          }
5131                          range.first++;
5132                          blocks_with_unknown_parent->erase(it);
5133                          NotifyHeaderTip();
5134                      }
5135                  }
5136              } catch (const std::exception& e) {
5137                  // historical bugs added extra data to the block files that does not deserialize cleanly.
5138                  // commonly this data is between readable blocks, but it does not really matter. such data is not fatal to the import process.
5139                  // the code that reads the block files deals with invalid data by simply ignoring it.
5140                  // it continues to search for the next {4 byte magic message start bytes + 4 byte length + block} that does deserialize cleanly
5141                  // and passes all of the other block validation checks dealing with POW and the merkle root, etc...
5142                  // we merely note with this informational log message when unexpected data is encountered.
5143                  // we could also be experiencing a storage system read error, or a read of a previous bad write. these are possible, but
5144                  // less likely scenarios. we don't have enough information to tell a difference here.
5145                  // the reindex process is not the place to attempt to clean and/or compact the block files. if so desired, a studious node operator
5146                  // may use knowledge of the fact that the block files are not entirely pristine in order to prepare a set of pristine, and
5147                  // perhaps ordered, block files for later reindexing.
5148                  LogDebug(BCLog::REINDEX, "%s: unexpected data at file offset 0x%x - %s. continuing\n", __func__, (nRewind - 1), e.what());
5149              }
5150          }
5151      } catch (const std::runtime_error& e) {
5152          GetNotifications().fatalError(strprintf(_("System error while loading external block file: %s"), e.what()));
5153      }
5154      LogInfo("Loaded %i blocks from external file in %dms", nLoaded, Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
5155  }
5156  
5157  bool ChainstateManager::ShouldCheckBlockIndex() const
5158  {
5159      // Assert to verify Flatten() has been called.
5160      if (!*Assert(m_options.check_block_index)) return false;
5161      if (FastRandomContext().randrange(*m_options.check_block_index) >= 1) return false;
5162      return true;
5163  }
5164  
5165  void ChainstateManager::CheckBlockIndex() const
5166  {
5167      if (!ShouldCheckBlockIndex()) {
5168          return;
5169      }
5170  
5171      LOCK(cs_main);
5172  
5173      // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
5174      // so we have the genesis block in m_blockman.m_block_index but no active chain. (A few of the
5175      // tests when iterating the block tree require that m_chain has been initialized.)
5176      if (ActiveChain().Height() < 0) {
5177          assert(m_blockman.m_block_index.size() <= 1);
5178          return;
5179      }
5180  
5181      // Build forward-pointing data structure for the entire block tree.
5182      // For performance reasons, indexes of the best header chain are stored in a vector (within CChain).
5183      // All remaining blocks are stored in a multimap.
5184      // The best header chain can differ from the active chain: E.g. its entries may belong to blocks that
5185      // are not yet validated.
5186      CChain best_hdr_chain;
5187      assert(m_best_header);
5188      assert(!(m_best_header->nStatus & BLOCK_FAILED_VALID));
5189      best_hdr_chain.SetTip(*m_best_header);
5190  
5191      std::multimap<const CBlockIndex*, const CBlockIndex*> forward;
5192      for (auto& [_, block_index] : m_blockman.m_block_index) {
5193          // Only save indexes in forward that are not part of the best header chain.
5194          if (!best_hdr_chain.Contains(&block_index)) {
5195              // Only genesis, which must be part of the best header chain, can have a nullptr parent.
5196              assert(block_index.pprev);
5197              forward.emplace(block_index.pprev, &block_index);
5198          }
5199      }
5200      assert(forward.size() + best_hdr_chain.Height() + 1 == m_blockman.m_block_index.size());
5201  
5202      const CBlockIndex* pindex = best_hdr_chain[0];
5203      assert(pindex);
5204      // Iterate over the entire block tree, using depth-first search.
5205      // Along the way, remember whether there are blocks on the path from genesis
5206      // block being explored which are the first to have certain properties.
5207      size_t nNodes = 0;
5208      int nHeight = 0;
5209      const CBlockIndex* pindexFirstInvalid = nullptr;              // Oldest ancestor of pindex which is invalid.
5210      const CBlockIndex* pindexFirstMissing = nullptr;              // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA, since assumeutxo snapshot if used.
5211      const CBlockIndex* pindexFirstNeverProcessed = nullptr;       // Oldest ancestor of pindex for which nTx == 0, since assumeutxo snapshot if used.
5212      const CBlockIndex* pindexFirstNotTreeValid = nullptr;         // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
5213      const CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not), since assumeutxo snapshot if used.
5214      const CBlockIndex* pindexFirstNotChainValid = nullptr;        // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not), since assumeutxo snapshot if used.
5215      const CBlockIndex* pindexFirstNotScriptsValid = nullptr;      // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not), since assumeutxo snapshot if used.
5216  
5217      // After checking an assumeutxo snapshot block, reset pindexFirst pointers
5218      // to earlier blocks that have not been downloaded or validated yet, so
5219      // checks for later blocks can assume the earlier blocks were validated and
5220      // be stricter, testing for more requirements.
5221      const CBlockIndex* snap_base{CurrentChainstate().SnapshotBase()};
5222      const CBlockIndex *snap_first_missing{}, *snap_first_notx{}, *snap_first_notv{}, *snap_first_nocv{}, *snap_first_nosv{};
5223      auto snap_update_firsts = [&] {
5224          if (pindex == snap_base) {
5225              std::swap(snap_first_missing, pindexFirstMissing);
5226              std::swap(snap_first_notx, pindexFirstNeverProcessed);
5227              std::swap(snap_first_notv, pindexFirstNotTransactionsValid);
5228              std::swap(snap_first_nocv, pindexFirstNotChainValid);
5229              std::swap(snap_first_nosv, pindexFirstNotScriptsValid);
5230          }
5231      };
5232  
5233      while (pindex != nullptr) {
5234          nNodes++;
5235          if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
5236          if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
5237              pindexFirstMissing = pindex;
5238          }
5239          if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
5240          if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
5241  
5242          if (pindex->pprev != nullptr) {
5243              if (pindexFirstNotTransactionsValid == nullptr &&
5244                      (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) {
5245                  pindexFirstNotTransactionsValid = pindex;
5246              }
5247  
5248              if (pindexFirstNotChainValid == nullptr &&
5249                      (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) {
5250                  pindexFirstNotChainValid = pindex;
5251              }
5252  
5253              if (pindexFirstNotScriptsValid == nullptr &&
5254                      (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) {
5255                  pindexFirstNotScriptsValid = pindex;
5256              }
5257          }
5258  
5259          // Begin: actual consistency checks.
5260          if (pindex->pprev == nullptr) {
5261              // Genesis block checks.
5262              assert(pindex->GetBlockHash() == GetConsensus().hashGenesisBlock); // Genesis block's hash must match.
5263              for (const auto& c : m_chainstates) {
5264                  if (c->m_chain.Genesis() != nullptr) {
5265                      assert(pindex == c->m_chain.Genesis()); // The chain's genesis block must be this block.
5266                  }
5267              }
5268          }
5269          // nSequenceId can't be set higher than SEQ_ID_INIT_FROM_DISK{1} for blocks that aren't linked
5270          // (negative is used for preciousblock, SEQ_ID_BEST_CHAIN_FROM_DISK{0} for active chain when loaded from disk)
5271          if (!pindex->HaveNumChainTxs()) assert(pindex->nSequenceId <= SEQ_ID_INIT_FROM_DISK);
5272          // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
5273          // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
5274          if (!m_blockman.m_have_pruned) {
5275              // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
5276              assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
5277              assert(pindexFirstMissing == pindexFirstNeverProcessed);
5278          } else {
5279              // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
5280              if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
5281          }
5282          if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
5283          if (snap_base && snap_base->GetAncestor(pindex->nHeight) == pindex) {
5284              // Assumed-valid blocks should connect to the main chain.
5285              assert((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE);
5286          }
5287          // There should only be an nTx value if we have
5288          // actually seen a block's transactions.
5289          assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
5290          // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to HaveNumChainTxs().
5291          // HaveNumChainTxs will also be set in the assumeutxo snapshot block from snapshot metadata.
5292          assert((pindexFirstNeverProcessed == nullptr || pindex == snap_base) == pindex->HaveNumChainTxs());
5293          assert((pindexFirstNotTransactionsValid == nullptr || pindex == snap_base) == pindex->HaveNumChainTxs());
5294          assert(pindex->nHeight == nHeight); // nHeight must be consistent.
5295          assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
5296          assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
5297          assert(pindexFirstNotTreeValid == nullptr); // All m_blockman.m_block_index entries must at least be TREE valid
5298          if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
5299          if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
5300          if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
5301          if (pindexFirstInvalid == nullptr) {
5302              // Checks for not-invalid blocks.
5303              assert((pindex->nStatus & BLOCK_FAILED_VALID) == 0); // The failed flag cannot be set for blocks without invalid parents.
5304          } else {
5305              assert(pindex->nStatus & BLOCK_FAILED_VALID); // Invalid blocks and their descendants must be marked as invalid
5306          }
5307          // Make sure m_chain_tx_count sum is correctly computed.
5308          if (!pindex->pprev) {
5309              // If no previous block, nTx and m_chain_tx_count must be the same.
5310              assert(pindex->m_chain_tx_count == pindex->nTx);
5311          } else if (pindex->pprev->m_chain_tx_count > 0 && pindex->nTx > 0) {
5312              // If previous m_chain_tx_count is set and number of transactions in block is known, sum must be set.
5313              assert(pindex->m_chain_tx_count == pindex->nTx + pindex->pprev->m_chain_tx_count);
5314          } else {
5315              // Otherwise m_chain_tx_count should only be set if this is a snapshot
5316              // block, and must be set if it is.
5317              assert((pindex->m_chain_tx_count != 0) == (pindex == snap_base));
5318          }
5319          // There should be no block with more work than m_best_header, unless it's known to be invalid
5320          assert((pindex->nStatus & BLOCK_FAILED_VALID) || pindex->nChainWork <= m_best_header->nChainWork);
5321  
5322          // Chainstate-specific checks on setBlockIndexCandidates
5323          for (const auto& c : m_chainstates) {
5324              if (c->m_chain.Tip() == nullptr) continue;
5325              // Two main factors determine whether pindex is a candidate in
5326              // setBlockIndexCandidates:
5327              //
5328              // - If pindex has less work than the chain tip, it should not be a
5329              //   candidate, and this will be asserted below. Otherwise it is a
5330              //   potential candidate.
5331              //
5332              // - If pindex or one of its parent blocks back to the genesis block
5333              //   or an assumeutxo snapshot never downloaded transactions
5334              //   (pindexFirstNeverProcessed is non-null), it should not be a
5335              //   candidate, and this will be asserted below. The only exception
5336              //   is if pindex itself is an assumeutxo snapshot block. Then it is
5337              //   also a potential candidate.
5338              if (!CBlockIndexWorkComparator()(pindex, c->m_chain.Tip()) && (pindexFirstNeverProcessed == nullptr || pindex == snap_base)) {
5339                  // If pindex was detected as invalid (pindexFirstInvalid is
5340                  // non-null), it is not required to be in
5341                  // setBlockIndexCandidates.
5342                  if (pindexFirstInvalid == nullptr) {
5343                      // If pindex and all its parents back to the genesis block
5344                      // or an assumeutxo snapshot block downloaded transactions,
5345                      // and the transactions were not pruned (pindexFirstMissing
5346                      // is null), it is a potential candidate. The check
5347                      // excludes pruned blocks, because if any blocks were
5348                      // pruned between pindex and the current chain tip, pindex will
5349                      // only temporarily be added to setBlockIndexCandidates,
5350                      // before being moved to m_blocks_unlinked. This check
5351                      // could be improved to verify that if all blocks between
5352                      // the chain tip and pindex have data, pindex must be a
5353                      // candidate.
5354                      //
5355                      // If pindex is the chain tip, it also is a potential
5356                      // candidate.
5357                      //
5358                      // If the chainstate was loaded from a snapshot and pindex
5359                      // is the base of the snapshot, pindex is also a potential
5360                      // candidate.
5361                      if (pindexFirstMissing == nullptr || pindex == c->m_chain.Tip() || pindex == c->SnapshotBase()) {
5362                          // If this chainstate is not a historical chainstate
5363                          // targeting a specific block, pindex must be in
5364                          // setBlockIndexCandidates. Otherwise, pindex only
5365                          // needs to be added if it is an ancestor of the target
5366                          // block.
5367                          if (!c->TargetBlock() || c->TargetBlock()->GetAncestor(pindex->nHeight) == pindex) {
5368                              assert(c->setBlockIndexCandidates.contains(pindex));
5369                          }
5370                      }
5371                      // If some parent is missing, then it could be that this block was in
5372                      // setBlockIndexCandidates but had to be removed because of the missing data.
5373                      // In this case it must be in m_blocks_unlinked -- see test below.
5374                  }
5375              } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
5376                  assert(!c->setBlockIndexCandidates.contains(pindex));
5377              }
5378          }
5379          // Check whether this block is in m_blocks_unlinked.
5380          auto rangeUnlinked{m_blockman.m_blocks_unlinked.equal_range(pindex->pprev)};
5381          bool foundInUnlinked = false;
5382          while (rangeUnlinked.first != rangeUnlinked.second) {
5383              assert(rangeUnlinked.first->first == pindex->pprev);
5384              if (rangeUnlinked.first->second == pindex) {
5385                  foundInUnlinked = true;
5386                  break;
5387              }
5388              rangeUnlinked.first++;
5389          }
5390          if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
5391              // If this block has block data available, some parent was never received, and has no invalid parents, it must be in m_blocks_unlinked.
5392              assert(foundInUnlinked);
5393          }
5394          if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in m_blocks_unlinked if we don't HAVE_DATA
5395          if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in m_blocks_unlinked.
5396          if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
5397              // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
5398              assert(m_blockman.m_have_pruned);
5399              // This block may have entered m_blocks_unlinked if:
5400              //  - it has a descendant that at some point had more work than the
5401              //    tip, and
5402              //  - we tried switching to that descendant but were missing
5403              //    data for some intermediate block between m_chain and the
5404              //    tip.
5405              // So if this block is itself better than any m_chain.Tip() and it wasn't in
5406              // setBlockIndexCandidates, then it must be in m_blocks_unlinked.
5407              for (const auto& c : m_chainstates) {
5408                  if (!CBlockIndexWorkComparator()(pindex, c->m_chain.Tip()) && !c->setBlockIndexCandidates.contains(pindex)) {
5409                      if (pindexFirstInvalid == nullptr) {
5410                          if (!c->TargetBlock() || c->TargetBlock()->GetAncestor(pindex->nHeight) == pindex) {
5411                              assert(foundInUnlinked);
5412                          }
5413                      }
5414                  }
5415              }
5416          }
5417          // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
5418          // End: actual consistency checks.
5419  
5420  
5421          // Try descending into the first subnode. Always process forks first and the best header chain after.
5422          snap_update_firsts();
5423          auto range{forward.equal_range(pindex)};
5424          if (range.first != range.second) {
5425              // A subnode not part of the best header chain was found.
5426              pindex = range.first->second;
5427              nHeight++;
5428              continue;
5429          } else if (best_hdr_chain.Contains(pindex)) {
5430              // Descend further into best header chain.
5431              nHeight++;
5432              pindex = best_hdr_chain[nHeight];
5433              if (!pindex) break; // we are finished, since the best header chain is always processed last
5434              continue;
5435          }
5436          // This is a leaf node.
5437          // Move upwards until we reach a node of which we have not yet visited the last child.
5438          while (pindex) {
5439              // We are going to either move to a parent or a sibling of pindex.
5440              snap_update_firsts();
5441              // If pindex was the first with a certain property, unset the corresponding variable.
5442              if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
5443              if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
5444              if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
5445              if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
5446              if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
5447              if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
5448              if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
5449              // Find our parent.
5450              CBlockIndex* pindexPar = pindex->pprev;
5451              // Find which child we just visited.
5452              auto rangePar{forward.equal_range(pindexPar)};
5453              while (rangePar.first->second != pindex) {
5454                  assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
5455                  rangePar.first++;
5456              }
5457              // Proceed to the next one.
5458              rangePar.first++;
5459              if (rangePar.first != rangePar.second) {
5460                  // Move to a sibling not part of the best header chain.
5461                  pindex = rangePar.first->second;
5462                  break;
5463              } else if (pindexPar == best_hdr_chain[nHeight - 1]) {
5464                  // Move to pindex's sibling on the best-chain, if it has one.
5465                  pindex = best_hdr_chain[nHeight];
5466                  // There will not be a next block if (and only if) parent block is the best header.
5467                  assert((pindex == nullptr) == (pindexPar == best_hdr_chain.Tip()));
5468                  break;
5469              } else {
5470                  // Move up further.
5471                  pindex = pindexPar;
5472                  nHeight--;
5473                  continue;
5474              }
5475          }
5476      }
5477  
5478      // Check that we actually traversed the entire block index.
5479      assert(nNodes == forward.size() + best_hdr_chain.Height() + 1);
5480  }
5481  
5482  std::string Chainstate::ToString()
5483  {
5484      AssertLockHeld(::cs_main);
5485      CBlockIndex* tip = m_chain.Tip();
5486      return strprintf("Chainstate [%s] @ height %d (%s)",
5487                       m_from_snapshot_blockhash ? "snapshot" : "ibd",
5488                       tip ? tip->nHeight : -1, tip ? tip->GetBlockHash().ToString() : "null");
5489  }
5490  
5491  bool Chainstate::ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
5492  {
5493      AssertLockHeld(::cs_main);
5494      if (coinstip_size == m_coinstip_cache_size_bytes &&
5495              coinsdb_size == m_coinsdb_cache_size_bytes) {
5496          // Cache sizes are unchanged, no need to continue.
5497          return true;
5498      }
5499      size_t old_coinstip_size = m_coinstip_cache_size_bytes;
5500      m_coinstip_cache_size_bytes = coinstip_size;
5501      m_coinsdb_cache_size_bytes = coinsdb_size;
5502      CoinsDB().ResizeCache(coinsdb_size);
5503  
5504      LogInfo("[%s] resized coinsdb cache to %.1f MiB",
5505          this->ToString(), coinsdb_size * (1.0 / 1024 / 1024));
5506      LogInfo("[%s] resized coinstip cache to %.1f MiB",
5507          this->ToString(), coinstip_size * (1.0 / 1024 / 1024));
5508  
5509      BlockValidationState state;
5510      bool ret;
5511  
5512      if (coinstip_size > old_coinstip_size) {
5513          // Likely no need to flush if cache sizes have grown.
5514          ret = FlushStateToDisk(state, FlushStateMode::IF_NEEDED);
5515      } else {
5516          // Otherwise, flush state to disk and deallocate the in-memory coins map.
5517          ret = FlushStateToDisk(state, FlushStateMode::FORCE_FLUSH);
5518      }
5519      return ret;
5520  }
5521  
5522  double ChainstateManager::GuessVerificationProgress(const CBlockIndex* pindex) const
5523  {
5524      AssertLockHeld(GetMutex());
5525      const ChainTxData& data{GetParams().TxData()};
5526      if (pindex == nullptr) {
5527          return 0.0;
5528      }
5529  
5530      if (pindex->m_chain_tx_count == 0) {
5531          LogDebug(BCLog::VALIDATION, "Block %d has unset m_chain_tx_count. Unable to estimate verification progress.\n", pindex->nHeight);
5532          return 0.0;
5533      }
5534  
5535      const int64_t nNow{TicksSinceEpoch<std::chrono::seconds>(NodeClock::now())};
5536      const auto block_time{
5537          (Assume(m_best_header) && std::abs(nNow - pindex->GetBlockTime()) <= Ticks<std::chrono::seconds>(2h) &&
5538           Assume(m_best_header->nHeight >= pindex->nHeight)) ?
5539              // When the header is known to be recent, switch to a height-based
5540              // approach. This ensures the returned value is quantized when
5541              // close to "1.0", because some users expect it to be. This also
5542              // avoids relying too much on the exact miner-set timestamp, which
5543              // may be off.
5544              nNow - (m_best_header->nHeight - pindex->nHeight) * GetConsensus().nPowTargetSpacing :
5545              pindex->GetBlockTime(),
5546      };
5547  
5548      double fTxTotal;
5549  
5550      if (pindex->m_chain_tx_count <= data.tx_count) {
5551          fTxTotal = data.tx_count + (nNow - data.nTime) * data.dTxRate;
5552      } else {
5553          fTxTotal = pindex->m_chain_tx_count + (nNow - block_time) * data.dTxRate;
5554      }
5555  
5556      return std::min<double>(pindex->m_chain_tx_count / fTxTotal, 1.0);
5557  }
5558  
5559  Chainstate& ChainstateManager::InitializeChainstate(CTxMemPool* mempool)
5560  {
5561      AssertLockHeld(::cs_main);
5562      assert(m_chainstates.empty());
5563      m_chainstates.emplace_back(std::make_unique<Chainstate>(mempool, m_blockman, *this));
5564      return *m_chainstates.back();
5565  }
5566  
5567  [[nodiscard]] static bool DeleteCoinsDBFromDisk(const fs::path db_path, bool is_snapshot)
5568      EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
5569  {
5570      AssertLockHeld(::cs_main);
5571  
5572      if (is_snapshot) {
5573          fs::path base_blockhash_path = db_path / node::SNAPSHOT_BLOCKHASH_FILENAME;
5574  
5575          try {
5576              bool existed = fs::remove(base_blockhash_path);
5577              if (!existed) {
5578                  LogWarning("[snapshot] snapshot chainstate dir being removed lacks %s file",
5579                            fs::PathToString(node::SNAPSHOT_BLOCKHASH_FILENAME));
5580              }
5581          } catch (const fs::filesystem_error& e) {
5582              LogWarning("[snapshot] failed to remove file %s: %s\n",
5583                         fs::PathToString(base_blockhash_path), e.code().message());
5584          }
5585      }
5586  
5587      std::string path_str = fs::PathToString(db_path);
5588      LogInfo("Removing leveldb dir at %s\n", path_str);
5589  
5590      // We have to destruct before this call leveldb::DB in order to release the db
5591      // lock, otherwise `DestroyDB` will fail. See `leveldb::~DBImpl()`.
5592      const bool destroyed = DestroyDB(path_str);
5593  
5594      if (!destroyed) {
5595          LogError("leveldb DestroyDB call failed on %s", path_str);
5596      }
5597  
5598      // Datadir should be removed from filesystem; otherwise initialization may detect
5599      // it on subsequent statups and get confused.
5600      //
5601      // If the base_blockhash_path removal above fails in the case of snapshot
5602      // chainstates, this will return false since leveldb won't remove a non-empty
5603      // directory.
5604      return destroyed && !fs::exists(db_path);
5605  }
5606  
5607  util::Result<CBlockIndex*> ChainstateManager::ActivateSnapshot(
5608          AutoFile& coins_file,
5609          const SnapshotMetadata& metadata,
5610          bool in_memory)
5611  {
5612      uint256 base_blockhash = metadata.m_base_blockhash;
5613  
5614      CBlockIndex* snapshot_start_block{};
5615  
5616      {
5617          LOCK(::cs_main);
5618  
5619          if (this->CurrentChainstate().m_from_snapshot_blockhash) {
5620              return util::Error{Untranslated("Can't activate a snapshot-based chainstate more than once")};
5621          }
5622          if (!GetParams().AssumeutxoForBlockhash(base_blockhash).has_value()) {
5623              auto available_heights = GetParams().GetAvailableSnapshotHeights();
5624              std::string heights_formatted = util::Join(available_heights, ", ", [&](const auto& i) { return util::ToString(i); });
5625              return util::Error{Untranslated(strprintf("assumeutxo block hash in snapshot metadata not recognized (hash: %s). The following snapshot heights are available: %s",
5626                  base_blockhash.ToString(),
5627                  heights_formatted))};
5628          }
5629  
5630          snapshot_start_block = m_blockman.LookupBlockIndex(base_blockhash);
5631          if (!snapshot_start_block) {
5632              return util::Error{Untranslated(strprintf("The base block header (%s) must appear in the headers chain. Make sure all headers are syncing, and call loadtxoutset again",
5633                            base_blockhash.ToString()))};
5634          }
5635  
5636          bool start_block_invalid = snapshot_start_block->nStatus & BLOCK_FAILED_VALID;
5637          if (start_block_invalid) {
5638              return util::Error{Untranslated(strprintf("The base block header (%s) is part of an invalid chain", base_blockhash.ToString()))};
5639          }
5640  
5641          if (!m_best_header || m_best_header->GetAncestor(snapshot_start_block->nHeight) != snapshot_start_block) {
5642              return util::Error{Untranslated("A forked headers-chain with more work than the chain with the snapshot base block header exists. Please proceed to sync without AssumeUtxo.")};
5643          }
5644  
5645          auto mempool{CurrentChainstate().GetMempool()};
5646          if (mempool && mempool->size() > 0) {
5647              return util::Error{Untranslated("Can't activate a snapshot when mempool not empty")};
5648          }
5649      }
5650  
5651      int64_t current_coinsdb_cache_size{0};
5652      int64_t current_coinstip_cache_size{0};
5653  
5654      // Cache percentages to allocate to each chainstate.
5655      //
5656      // These particular percentages don't matter so much since they will only be
5657      // relevant during snapshot activation; caches are rebalanced at the conclusion of
5658      // this function. We want to give (essentially) all available cache capacity to the
5659      // snapshot to aid the bulk load later in this function.
5660      static constexpr double IBD_CACHE_PERC = 0.01;
5661      static constexpr double SNAPSHOT_CACHE_PERC = 0.99;
5662  
5663      {
5664          LOCK(::cs_main);
5665          // Resize the coins caches to ensure we're not exceeding memory limits.
5666          //
5667          // Allocate the majority of the cache to the incoming snapshot chainstate, since
5668          // (optimistically) getting to its tip will be the top priority. We'll need to call
5669          // `MaybeRebalanceCaches()` once we're done with this function to ensure
5670          // the right allocation (including the possibility that no snapshot was activated
5671          // and that we should restore the active chainstate caches to their original size).
5672          //
5673          current_coinsdb_cache_size = this->ActiveChainstate().m_coinsdb_cache_size_bytes;
5674          current_coinstip_cache_size = this->ActiveChainstate().m_coinstip_cache_size_bytes;
5675  
5676          // Temporarily resize the active coins cache to make room for the newly-created
5677          // snapshot chain.
5678          this->ActiveChainstate().ResizeCoinsCaches(
5679              static_cast<size_t>(current_coinstip_cache_size * IBD_CACHE_PERC),
5680              static_cast<size_t>(current_coinsdb_cache_size * IBD_CACHE_PERC));
5681      }
5682  
5683      auto snapshot_chainstate = WITH_LOCK(::cs_main,
5684          return std::make_unique<Chainstate>(
5685              /*mempool=*/nullptr, m_blockman, *this, base_blockhash));
5686  
5687      {
5688          LOCK(::cs_main);
5689          snapshot_chainstate->InitCoinsDB(
5690              static_cast<size_t>(current_coinsdb_cache_size * SNAPSHOT_CACHE_PERC),
5691              in_memory, /*should_wipe=*/false);
5692          snapshot_chainstate->InitCoinsCache(
5693              static_cast<size_t>(current_coinstip_cache_size * SNAPSHOT_CACHE_PERC));
5694      }
5695  
5696      auto cleanup_bad_snapshot = [&](bilingual_str reason) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
5697          this->MaybeRebalanceCaches();
5698  
5699          // PopulateAndValidateSnapshot can return (in error) before the leveldb datadir
5700          // has been created, so only attempt removal if we got that far.
5701          if (auto snapshot_datadir = node::FindAssumeutxoChainstateDir(m_options.datadir)) {
5702              // We have to destruct leveldb::DB in order to release the db lock, otherwise
5703              // DestroyDB() (in DeleteCoinsDBFromDisk()) will fail. See `leveldb::~DBImpl()`.
5704              // Destructing the chainstate (and so resetting the coinsviews object) does this.
5705              snapshot_chainstate.reset();
5706              bool removed = DeleteCoinsDBFromDisk(*snapshot_datadir, /*is_snapshot=*/true);
5707              if (!removed) {
5708                  GetNotifications().fatalError(strprintf(_("Failed to remove snapshot chainstate dir (%s). "
5709                      "Manually remove it before restarting.\n"), fs::PathToString(*snapshot_datadir)));
5710              }
5711          }
5712          return util::Error{std::move(reason)};
5713      };
5714  
5715      if (auto res{this->PopulateAndValidateSnapshot(*snapshot_chainstate, coins_file, metadata)}; !res) {
5716          LOCK(::cs_main);
5717          return cleanup_bad_snapshot(Untranslated(strprintf("Population failed: %s", util::ErrorString(res).original)));
5718      }
5719  
5720      LOCK(::cs_main);  // cs_main required for rest of snapshot activation.
5721  
5722      // Do a final check to ensure that the snapshot chainstate is actually a more
5723      // work chain than the active chainstate; a user could have loaded a snapshot
5724      // very late in the IBD process, and we wouldn't want to load a useless chainstate.
5725      if (!CBlockIndexWorkComparator()(ActiveTip(), snapshot_chainstate->m_chain.Tip())) {
5726          return cleanup_bad_snapshot(Untranslated("work does not exceed active chainstate"));
5727      }
5728      // If not in-memory, persist the base blockhash for use during subsequent
5729      // initialization.
5730      if (!in_memory) {
5731          if (!node::WriteSnapshotBaseBlockhash(*snapshot_chainstate)) {
5732              return cleanup_bad_snapshot(Untranslated("could not write base blockhash"));
5733          }
5734      }
5735  
5736      Chainstate& chainstate{AddChainstate(std::move(snapshot_chainstate))};
5737      m_blockman.m_snapshot_height = Assert(chainstate.SnapshotBase())->nHeight;
5738  
5739      chainstate.PopulateBlockIndexCandidates();
5740  
5741      LogInfo("[snapshot] successfully activated snapshot %s", base_blockhash.ToString());
5742      LogInfo("[snapshot] (%.2f MB)",
5743                chainstate.CoinsTip().DynamicMemoryUsage() / (1000 * 1000));
5744  
5745      this->MaybeRebalanceCaches();
5746      return snapshot_start_block;
5747  }
5748  
5749  static void FlushSnapshotToDisk(CCoinsViewCache& coins_cache, bool snapshot_loaded)
5750  {
5751      LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE(
5752          strprintf("%s (%.2f MB)",
5753                    snapshot_loaded ? "saving snapshot chainstate" : "flushing coins cache",
5754                    coins_cache.DynamicMemoryUsage() / (1000 * 1000)),
5755          BCLog::LogFlags::ALL);
5756  
5757      coins_cache.Flush();
5758  }
5759  
5760  struct StopHashingException : public std::exception
5761  {
5762      const char* what() const noexcept override
5763      {
5764          return "ComputeUTXOStats interrupted.";
5765      }
5766  };
5767  
5768  static void SnapshotUTXOHashBreakpoint(const util::SignalInterrupt& interrupt)
5769  {
5770      if (interrupt) throw StopHashingException();
5771  }
5772  
5773  util::Result<void> ChainstateManager::PopulateAndValidateSnapshot(
5774      Chainstate& snapshot_chainstate,
5775      AutoFile& coins_file,
5776      const SnapshotMetadata& metadata)
5777  {
5778      // It's okay to release cs_main before we're done using `coins_cache` because we know
5779      // that nothing else will be referencing the newly created snapshot_chainstate yet.
5780      CCoinsViewCache& coins_cache = *WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsTip());
5781  
5782      uint256 base_blockhash = metadata.m_base_blockhash;
5783  
5784      CBlockIndex* snapshot_start_block = WITH_LOCK(::cs_main, return m_blockman.LookupBlockIndex(base_blockhash));
5785  
5786      if (!snapshot_start_block) {
5787          // Needed for ComputeUTXOStats to determine the
5788          // height and to avoid a crash when base_blockhash.IsNull()
5789          return util::Error{Untranslated(strprintf("Did not find snapshot start blockheader %s",
5790                    base_blockhash.ToString()))};
5791      }
5792  
5793      int base_height = snapshot_start_block->nHeight;
5794      const auto& maybe_au_data = GetParams().AssumeutxoForHeight(base_height);
5795  
5796      if (!maybe_au_data) {
5797          return util::Error{Untranslated(strprintf("Assumeutxo height in snapshot metadata not recognized "
5798                    "(%d) - refusing to load snapshot", base_height))};
5799      }
5800  
5801      const AssumeutxoData& au_data = *maybe_au_data;
5802  
5803      // This work comparison is a duplicate check with the one performed later in
5804      // ActivateSnapshot(), but is done so that we avoid doing the long work of staging
5805      // a snapshot that isn't actually usable.
5806      if (WITH_LOCK(::cs_main, return !CBlockIndexWorkComparator()(ActiveTip(), snapshot_start_block))) {
5807          return util::Error{Untranslated("Work does not exceed active chainstate")};
5808      }
5809  
5810      const uint64_t coins_count = metadata.m_coins_count;
5811      uint64_t coins_left = metadata.m_coins_count;
5812  
5813      LogInfo("[snapshot] loading %d coins from snapshot %s", coins_left, base_blockhash.ToString());
5814      int64_t coins_processed{0};
5815  
5816      while (coins_left > 0) {
5817          try {
5818              Txid txid;
5819              coins_file >> txid;
5820              size_t coins_per_txid{0};
5821              coins_per_txid = ReadCompactSize(coins_file);
5822  
5823              if (coins_per_txid > coins_left) {
5824                  return util::Error{Untranslated("Mismatch in coins count in snapshot metadata and actual snapshot data")};
5825              }
5826  
5827              for (size_t i = 0; i < coins_per_txid; i++) {
5828                  COutPoint outpoint;
5829                  Coin coin;
5830                  outpoint.n = static_cast<uint32_t>(ReadCompactSize(coins_file));
5831                  outpoint.hash = txid;
5832                  coins_file >> coin;
5833                  if (coin.nHeight > base_height ||
5834                      outpoint.n >= std::numeric_limits<decltype(outpoint.n)>::max() // Avoid integer wrap-around in coinstats.cpp:ApplyHash
5835                  ) {
5836                      return util::Error{Untranslated(strprintf("Bad snapshot data after deserializing %d coins",
5837                                coins_count - coins_left))};
5838                  }
5839                  if (!MoneyRange(coin.out.nValue)) {
5840                      return util::Error{Untranslated(strprintf("Bad snapshot data after deserializing %d coins - bad tx out value",
5841                                coins_count - coins_left))};
5842                  }
5843                  coins_cache.EmplaceCoinInternalDANGER(std::move(outpoint), std::move(coin));
5844  
5845                  --coins_left;
5846                  ++coins_processed;
5847  
5848                  if (coins_processed % 1000000 == 0) {
5849                      LogInfo("[snapshot] %d coins loaded (%.2f%%, %.2f MB)",
5850                          coins_processed,
5851                          static_cast<float>(coins_processed) * 100 / static_cast<float>(coins_count),
5852                          coins_cache.DynamicMemoryUsage() / (1000 * 1000));
5853                  }
5854  
5855                  // Batch write and flush (if we need to) every so often.
5856                  //
5857                  // If our average Coin size is roughly 41 bytes, checking every 120,000 coins
5858                  // means <5MB of memory imprecision.
5859                  if (coins_processed % 120000 == 0) {
5860                      if (m_interrupt) {
5861                          return util::Error{Untranslated("Aborting after an interrupt was requested")};
5862                      }
5863  
5864                      const auto snapshot_cache_state = WITH_LOCK(::cs_main,
5865                          return snapshot_chainstate.GetCoinsCacheSizeState());
5866  
5867                      if (snapshot_cache_state >= CoinsCacheSizeState::CRITICAL) {
5868                          // This is a hack - we don't know what the actual best block is, but that
5869                          // doesn't matter for the purposes of flushing the cache here. We'll set this
5870                          // to its correct value (`base_blockhash`) below after the coins are loaded.
5871                          coins_cache.SetBestBlock(GetRandHash());
5872  
5873                          // No need to acquire cs_main since this chainstate isn't being used yet.
5874                          FlushSnapshotToDisk(coins_cache, /*snapshot_loaded=*/false);
5875                      }
5876                  }
5877              }
5878          } catch (const std::ios_base::failure&) {
5879              return util::Error{Untranslated(strprintf("Bad snapshot format or truncated snapshot after deserializing %d coins",
5880                        coins_processed))};
5881          }
5882      }
5883  
5884      // Important that we set this. This and the coins_cache accesses above are
5885      // sort of a layer violation, but either we reach into the innards of
5886      // CCoinsViewCache here or we have to invert some of the Chainstate to
5887      // embed them in a snapshot-activation-specific CCoinsViewCache bulk load
5888      // method.
5889      coins_cache.SetBestBlock(base_blockhash);
5890  
5891      bool out_of_coins{false};
5892      try {
5893          std::byte left_over_byte;
5894          coins_file >> left_over_byte;
5895      } catch (const std::ios_base::failure&) {
5896          // We expect an exception since we should be out of coins.
5897          out_of_coins = true;
5898      }
5899      if (!out_of_coins) {
5900          return util::Error{Untranslated(strprintf("Bad snapshot - coins left over after deserializing %d coins",
5901              coins_count))};
5902      }
5903  
5904      LogInfo("[snapshot] loaded %d (%.2f MB) coins from snapshot %s",
5905          coins_count,
5906          coins_cache.DynamicMemoryUsage() / (1000 * 1000),
5907          base_blockhash.ToString());
5908  
5909      // No need to acquire cs_main since this chainstate isn't being used yet.
5910      FlushSnapshotToDisk(coins_cache, /*snapshot_loaded=*/true);
5911  
5912      assert(coins_cache.GetBestBlock() == base_blockhash);
5913  
5914      // As above, okay to immediately release cs_main here since no other context knows
5915      // about the snapshot_chainstate.
5916      CCoinsViewDB* snapshot_coinsdb = WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsDB());
5917  
5918      std::optional<CCoinsStats> maybe_stats;
5919  
5920      try {
5921          maybe_stats = ComputeUTXOStats(
5922              CoinStatsHashType::HASH_SERIALIZED, snapshot_coinsdb, m_blockman, [&interrupt = m_interrupt] { SnapshotUTXOHashBreakpoint(interrupt); });
5923      } catch (StopHashingException const&) {
5924          return util::Error{Untranslated("Aborting after an interrupt was requested")};
5925      }
5926      if (!maybe_stats.has_value()) {
5927          return util::Error{Untranslated("Failed to generate coins stats")};
5928      }
5929  
5930      // Assert that the deserialized chainstate contents match the expected assumeutxo value.
5931      if (AssumeutxoHash{maybe_stats->hashSerialized} != au_data.hash_serialized) {
5932          return util::Error{Untranslated(strprintf("Bad snapshot content hash: expected %s, got %s",
5933              au_data.hash_serialized.ToString(), maybe_stats->hashSerialized.ToString()))};
5934      }
5935  
5936      snapshot_chainstate.m_chain.SetTip(*snapshot_start_block);
5937  
5938      // The remainder of this function requires modifying data protected by cs_main.
5939      LOCK(::cs_main);
5940  
5941      // Fake various pieces of CBlockIndex state:
5942      CBlockIndex* index = nullptr;
5943  
5944      // Don't make any modifications to the genesis block since it shouldn't be
5945      // necessary, and since the genesis block doesn't have normal flags like
5946      // BLOCK_VALID_SCRIPTS set.
5947      constexpr int AFTER_GENESIS_START{1};
5948  
5949      for (int i = AFTER_GENESIS_START; i <= snapshot_chainstate.m_chain.Height(); ++i) {
5950          index = snapshot_chainstate.m_chain[i];
5951  
5952          // Fake BLOCK_OPT_WITNESS so that Chainstate::NeedsRedownload()
5953          // won't ask for -reindex on startup.
5954          if (DeploymentActiveAt(*index, *this, Consensus::DEPLOYMENT_SEGWIT)) {
5955              index->nStatus |= BLOCK_OPT_WITNESS;
5956          }
5957  
5958          m_blockman.m_dirty_blockindex.insert(index);
5959          // Changes to the block index will be flushed to disk after this call
5960          // returns in `ActivateSnapshot()`, when `MaybeRebalanceCaches()` is
5961          // called, since we've added a snapshot chainstate and therefore will
5962          // have to downsize the IBD chainstate, which will result in a call to
5963          // `FlushStateToDisk(FORCE_FLUSH)`.
5964      }
5965  
5966      assert(index);
5967      assert(index == snapshot_start_block);
5968      index->m_chain_tx_count = au_data.m_chain_tx_count;
5969  
5970      LogInfo("[snapshot] validated snapshot (%.2f MB)",
5971          coins_cache.DynamicMemoryUsage() / (1000 * 1000));
5972      return {};
5973  }
5974  
5975  // Currently, this function holds cs_main for its duration, which could be for
5976  // multiple minutes due to the ComputeUTXOStats call. Holding cs_main used to be
5977  // necessary (before d43a1f1a2fa3) to avoid advancing validated_cs farther than
5978  // its target block. Now it should be possible to avoid this, but simply
5979  // releasing cs_main here would not be possible because this function is invoked
5980  // by ConnectTip within ActivateBestChain.
5981  //
5982  // Eventually (TODO) it would be better to call this function outside of
5983  // ActivateBestChain, on a separate thread that should not require cs_main to
5984  // hash, because the UTXO set is only hashed after the historical chainstate
5985  // reaches its target block and is no longer changing.
5986  SnapshotCompletionResult ChainstateManager::MaybeValidateSnapshot(Chainstate& validated_cs, Chainstate& unvalidated_cs)
5987  {
5988      AssertLockHeld(cs_main);
5989  
5990      // If the snapshot does not need to be validated...
5991      if (unvalidated_cs.m_assumeutxo != Assumeutxo::UNVALIDATED ||
5992              // Or if either chainstate is unusable...
5993              !unvalidated_cs.m_from_snapshot_blockhash ||
5994              validated_cs.m_assumeutxo != Assumeutxo::VALIDATED ||
5995              !validated_cs.m_chain.Tip() ||
5996              // Or the validated chainstate is not targeting the snapshot block...
5997              !validated_cs.m_target_blockhash ||
5998              *validated_cs.m_target_blockhash != *unvalidated_cs.m_from_snapshot_blockhash ||
5999              // Or the validated chainstate has not reached the snapshot block yet...
6000              !validated_cs.ReachedTarget()) {
6001         // Then the snapshot cannot be validated and there is nothing to do.
6002         return SnapshotCompletionResult::SKIPPED;
6003      }
6004      assert(validated_cs.TargetBlock() == validated_cs.m_chain.Tip());
6005  
6006      auto handle_invalid_snapshot = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
6007          bilingual_str user_error = strprintf(_(
6008              "%s failed to validate the -assumeutxo snapshot state. "
6009              "This indicates a hardware problem, or a bug in the software, or a "
6010              "bad software modification that allowed an invalid snapshot to be "
6011              "loaded. As a result of this, the node will shut down and stop using any "
6012              "state that was built on the snapshot, resetting the chain height "
6013              "from %d to %d. On the next "
6014              "restart, the node will resume syncing from %d "
6015              "without using any snapshot data. "
6016              "Please report this incident to %s, including how you obtained the snapshot. "
6017              "The invalid snapshot chainstate will be left on disk in case it is "
6018              "helpful in diagnosing the issue that caused this error."),
6019              CLIENT_NAME, unvalidated_cs.m_chain.Height(),
6020              validated_cs.m_chain.Height(),
6021              validated_cs.m_chain.Height(), CLIENT_BUGREPORT);
6022  
6023          LogError("[snapshot] !!! %s\n", user_error.original);
6024          LogError("[snapshot] deleting snapshot, reverting to validated chain, and stopping node\n");
6025  
6026          // Reset chainstate target to network tip instead of snapshot block.
6027          validated_cs.SetTargetBlock(nullptr);
6028  
6029          unvalidated_cs.m_assumeutxo = Assumeutxo::INVALID;
6030  
6031          auto rename_result = unvalidated_cs.InvalidateCoinsDBOnDisk();
6032          if (!rename_result) {
6033              user_error += Untranslated("\n") + util::ErrorString(rename_result);
6034          }
6035  
6036          GetNotifications().fatalError(user_error);
6037      };
6038  
6039      CCoinsViewDB& validated_coins_db = validated_cs.CoinsDB();
6040      validated_cs.ForceFlushStateToDisk();
6041  
6042      const auto& maybe_au_data = m_options.chainparams.AssumeutxoForHeight(validated_cs.m_chain.Height());
6043      if (!maybe_au_data) {
6044          LogWarning("[snapshot] assumeutxo data not found for height "
6045              "(%d) - refusing to validate snapshot", validated_cs.m_chain.Height());
6046          handle_invalid_snapshot();
6047          return SnapshotCompletionResult::MISSING_CHAINPARAMS;
6048      }
6049  
6050      const AssumeutxoData& au_data = *maybe_au_data;
6051      std::optional<CCoinsStats> validated_cs_stats;
6052      LogInfo("[snapshot] computing UTXO stats for background chainstate to validate "
6053          "snapshot - this could take a few minutes");
6054      try {
6055          validated_cs_stats = ComputeUTXOStats(
6056              CoinStatsHashType::HASH_SERIALIZED,
6057              &validated_coins_db,
6058              m_blockman,
6059              [&interrupt = m_interrupt] { SnapshotUTXOHashBreakpoint(interrupt); });
6060      } catch (StopHashingException const&) {
6061          return SnapshotCompletionResult::STATS_FAILED;
6062      }
6063  
6064      // XXX note that this function is slow and will hold cs_main for potentially minutes.
6065      if (!validated_cs_stats) {
6066          LogWarning("[snapshot] failed to generate stats for validation coins db");
6067          // While this isn't a problem with the snapshot per se, this condition
6068          // prevents us from validating the snapshot, so we should shut down and let the
6069          // user handle the issue manually.
6070          handle_invalid_snapshot();
6071          return SnapshotCompletionResult::STATS_FAILED;
6072      }
6073  
6074      // Compare the validated chainstate's UTXO set hash against the hard-coded
6075      // assumeutxo hash we expect.
6076      //
6077      // TODO: For belt-and-suspenders, we could cache the UTXO set
6078      // hash for the snapshot when it's loaded in its chainstate's leveldb. We could then
6079      // reference that here for an additional check.
6080      if (AssumeutxoHash{validated_cs_stats->hashSerialized} != au_data.hash_serialized) {
6081          LogWarning("[snapshot] hash mismatch: actual=%s, expected=%s",
6082              validated_cs_stats->hashSerialized.ToString(),
6083              au_data.hash_serialized.ToString());
6084          handle_invalid_snapshot();
6085          return SnapshotCompletionResult::HASH_MISMATCH;
6086      }
6087  
6088      LogInfo("[snapshot] snapshot beginning at %s has been fully validated",
6089          unvalidated_cs.m_from_snapshot_blockhash->ToString());
6090  
6091      unvalidated_cs.m_assumeutxo = Assumeutxo::VALIDATED;
6092      validated_cs.m_target_utxohash = AssumeutxoHash{validated_cs_stats->hashSerialized};
6093      this->MaybeRebalanceCaches();
6094  
6095      return SnapshotCompletionResult::SUCCESS;
6096  }
6097  
6098  Chainstate& ChainstateManager::ActiveChainstate() const
6099  {
6100      LOCK(::cs_main);
6101      return CurrentChainstate();
6102  }
6103  
6104  void ChainstateManager::MaybeRebalanceCaches()
6105  {
6106      AssertLockHeld(::cs_main);
6107      Chainstate& current_cs{CurrentChainstate()};
6108      Chainstate* historical_cs{HistoricalChainstate()};
6109      if (!historical_cs && !current_cs.m_from_snapshot_blockhash) {
6110          // Allocate everything to the IBD chainstate. This will always happen
6111          // when we are not using a snapshot.
6112          current_cs.ResizeCoinsCaches(m_total_coinstip_cache, m_total_coinsdb_cache);
6113      } else if (!historical_cs) {
6114          // If background validation has completed and snapshot is our active chain...
6115          LogInfo("[snapshot] allocating all cache to the snapshot chainstate");
6116          // Allocate everything to the snapshot chainstate.
6117          current_cs.ResizeCoinsCaches(m_total_coinstip_cache, m_total_coinsdb_cache);
6118      } else {
6119          // If both chainstates exist, determine who needs more cache based on IBD status.
6120          //
6121          // Note: shrink caches first so that we don't inadvertently overwhelm available memory.
6122          if (IsInitialBlockDownload()) {
6123              historical_cs->ResizeCoinsCaches(
6124                  m_total_coinstip_cache * 0.05, m_total_coinsdb_cache * 0.05);
6125              current_cs.ResizeCoinsCaches(
6126                  m_total_coinstip_cache * 0.95, m_total_coinsdb_cache * 0.95);
6127          } else {
6128              current_cs.ResizeCoinsCaches(
6129                  m_total_coinstip_cache * 0.05, m_total_coinsdb_cache * 0.05);
6130              historical_cs->ResizeCoinsCaches(
6131                  m_total_coinstip_cache * 0.95, m_total_coinsdb_cache * 0.95);
6132          }
6133      }
6134  }
6135  
6136  void ChainstateManager::ResetChainstates()
6137  {
6138      m_chainstates.clear();
6139  }
6140  
6141  /**
6142   * Apply default chain params to nullopt members.
6143   * This helps to avoid coding errors around the accidental use of the compare
6144   * operators that accept nullopt, thus ignoring the intended default value.
6145   */
6146  static ChainstateManager::Options&& Flatten(ChainstateManager::Options&& opts)
6147  {
6148      if (!opts.check_block_index.has_value()) opts.check_block_index = opts.chainparams.DefaultConsistencyChecks();
6149      if (!opts.minimum_chain_work.has_value()) opts.minimum_chain_work = UintToArith256(opts.chainparams.GetConsensus().nMinimumChainWork);
6150      if (!opts.assumed_valid_block.has_value()) opts.assumed_valid_block = opts.chainparams.GetConsensus().defaultAssumeValid;
6151      return std::move(opts);
6152  }
6153  
6154  ChainstateManager::ChainstateManager(const util::SignalInterrupt& interrupt, Options options, node::BlockManager::Options blockman_options)
6155      : m_script_check_queue{/*batch_size=*/128, std::clamp(options.worker_threads_num, 0, MAX_SCRIPTCHECK_THREADS)},
6156        m_interrupt{interrupt},
6157        m_options{Flatten(std::move(options))},
6158        m_blockman{interrupt, std::move(blockman_options)},
6159        m_validation_cache{m_options.script_execution_cache_bytes, m_options.signature_cache_bytes}
6160  {
6161  }
6162  
6163  ChainstateManager::~ChainstateManager()
6164  {
6165      LOCK(::cs_main);
6166  
6167      m_versionbitscache.Clear();
6168  }
6169  
6170  Chainstate* ChainstateManager::LoadAssumeutxoChainstate()
6171  {
6172      assert(!CurrentChainstate().m_from_snapshot_blockhash);
6173      std::optional<fs::path> path = node::FindAssumeutxoChainstateDir(m_options.datadir);
6174      if (!path) {
6175          return nullptr;
6176      }
6177      std::optional<uint256> base_blockhash = node::ReadSnapshotBaseBlockhash(*path);
6178      if (!base_blockhash) {
6179          return nullptr;
6180      }
6181      LogInfo("[snapshot] detected active snapshot chainstate (%s) - loading",
6182          fs::PathToString(*path));
6183  
6184      auto snapshot_chainstate{std::make_unique<Chainstate>(nullptr, m_blockman, *this, base_blockhash)};
6185      LogInfo("[snapshot] switching active chainstate to %s", snapshot_chainstate->ToString());
6186      return &this->AddChainstate(std::move(snapshot_chainstate));
6187  }
6188  
6189  Chainstate& ChainstateManager::AddChainstate(std::unique_ptr<Chainstate> chainstate)
6190  {
6191      Chainstate& prev_chainstate{CurrentChainstate()};
6192      assert(prev_chainstate.m_assumeutxo == Assumeutxo::VALIDATED);
6193      // Set target block for historical chainstate to snapshot block.
6194      assert(!prev_chainstate.m_target_blockhash);
6195      prev_chainstate.m_target_blockhash = chainstate->m_from_snapshot_blockhash;
6196      m_chainstates.push_back(std::move(chainstate));
6197      Chainstate& curr_chainstate{CurrentChainstate()};
6198      assert(&curr_chainstate == m_chainstates.back().get());
6199  
6200      // Transfer possession of the mempool to the chainstate.
6201      // Mempool is empty at this point because we're still in IBD.
6202      assert(!prev_chainstate.m_mempool || prev_chainstate.m_mempool->size() == 0);
6203      assert(!curr_chainstate.m_mempool);
6204      std::swap(curr_chainstate.m_mempool, prev_chainstate.m_mempool);
6205      return curr_chainstate;
6206  }
6207  
6208  bool IsBIP30Repeat(const CBlockIndex& block_index)
6209  {
6210      return (block_index.nHeight==91842 && block_index.GetBlockHash() == uint256{"00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec"}) ||
6211             (block_index.nHeight==91880 && block_index.GetBlockHash() == uint256{"00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"});
6212  }
6213  
6214  bool IsBIP30Unspendable(const uint256& block_hash, int block_height)
6215  {
6216      return (block_height==91722 && block_hash == uint256{"00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"}) ||
6217             (block_height==91812 && block_hash == uint256{"00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"});
6218  }
6219  
6220  util::Result<void> Chainstate::InvalidateCoinsDBOnDisk()
6221  {
6222      // Should never be called on a non-snapshot chainstate.
6223      assert(m_from_snapshot_blockhash);
6224  
6225      // Coins views no longer usable.
6226      m_coins_views.reset();
6227  
6228      const fs::path db_path{StoragePath()};
6229      const fs::path invalid_path{db_path + "_INVALID"};
6230      const std::string db_path_str{fs::PathToString(db_path)};
6231      const std::string invalid_path_str{fs::PathToString(invalid_path)};
6232      LogInfo("[snapshot] renaming snapshot datadir %s to %s", db_path_str, invalid_path_str);
6233  
6234      // The invalid storage directory is simply moved and not deleted because we may
6235      // want to do forensics later during issue investigation. The user is instructed
6236      // accordingly in MaybeValidateSnapshot().
6237      try {
6238          fs::rename(db_path, invalid_path);
6239      } catch (const fs::filesystem_error& e) {
6240          LogError("While invalidating the coins db: Error renaming file '%s' -> '%s': %s",
6241                   db_path_str, invalid_path_str, e.what());
6242          return util::Error{strprintf(_(
6243              "Rename of '%s' -> '%s' failed. "
6244              "You should resolve this by manually moving or deleting the invalid "
6245              "snapshot directory %s, otherwise you will encounter the same error again "
6246              "on the next startup."),
6247              db_path_str, invalid_path_str, db_path_str)};
6248      }
6249      return {};
6250  }
6251  
6252  bool ChainstateManager::DeleteChainstate(Chainstate& chainstate)
6253  {
6254      AssertLockHeld(::cs_main);
6255      assert(!chainstate.m_coins_views);
6256      const fs::path db_path{chainstate.StoragePath()};
6257      if (!DeleteCoinsDBFromDisk(db_path, /*is_snapshot=*/bool{chainstate.m_from_snapshot_blockhash})) {
6258          LogError("Deletion of %s failed. Please remove it manually to continue reindexing.",
6259                    fs::PathToString(db_path));
6260          return false;
6261      }
6262      std::unique_ptr<Chainstate> prev_chainstate{Assert(RemoveChainstate(chainstate))};
6263      Chainstate& curr_chainstate{CurrentChainstate()};
6264      assert(prev_chainstate->m_mempool->size() == 0);
6265      assert(!curr_chainstate.m_mempool);
6266      std::swap(curr_chainstate.m_mempool, prev_chainstate->m_mempool);
6267      return true;
6268  }
6269  
6270  ChainstateRole Chainstate::GetRole() const
6271  {
6272      return ChainstateRole{.validated = m_assumeutxo == Assumeutxo::VALIDATED, .historical = bool{m_target_blockhash}};
6273  }
6274  
6275  void ChainstateManager::RecalculateBestHeader()
6276  {
6277      AssertLockHeld(cs_main);
6278      m_best_header = ActiveChain().Tip();
6279      for (auto& entry : m_blockman.m_block_index) {
6280          if (!(entry.second.nStatus & BLOCK_FAILED_VALID) && m_best_header->nChainWork < entry.second.nChainWork) {
6281              m_best_header = &entry.second;
6282          }
6283      }
6284  }
6285  
6286  std::optional<int> ChainstateManager::BlocksAheadOfTip() const
6287  {
6288      LOCK(::cs_main);
6289      const CBlockIndex* best_header{m_best_header};
6290      const CBlockIndex* tip{ActiveChain().Tip()};
6291      // Only consider headers that extend the active tip; ignore competing branches.
6292      if (best_header && tip && best_header->nChainWork > tip->nChainWork &&
6293          best_header->GetAncestor(tip->nHeight) == tip) {
6294          return best_header->nHeight - tip->nHeight;
6295      }
6296      return std::nullopt;
6297  }
6298  
6299  bool ChainstateManager::ValidatedSnapshotCleanup(Chainstate& validated_cs, Chainstate& unvalidated_cs)
6300  {
6301      AssertLockHeld(::cs_main);
6302      if (unvalidated_cs.m_assumeutxo != Assumeutxo::VALIDATED) {
6303          // No need to clean up.
6304          return false;
6305      }
6306  
6307      const fs::path validated_path{validated_cs.StoragePath()};
6308      const fs::path assumed_valid_path{unvalidated_cs.StoragePath()};
6309      const fs::path delete_path{validated_path + "_todelete"};
6310  
6311      // Since we're going to be moving around the underlying leveldb filesystem content
6312      // for each chainstate, make sure that the chainstates (and their constituent
6313      // CoinsViews members) have been destructed first.
6314      //
6315      // The caller of this method will be responsible for reinitializing chainstates
6316      // if they want to continue operation.
6317      this->ResetChainstates();
6318      assert(this->m_chainstates.size() == 0);
6319  
6320      LogInfo("[snapshot] deleting background chainstate directory (now unnecessary) (%s)",
6321                fs::PathToString(validated_path));
6322  
6323      auto rename_failed_abort = [this](
6324                                     fs::path p_old,
6325                                     fs::path p_new,
6326                                     const fs::filesystem_error& err) {
6327          LogError("[snapshot] Error renaming path (%s) -> (%s): %s\n",
6328                    fs::PathToString(p_old), fs::PathToString(p_new), err.what());
6329          GetNotifications().fatalError(strprintf(_(
6330              "Rename of '%s' -> '%s' failed. "
6331              "Cannot clean up the background chainstate leveldb directory."),
6332              fs::PathToString(p_old), fs::PathToString(p_new)));
6333      };
6334  
6335      try {
6336          fs::rename(validated_path, delete_path);
6337      } catch (const fs::filesystem_error& e) {
6338          rename_failed_abort(validated_path, delete_path, e);
6339          throw;
6340      }
6341  
6342      LogInfo("[snapshot] moving snapshot chainstate (%s) to "
6343                "default chainstate directory (%s)",
6344                fs::PathToString(assumed_valid_path), fs::PathToString(validated_path));
6345  
6346      try {
6347          fs::rename(assumed_valid_path, validated_path);
6348      } catch (const fs::filesystem_error& e) {
6349          rename_failed_abort(assumed_valid_path, validated_path, e);
6350          throw;
6351      }
6352  
6353      if (!DeleteCoinsDBFromDisk(delete_path, /*is_snapshot=*/false)) {
6354          // No need to FatalError because once the unneeded bg chainstate data is
6355          // moved, it will not interfere with subsequent initialization.
6356          LogWarning("Deletion of %s failed. Please remove it manually, as the "
6357                     "directory is now unnecessary.",
6358                     fs::PathToString(delete_path));
6359      } else {
6360          LogInfo("[snapshot] deleted background chainstate directory (%s)",
6361                  fs::PathToString(validated_path));
6362      }
6363      return true;
6364  }
6365  
6366  std::pair<int, int> Chainstate::GetPruneRange(int last_height_can_prune) const
6367  {
6368      if (m_chain.Height() <= 0) {
6369          return {0, 0};
6370      }
6371      int prune_start{0};
6372  
6373      if (m_from_snapshot_blockhash && m_assumeutxo != Assumeutxo::VALIDATED) {
6374          // Only prune blocks _after_ the snapshot if this is a snapshot chain
6375          // that has not been fully validated yet. The earlier blocks need to be
6376          // kept to validate the snapshot
6377          prune_start = Assert(SnapshotBase())->nHeight + 1;
6378      }
6379  
6380      int max_prune = std::max<int>(
6381          0, m_chain.Height() - static_cast<int>(MIN_BLOCKS_TO_KEEP));
6382  
6383      // last block to prune is the lesser of (caller-specified height, MIN_BLOCKS_TO_KEEP from the tip)
6384      //
6385      // While you might be tempted to prune the background chainstate more
6386      // aggressively (i.e. fewer MIN_BLOCKS_TO_KEEP), this won't work with index
6387      // building - specifically blockfilterindex requires undo data, and if
6388      // we don't maintain this trailing window, we hit indexing failures.
6389      int prune_end = std::min(last_height_can_prune, max_prune);
6390  
6391      return {prune_start, prune_end};
6392  }
6393  
6394  std::optional<std::pair<const CBlockIndex*, const CBlockIndex*>> ChainstateManager::GetHistoricalBlockRange() const
6395  {
6396      const Chainstate* chainstate{HistoricalChainstate()};
6397      if (!chainstate) return {};
6398      return std::make_pair(chainstate->m_chain.Tip(), chainstate->TargetBlock());
6399  }
6400  
6401  util::Result<void> ChainstateManager::ActivateBestChains()
6402  {
6403      // We can't hold cs_main during ActivateBestChain even though we're accessing
6404      // the chainman unique_ptrs since ABC requires us not to be holding cs_main, so retrieve
6405      // the relevant pointers before the ABC call.
6406      AssertLockNotHeld(cs_main);
6407      std::vector<Chainstate*> chainstates;
6408      {
6409          LOCK(GetMutex());
6410          chainstates.reserve(m_chainstates.size());
6411          for (const auto& chainstate : m_chainstates) {
6412              if (chainstate && chainstate->m_assumeutxo != Assumeutxo::INVALID && !chainstate->m_target_utxohash) {
6413                  chainstates.push_back(chainstate.get());
6414              }
6415          }
6416      }
6417      for (Chainstate* chainstate : chainstates) {
6418          BlockValidationState state;
6419          if (!chainstate->ActivateBestChain(state, nullptr)) {
6420              LOCK(GetMutex());
6421              return util::Error{Untranslated(strprintf("%s Failed to connect best block (%s)", chainstate->ToString(), state.ToString()))};
6422          }
6423      }
6424      return {};
6425  }