Bitcoin ABC  0.26.3
P2P Digital Currency
validation.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 The Bitcoin Core developers
3 // Copyright (c) 2017-2020 The Bitcoin developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include <validation.h>
8 
9 #include <kernel/chainparams.h>
10 #include <kernel/coinstats.h>
12 #include <kernel/mempool_entry.h>
13 #include <kernel/mempool_persist.h>
14 
15 #include <arith_uint256.h>
16 #include <avalanche/avalanche.h>
17 #include <avalanche/processor.h>
18 #include <blockvalidity.h>
19 #include <chainparams.h>
20 #include <checkpoints.h>
21 #include <checkqueue.h>
22 #include <common/args.h>
23 #include <config.h>
24 #include <consensus/activation.h>
25 #include <consensus/amount.h>
26 #include <consensus/merkle.h>
27 #include <consensus/tx_check.h>
28 #include <consensus/tx_verify.h>
29 #include <consensus/validation.h>
30 #include <hash.h>
32 #include <logging.h>
33 #include <logging/timer.h>
34 #include <minerfund.h>
35 #include <node/blockstorage.h>
36 #include <node/utxo_snapshot.h>
37 #include <policy/block/minerfund.h>
40 #include <policy/policy.h>
41 #include <policy/settings.h>
42 #include <pow/pow.h>
43 #include <primitives/block.h>
44 #include <primitives/transaction.h>
45 #include <random.h>
46 #include <reverse_iterator.h>
47 #include <script/script.h>
48 #include <script/scriptcache.h>
49 #include <script/sigcache.h>
50 #include <shutdown.h>
51 #include <tinyformat.h>
52 #include <txdb.h>
53 #include <txmempool.h>
54 #include <undo.h>
55 #include <util/check.h> // For NDEBUG compile time check
56 #include <util/fs.h>
57 #include <util/fs_helpers.h>
58 #include <util/strencodings.h>
59 #include <util/string.h>
60 #include <util/time.h>
61 #include <util/trace.h>
62 #include <util/translation.h>
63 #include <validationinterface.h>
64 #include <warnings.h>
65 
66 #include <algorithm>
67 #include <atomic>
68 #include <cassert>
69 #include <chrono>
70 #include <deque>
71 #include <numeric>
72 #include <optional>
73 #include <string>
74 #include <thread>
75 
81 
82 using fsbridge::FopenFn;
84 using node::BlockManager;
85 using node::BlockMap;
86 using node::fReindex;
89 
90 #define MICRO 0.000001
91 #define MILLI 0.001
92 
94 static constexpr std::chrono::hours DATABASE_WRITE_INTERVAL{1};
96 static constexpr std::chrono::hours DATABASE_FLUSH_INTERVAL{24};
97 const std::vector<std::string> CHECKLEVEL_DOC{
98  "level 0 reads the blocks from disk",
99  "level 1 verifies block validity",
100  "level 2 verifies undo data",
101  "level 3 checks disconnection of tip blocks",
102  "level 4 tries to reconnect the blocks",
103  "each level includes the checks of the previous levels",
104 };
111 static constexpr int PRUNE_LOCK_BUFFER{10};
112 
114 std::condition_variable g_best_block_cv;
116 
118  : excessiveBlockSize(config.GetMaxBlockSize()), checkPoW(true),
119  checkMerkleRoot(true) {}
120 
121 const CBlockIndex *
124 
125  // Find the latest block common to locator and chain - we expect that
126  // locator.vHave is sorted descending by height.
127  for (const BlockHash &hash : locator.vHave) {
128  const CBlockIndex *pindex{m_blockman.LookupBlockIndex(hash)};
129  if (pindex) {
130  if (m_chain.Contains(pindex)) {
131  return pindex;
132  }
133  if (pindex->GetAncestor(m_chain.Height()) == m_chain.Tip()) {
134  return m_chain.Tip();
135  }
136  }
137  }
138  return m_chain.Genesis();
139 }
140 
141 static uint32_t GetNextBlockScriptFlags(const CBlockIndex *pindex,
142  const ChainstateManager &chainman);
143 
144 namespace {
156 std::optional<std::vector<int>> CalculatePrevHeights(const CBlockIndex &tip,
157  const CCoinsView &coins,
158  const CTransaction &tx) {
159  std::vector<int> prev_heights;
160  prev_heights.resize(tx.vin.size());
161  for (size_t i = 0; i < tx.vin.size(); ++i) {
162  const CTxIn &txin = tx.vin[i];
163  Coin coin;
164  if (!coins.GetCoin(txin.prevout, coin)) {
165  LogPrintf("ERROR: %s: Missing input %d in transaction \'%s\'\n",
166  __func__, i, tx.GetId().GetHex());
167  return std::nullopt;
168  }
169  if (coin.GetHeight() == MEMPOOL_HEIGHT) {
170  // Assume all mempool transaction confirm in the next block.
171  prev_heights[i] = tip.nHeight + 1;
172  } else {
173  prev_heights[i] = coin.GetHeight();
174  }
175  }
176  return prev_heights;
177 }
178 } // namespace
179 
180 std::optional<LockPoints> CalculateLockPointsAtTip(CBlockIndex *tip,
181  const CCoinsView &coins_view,
182  const CTransaction &tx) {
183  assert(tip);
184 
185  auto prev_heights{CalculatePrevHeights(*tip, coins_view, tx)};
186  if (!prev_heights.has_value()) {
187  return std::nullopt;
188  }
189 
190  CBlockIndex next_tip;
191  next_tip.pprev = tip;
192  // When SequenceLocks() is called within ConnectBlock(), the height
193  // of the block *being* evaluated is what is used.
194  // Thus if we want to know if a transaction can be part of the
195  // *next* block, we need to use one more than
196  // active_chainstate.m_chain.Height()
197  next_tip.nHeight = tip->nHeight + 1;
198  const auto [min_height, min_time] = CalculateSequenceLocks(
199  tx, STANDARD_LOCKTIME_VERIFY_FLAGS, prev_heights.value(), next_tip);
200 
201  return LockPoints{min_height, min_time};
202 }
203 
204 bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points) {
205  assert(tip != nullptr);
206 
207  CBlockIndex index;
208  index.pprev = tip;
209  // CheckSequenceLocksAtTip() uses active_chainstate.m_chain.Height()+1 to
210  // evaluate height based locks because when SequenceLocks() is called within
211  // ConnectBlock(), the height of the block *being* evaluated is what is
212  // used. Thus if we want to know if a transaction can be part of the *next*
213  // block, we need to use one more than active_chainstate.m_chain.Height()
214  index.nHeight = tip->nHeight + 1;
215 
216  return EvaluateSequenceLocks(index, {lock_points.height, lock_points.time});
217 }
218 
219 // Command-line argument "-replayprotectionactivationtime=<timestamp>" will
220 // cause the node to switch to replay protected SigHash ForkID value when the
221 // median timestamp of the previous 11 blocks is greater than or equal to
222 // <timestamp>. Defaults to the pre-defined timestamp when not set.
224  int64_t nMedianTimePast) {
225  return nMedianTimePast >= gArgs.GetIntArg("-replayprotectionactivationtime",
226  params.augustoActivationTime);
227 }
228 
230  const CBlockIndex *pindexPrev) {
231  if (pindexPrev == nullptr) {
232  return false;
233  }
234 
235  return IsReplayProtectionEnabled(params, pindexPrev->GetMedianTimePast());
236 }
237 
244  const CTransaction &tx, TxValidationState &state,
245  const CCoinsViewCache &view, const CTxMemPool &pool, const uint32_t flags,
246  PrecomputedTransactionData &txdata, int &nSigChecksOut,
249  AssertLockHeld(pool.cs);
250 
252  for (const CTxIn &txin : tx.vin) {
253  const Coin &coin = view.AccessCoin(txin.prevout);
254 
255  // This coin was checked in PreChecks and MemPoolAccept
256  // has been holding cs_main since then.
257  Assume(!coin.IsSpent());
258  if (coin.IsSpent()) {
259  return false;
260  }
261 
262  // If the Coin is available, there are 2 possibilities:
263  // it is available in our current ChainstateActive UTXO set,
264  // or it's a UTXO provided by a transaction in our mempool.
265  // Ensure the scriptPubKeys in Coins from CoinsView are correct.
266  const CTransactionRef &txFrom = pool.get(txin.prevout.GetTxId());
267  if (txFrom) {
268  assert(txFrom->GetId() == txin.prevout.GetTxId());
269  assert(txFrom->vout.size() > txin.prevout.GetN());
270  assert(txFrom->vout[txin.prevout.GetN()] == coin.GetTxOut());
271  } else {
272  const Coin &coinFromUTXOSet = coins_tip.AccessCoin(txin.prevout);
273  assert(!coinFromUTXOSet.IsSpent());
274  assert(coinFromUTXOSet.GetTxOut() == coin.GetTxOut());
275  }
276  }
277 
278  // Call CheckInputScripts() to cache signature and script validity against
279  // current tip consensus rules.
280  return CheckInputScripts(tx, state, view, flags, /*sigCacheStore=*/true,
281  /*scriptCacheStore=*/true, txdata, nSigChecksOut);
282 }
283 
284 namespace {
285 
286 class MemPoolAccept {
287 public:
288  MemPoolAccept(CTxMemPool &mempool, Chainstate &active_chainstate)
289  : m_pool(mempool), m_view(&m_dummy),
290  m_viewmempool(&active_chainstate.CoinsTip(), m_pool),
291  m_active_chainstate(active_chainstate) {}
292 
293  // We put the arguments we're handed into a struct, so we can pass them
294  // around easier.
295  struct ATMPArgs {
296  const Config &m_config;
297  const int64_t m_accept_time;
298  const bool m_bypass_limits;
299  /*
300  * Return any outpoints which were not previously present in the coins
301  * cache, but were added as a result of validating the tx for mempool
302  * acceptance. This allows the caller to optionally remove the cache
303  * additions if the associated transaction ends up being rejected by
304  * the mempool.
305  */
306  std::vector<COutPoint> &m_coins_to_uncache;
307  const bool m_test_accept;
308  const unsigned int m_heightOverride;
314  const bool m_package_submission;
320  const bool m_package_feerates;
321 
323  static ATMPArgs SingleAccept(const Config &config, int64_t accept_time,
324  bool bypass_limits,
325  std::vector<COutPoint> &coins_to_uncache,
326  bool test_accept,
327  unsigned int heightOverride) {
328  return ATMPArgs{
329  config,
330  accept_time,
331  bypass_limits,
332  coins_to_uncache,
333  test_accept,
334  heightOverride,
335  /*package_submission=*/false,
336  /*package_feerates=*/false,
337  };
338  }
339 
344  static ATMPArgs
345  PackageTestAccept(const Config &config, int64_t accept_time,
346  std::vector<COutPoint> &coins_to_uncache) {
347  return ATMPArgs{
348  config,
349  accept_time,
350  /*bypass_limits=*/false,
351  coins_to_uncache,
352  /*test_accept=*/true,
353  /*height_override=*/0,
354  // not submitting to mempool
355  /*package_submission=*/false,
356  /*package_feerates=*/false,
357  };
358  }
359 
361  static ATMPArgs
362  PackageChildWithParents(const Config &config, int64_t accept_time,
363  std::vector<COutPoint> &coins_to_uncache) {
364  return ATMPArgs{
365  config,
366  accept_time,
367  /*bypass_limits=*/false,
368  coins_to_uncache,
369  /*test_accept=*/false,
370  /*height_override=*/0,
371  /*package_submission=*/true,
372  /*package_feerates=*/true,
373  };
374  }
375 
377  static ATMPArgs SingleInPackageAccept(const ATMPArgs &package_args) {
378  return ATMPArgs{
379  /*config=*/package_args.m_config,
380  /*accept_time=*/package_args.m_accept_time,
381  /*bypass_limits=*/false,
382  /*coins_to_uncache=*/package_args.m_coins_to_uncache,
383  /*test_accept=*/package_args.m_test_accept,
384  /*height_override=*/package_args.m_heightOverride,
385  // do not LimitMempoolSize in Finalize()
386  /*package_submission=*/true,
387  // only 1 transaction
388  /*package_feerates=*/false,
389  };
390  }
391 
392  private:
393  // Private ctor to avoid exposing details to clients and allowing the
394  // possibility of mixing up the order of the arguments. Use static
395  // functions above instead.
396  ATMPArgs(const Config &config, int64_t accept_time, bool bypass_limits,
397  std::vector<COutPoint> &coins_to_uncache, bool test_accept,
398  unsigned int height_override, bool package_submission,
399  bool package_feerates)
400  : m_config{config}, m_accept_time{accept_time},
401  m_bypass_limits{bypass_limits},
402  m_coins_to_uncache{coins_to_uncache}, m_test_accept{test_accept},
403  m_heightOverride{height_override},
404  m_package_submission{package_submission},
405  m_package_feerates(package_feerates) {}
406  };
407 
408  // Single transaction acceptance
409  MempoolAcceptResult AcceptSingleTransaction(const CTransactionRef &ptx,
410  ATMPArgs &args)
412 
420  AcceptMultipleTransactions(const std::vector<CTransactionRef> &txns,
421  ATMPArgs &args)
423 
437  AcceptSubPackage(const std::vector<CTransactionRef> &subpackage,
438  ATMPArgs &args)
439  EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
440 
446  PackageMempoolAcceptResult AcceptPackage(const Package &package,
447  ATMPArgs &args)
449 
450 private:
451  // All the intermediate state that gets passed between the various levels
452  // of checking a given transaction.
453  struct Workspace {
454  Workspace(const CTransactionRef &ptx,
455  const uint32_t next_block_script_verify_flags)
456  : m_ptx(ptx),
457  m_next_block_script_verify_flags(next_block_script_verify_flags) {
458  }
464  std::unique_ptr<CTxMemPoolEntry> m_entry;
465 
470  int64_t m_vsize;
475  Amount m_base_fees;
476 
481  Amount m_modified_fees;
482 
489  CFeeRate m_package_feerate{Amount::zero()};
490 
491  const CTransactionRef &m_ptx;
492  TxValidationState m_state;
498  PrecomputedTransactionData m_precomputed_txdata;
499 
500  // ABC specific flags that are used in both PreChecks and
501  // ConsensusScriptChecks
502  const uint32_t m_next_block_script_verify_flags;
503  int m_sig_checks_standard;
504  };
505 
506  // Run the policy checks on a given transaction, excluding any script
507  // checks. Looks up inputs, calculates feerate, considers replacement,
508  // evaluates package limits, etc. As this function can be invoked for "free"
509  // by a peer, only tests that are fast should be done here (to avoid CPU
510  // DoS).
511  bool PreChecks(ATMPArgs &args, Workspace &ws)
512  EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
513 
514  // Re-run the script checks, using consensus flags, and try to cache the
515  // result in the scriptcache. This should be done after
516  // PolicyScriptChecks(). This requires that all inputs either be in our
517  // utxo set or in the mempool.
518  bool ConsensusScriptChecks(const ATMPArgs &args, Workspace &ws)
519  EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
520 
521  // Try to add the transaction to the mempool, removing any conflicts first.
522  // Returns true if the transaction is in the mempool after any size
523  // limiting is performed, false otherwise.
524  bool Finalize(const ATMPArgs &args, Workspace &ws)
525  EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
526 
527  // Submit all transactions to the mempool and call ConsensusScriptChecks to
528  // add to the script cache - should only be called after successful
529  // validation of all transactions in the package.
530  // Does not call LimitMempoolSize(), so mempool max_size_bytes may be
531  // temporarily exceeded.
532  bool SubmitPackage(const ATMPArgs &args, std::vector<Workspace> &workspaces,
533  PackageValidationState &package_state,
534  std::map<TxId, MempoolAcceptResult> &results)
535  EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
536 
537  // Compare a package's feerate against minimum allowed.
538  bool CheckFeeRate(size_t package_size, size_t package_vsize,
539  Amount package_fee, TxValidationState &state)
540  EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_pool.cs) {
542  AssertLockHeld(m_pool.cs);
543 
544  const Amount mempoolRejectFee =
545  m_pool.GetMinFee().GetFee(package_vsize);
546 
547  if (mempoolRejectFee > Amount::zero() &&
548  package_fee < mempoolRejectFee) {
549  return state.Invalid(
551  "mempool min fee not met",
552  strprintf("%d < %d", package_fee, mempoolRejectFee));
553  }
554 
555  // Do not change this to use virtualsize without coordinating a network
556  // policy upgrade.
557  if (package_fee < m_pool.m_min_relay_feerate.GetFee(package_size)) {
558  return state.Invalid(
559  TxValidationResult::TX_RECONSIDERABLE, "min relay fee not met",
560  strprintf("%d < %d", package_fee,
561  m_pool.m_min_relay_feerate.GetFee(package_size)));
562  }
563 
564  return true;
565  }
566 
567 private:
568  CTxMemPool &m_pool;
569  CCoinsViewCache m_view;
570  CCoinsViewMemPool m_viewmempool;
571  CCoinsView m_dummy;
572 
573  Chainstate &m_active_chainstate;
574 };
575 
576 bool MemPoolAccept::PreChecks(ATMPArgs &args, Workspace &ws) {
578  AssertLockHeld(m_pool.cs);
579  const CTransactionRef &ptx = ws.m_ptx;
580  const CTransaction &tx = *ws.m_ptx;
581  const TxId &txid = ws.m_ptx->GetId();
582 
583  // Copy/alias what we need out of args
584  const int64_t nAcceptTime = args.m_accept_time;
585  const bool bypass_limits = args.m_bypass_limits;
586  std::vector<COutPoint> &coins_to_uncache = args.m_coins_to_uncache;
587  const unsigned int heightOverride = args.m_heightOverride;
588 
589  // Alias what we need out of ws
590  TxValidationState &state = ws.m_state;
591  // Coinbase is only valid in a block, not as a loose transaction.
592  if (!CheckRegularTransaction(tx, state)) {
593  // state filled in by CheckRegularTransaction.
594  return false;
595  }
596 
597  // Rather not work on nonstandard transactions (unless -testnet)
598  std::string reason;
599  if (m_pool.m_require_standard &&
600  !IsStandardTx(tx, m_pool.m_max_datacarrier_bytes,
601  m_pool.m_permit_bare_multisig,
602  m_pool.m_dust_relay_feerate, reason)) {
603  return state.Invalid(TxValidationResult::TX_NOT_STANDARD, reason);
604  }
605 
606  // Only accept nLockTime-using transactions that can be mined in the next
607  // block; we don't want our mempool filled up with transactions that can't
608  // be mined yet.
609  TxValidationState ctxState;
611  *Assert(m_active_chainstate.m_chain.Tip()),
612  args.m_config.GetChainParams().GetConsensus(), tx, ctxState)) {
613  // We copy the state from a dummy to ensure we don't increase the
614  // ban score of peer for transaction that could be valid in the future.
616  ctxState.GetRejectReason(),
617  ctxState.GetDebugMessage());
618  }
619 
620  // Is it already in the memory pool?
621  if (m_pool.exists(txid)) {
623  "txn-already-in-mempool");
624  }
625 
626  // Check for conflicts with in-memory transactions
627  for (const CTxIn &txin : tx.vin) {
628  const CTransaction *ptxConflicting = m_pool.GetConflictTx(txin.prevout);
629  if (ptxConflicting) {
630  // Disable replacement feature for good
632  "txn-mempool-conflict");
633  }
634  }
635 
636  m_view.SetBackend(m_viewmempool);
637 
638  const CCoinsViewCache &coins_cache = m_active_chainstate.CoinsTip();
639  // Do all inputs exist?
640  for (const CTxIn &txin : tx.vin) {
641  if (!coins_cache.HaveCoinInCache(txin.prevout)) {
642  coins_to_uncache.push_back(txin.prevout);
643  }
644 
645  // Note: this call may add txin.prevout to the coins cache
646  // (coins_cache.cacheCoins) by way of FetchCoin(). It should be
647  // removed later (via coins_to_uncache) if this tx turns out to be
648  // invalid.
649  if (!m_view.HaveCoin(txin.prevout)) {
650  // Are inputs missing because we already have the tx?
651  for (size_t out = 0; out < tx.vout.size(); out++) {
652  // Optimistically just do efficient check of cache for
653  // outputs.
654  if (coins_cache.HaveCoinInCache(COutPoint(txid, out))) {
656  "txn-already-known");
657  }
658  }
659 
660  // Otherwise assume this might be an orphan tx for which we just
661  // haven't seen parents yet.
663  "bad-txns-inputs-missingorspent");
664  }
665  }
666 
667  // Are the actual inputs available?
668  if (!m_view.HaveInputs(tx)) {
670  "bad-txns-inputs-spent");
671  }
672 
673  // Bring the best block into scope.
674  m_view.GetBestBlock();
675 
676  // we have all inputs cached now, so switch back to dummy (to protect
677  // against bugs where we pull more inputs from disk that miss being
678  // added to coins_to_uncache)
679  m_view.SetBackend(m_dummy);
680 
681  assert(m_active_chainstate.m_blockman.LookupBlockIndex(
682  m_view.GetBestBlock()) == m_active_chainstate.m_chain.Tip());
683 
684  // Only accept BIP68 sequence locked transactions that can be mined in
685  // the next block; we don't want our mempool filled up with transactions
686  // that can't be mined yet.
687  // Pass in m_view which has all of the relevant inputs cached. Note that,
688  // since m_view's backend was removed, it no longer pulls coins from the
689  // mempool.
690  const std::optional<LockPoints> lock_points{CalculateLockPointsAtTip(
691  m_active_chainstate.m_chain.Tip(), m_view, tx)};
692  if (!lock_points.has_value() ||
693  !CheckSequenceLocksAtTip(m_active_chainstate.m_chain.Tip(),
694  *lock_points)) {
696  "non-BIP68-final");
697  }
698 
699  // The mempool holds txs for the next block, so pass height+1 to
700  // CheckTxInputs
701  if (!Consensus::CheckTxInputs(tx, state, m_view,
702  m_active_chainstate.m_chain.Height() + 1,
703  ws.m_base_fees)) {
704  // state filled in by CheckTxInputs
705  return false;
706  }
707 
708  // Check for non-standard pay-to-script-hash in inputs
709  if (m_pool.m_require_standard &&
710  !AreInputsStandard(tx, m_view, ws.m_next_block_script_verify_flags)) {
712  "bad-txns-nonstandard-inputs");
713  }
714 
715  // ws.m_modified_fess includes any fee deltas from PrioritiseTransaction
716  ws.m_modified_fees = ws.m_base_fees;
717  m_pool.ApplyDelta(txid, ws.m_modified_fees);
718 
719  unsigned int nSize = tx.GetTotalSize();
720 
721  // Validate input scripts against standard script flags.
722  const uint32_t scriptVerifyFlags =
723  ws.m_next_block_script_verify_flags | STANDARD_SCRIPT_VERIFY_FLAGS;
724  ws.m_precomputed_txdata = PrecomputedTransactionData{tx};
725  if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, false,
726  ws.m_precomputed_txdata, ws.m_sig_checks_standard)) {
727  // State filled in by CheckInputScripts
728  return false;
729  }
730 
731  ws.m_entry = std::make_unique<CTxMemPoolEntry>(
732  ptx, ws.m_base_fees, nAcceptTime,
733  heightOverride ? heightOverride : m_active_chainstate.m_chain.Height(),
734  ws.m_sig_checks_standard, lock_points.value());
735 
736  ws.m_vsize = ws.m_entry->GetTxVirtualSize();
737 
738  // No individual transactions are allowed below the min relay feerate except
739  // from disconnected blocks. This requirement, unlike CheckFeeRate, cannot
740  // be bypassed using m_package_feerates because, while a tx could be package
741  // CPFP'd when entering the mempool, we do not have a DoS-resistant method
742  // of ensuring the tx remains bumped. For example, the fee-bumping child
743  // could disappear due to a replacement.
744  if (!bypass_limits &&
745  ws.m_modified_fees <
746  m_pool.m_min_relay_feerate.GetFee(ws.m_ptx->GetTotalSize())) {
747  // Even though this is a fee-related failure, this result is
748  // TX_MEMPOOL_POLICY, not TX_RECONSIDERABLE, because it cannot be
749  // bypassed using package validation.
750  return state.Invalid(
751  TxValidationResult::TX_MEMPOOL_POLICY, "min relay fee not met",
752  strprintf("%d < %d", ws.m_modified_fees,
753  m_pool.m_min_relay_feerate.GetFee(nSize)));
754  }
755  // No individual transactions are allowed below the mempool min feerate
756  // except from disconnected blocks and transactions in a package. Package
757  // transactions will be checked using package feerate later.
758  if (!bypass_limits && !args.m_package_feerates &&
759  !CheckFeeRate(nSize, ws.m_vsize, ws.m_modified_fees, state)) {
760  return false;
761  }
762 
763  return true;
764 }
765 
766 bool MemPoolAccept::ConsensusScriptChecks(const ATMPArgs &args, Workspace &ws) {
768  AssertLockHeld(m_pool.cs);
769  const CTransaction &tx = *ws.m_ptx;
770  const TxId &txid = tx.GetId();
771  TxValidationState &state = ws.m_state;
772 
773  // Check again against the next block's script verification flags
774  // to cache our script execution flags.
775  //
776  // This is also useful in case of bugs in the standard flags that cause
777  // transactions to pass as valid when they're actually invalid. For
778  // instance the STRICTENC flag was incorrectly allowing certain CHECKSIG
779  // NOT scripts to pass, even though they were invalid.
780  //
781  // There is a similar check in CreateNewBlock() to prevent creating
782  // invalid blocks (using TestBlockValidity), however allowing such
783  // transactions into the mempool can be exploited as a DoS attack.
784  int nSigChecksConsensus;
786  tx, state, m_view, m_pool, ws.m_next_block_script_verify_flags,
787  ws.m_precomputed_txdata, nSigChecksConsensus,
788  m_active_chainstate.CoinsTip())) {
789  // This can occur under some circumstances, if the node receives an
790  // unrequested tx which is invalid due to new consensus rules not
791  // being activated yet (during IBD).
792  LogPrintf("BUG! PLEASE REPORT THIS! CheckInputScripts failed against "
793  "latest-block but not STANDARD flags %s, %s\n",
794  txid.ToString(), state.ToString());
795  return Assume(false);
796  }
797 
798  if (ws.m_sig_checks_standard != nSigChecksConsensus) {
799  // We can't accept this transaction as we've used the standard count
800  // for the mempool/mining, but the consensus count will be enforced
801  // in validation (we don't want to produce bad block templates).
802  return error(
803  "%s: BUG! PLEASE REPORT THIS! SigChecks count differed between "
804  "standard and consensus flags in %s",
805  __func__, txid.ToString());
806  }
807  return true;
808 }
809 
810 bool MemPoolAccept::Finalize(const ATMPArgs &args, Workspace &ws) {
812  AssertLockHeld(m_pool.cs);
813  const TxId &txid = ws.m_ptx->GetId();
814  TxValidationState &state = ws.m_state;
815  const bool bypass_limits = args.m_bypass_limits;
816 
817  // Store transaction in memory
818  CTxMemPoolEntry *pentry = ws.m_entry.release();
819  auto entry = CTxMemPoolEntryRef::acquire(pentry);
820  m_pool.addUnchecked(entry);
821 
822  // Trim mempool and check if tx was trimmed.
823  // If we are validating a package, don't trim here because we could evict a
824  // previous transaction in the package. LimitMempoolSize() should be called
825  // at the very end to make sure the mempool is still within limits and
826  // package submission happens atomically.
827  if (!args.m_package_submission && !bypass_limits) {
828  m_pool.LimitSize(m_active_chainstate.CoinsTip());
829  if (!m_pool.exists(txid)) {
830  // The tx no longer meets our (new) mempool minimum feerate but
831  // could be reconsidered in a package.
833  "mempool full");
834  }
835  }
836  return true;
837 }
838 
839 // Get the coins spent by ptx from the coins_view. Assumes coins are present.
840 static std::vector<Coin> getSpentCoins(const CTransactionRef &ptx,
841  const CCoinsViewCache &coins_view) {
842  std::vector<Coin> spent_coins;
843  spent_coins.reserve(ptx->vin.size());
844  for (const CTxIn &input : ptx->vin) {
845  Coin coin;
846  const bool coinFound = coins_view.GetCoin(input.prevout, coin);
847  Assume(coinFound);
848  spent_coins.push_back(std::move(coin));
849  }
850  return spent_coins;
851 }
852 
853 bool MemPoolAccept::SubmitPackage(
854  const ATMPArgs &args, std::vector<Workspace> &workspaces,
855  PackageValidationState &package_state,
856  std::map<TxId, MempoolAcceptResult> &results) {
858  AssertLockHeld(m_pool.cs);
859  // Sanity check: none of the transactions should be in the mempool.
860  assert(std::all_of(
861  workspaces.cbegin(), workspaces.cend(),
862  [this](const auto &ws) { return !m_pool.exists(ws.m_ptx->GetId()); }));
863 
864  bool all_submitted = true;
865  // ConsensusScriptChecks adds to the script cache and is therefore
866  // consensus-critical; CheckInputsFromMempoolAndCache asserts that
867  // transactions only spend coins available from the mempool or UTXO set.
868  // Submit each transaction to the mempool immediately after calling
869  // ConsensusScriptChecks to make the outputs available for subsequent
870  // transactions.
871  for (Workspace &ws : workspaces) {
872  if (!ConsensusScriptChecks(args, ws)) {
873  results.emplace(ws.m_ptx->GetId(),
874  MempoolAcceptResult::Failure(ws.m_state));
875  // Since PreChecks() passed, this should never fail.
876  all_submitted = false;
877  package_state.Invalid(
879  strprintf("BUG! PolicyScriptChecks succeeded but "
880  "ConsensusScriptChecks failed: %s",
881  ws.m_ptx->GetId().ToString()));
882  }
883 
884  // If we call LimitMempoolSize() for each individual Finalize(), the
885  // mempool will not take the transaction's descendant feerate into
886  // account because it hasn't seen them yet. Also, we risk evicting a
887  // transaction that a subsequent package transaction depends on.
888  // Instead, allow the mempool to temporarily bypass limits, the maximum
889  // package size) while submitting transactions individually and then
890  // trim at the very end.
891  if (!Finalize(args, ws)) {
892  results.emplace(ws.m_ptx->GetId(),
893  MempoolAcceptResult::Failure(ws.m_state));
894  // Since LimitMempoolSize() won't be called, this should never fail.
895  all_submitted = false;
897  strprintf("BUG! Adding to mempool failed: %s",
898  ws.m_ptx->GetId().ToString()));
899  }
900  }
901 
902  // It may or may not be the case that all the transactions made it into the
903  // mempool. Regardless, make sure we haven't exceeded max mempool size.
904  m_pool.LimitSize(m_active_chainstate.CoinsTip());
905 
906  std::vector<TxId> all_package_txids;
907  all_package_txids.reserve(workspaces.size());
908  std::transform(workspaces.cbegin(), workspaces.cend(),
909  std::back_inserter(all_package_txids),
910  [](const auto &ws) { return ws.m_ptx->GetId(); });
911 
912  // Add successful results. The returned results may change later if
913  // LimitMempoolSize() evicts them.
914  for (Workspace &ws : workspaces) {
915  const auto effective_feerate =
916  args.m_package_feerates
917  ? ws.m_package_feerate
918  : CFeeRate{ws.m_modified_fees,
919  static_cast<uint32_t>(ws.m_vsize)};
920  const auto effective_feerate_txids =
921  args.m_package_feerates ? all_package_txids
922  : std::vector<TxId>({ws.m_ptx->GetId()});
923  results.emplace(ws.m_ptx->GetId(),
924  MempoolAcceptResult::Success(ws.m_vsize, ws.m_base_fees,
925  effective_feerate,
926  effective_feerate_txids));
928  ws.m_ptx,
929  std::make_shared<const std::vector<Coin>>(
930  getSpentCoins(ws.m_ptx, m_view)),
931  m_pool.GetAndIncrementSequence());
932  }
933  return all_submitted;
934 }
935 
937 MemPoolAccept::AcceptSingleTransaction(const CTransactionRef &ptx,
938  ATMPArgs &args) {
940  // mempool "read lock" (held through
941  // GetMainSignals().TransactionAddedToMempool())
942  LOCK(m_pool.cs);
943 
944  const CBlockIndex *tip = m_active_chainstate.m_chain.Tip();
945 
946  Workspace ws(ptx,
947  GetNextBlockScriptFlags(tip, m_active_chainstate.m_chainman));
948 
949  const std::vector<TxId> single_txid{ws.m_ptx->GetId()};
950 
951  // Perform the inexpensive checks first and avoid hashing and signature
952  // verification unless those checks pass, to mitigate CPU exhaustion
953  // denial-of-service attacks.
954  if (!PreChecks(args, ws)) {
955  if (ws.m_state.GetResult() == TxValidationResult::TX_RECONSIDERABLE) {
956  // Failed for fee reasons. Provide the effective feerate and which
957  // tx was included.
959  ws.m_state, CFeeRate(ws.m_modified_fees, ws.m_vsize),
960  single_txid);
961  }
962  return MempoolAcceptResult::Failure(ws.m_state);
963  }
964 
965  if (!ConsensusScriptChecks(args, ws)) {
966  return MempoolAcceptResult::Failure(ws.m_state);
967  }
968 
969  const TxId txid = ptx->GetId();
970 
971  // Mempool sanity check -- in our new mempool no tx can be added if its
972  // outputs are already spent in the mempool (that is, no children before
973  // parents allowed; the mempool must be consistent at all times).
974  //
975  // This means that on reorg, the disconnectpool *must* always import
976  // the existing mempool tx's, clear the mempool, and then re-add
977  // remaining tx's in topological order via this function. Our new mempool
978  // has fast adds, so this is ok.
979  if (auto it = m_pool.mapNextTx.lower_bound(COutPoint{txid, 0});
980  it != m_pool.mapNextTx.end() && it->first->GetTxId() == txid) {
981  LogPrintf("%s: BUG! PLEASE REPORT THIS! Attempt to add txid %s, but "
982  "its outputs are already spent in the "
983  "mempool\n",
984  __func__, txid.ToString());
986  "txn-child-before-parent");
987  return MempoolAcceptResult::Failure(ws.m_state);
988  }
989 
990  const CFeeRate effective_feerate{ws.m_modified_fees,
991  static_cast<uint32_t>(ws.m_vsize)};
992  // Tx was accepted, but not added
993  if (args.m_test_accept) {
994  return MempoolAcceptResult::Success(ws.m_vsize, ws.m_base_fees,
995  effective_feerate, single_txid);
996  }
997 
998  if (!Finalize(args, ws)) {
999  // The only possible failure reason is fee-related (mempool full).
1000  // Failed for fee reasons. Provide the effective feerate and which txns
1001  // were included.
1002  Assume(ws.m_state.GetResult() == TxValidationResult::TX_RECONSIDERABLE);
1004  ws.m_state, CFeeRate(ws.m_modified_fees, ws.m_vsize), single_txid);
1005  }
1006 
1008  ptx,
1009  std::make_shared<const std::vector<Coin>>(getSpentCoins(ptx, m_view)),
1010  m_pool.GetAndIncrementSequence());
1011 
1012  return MempoolAcceptResult::Success(ws.m_vsize, ws.m_base_fees,
1013  effective_feerate, single_txid);
1014 }
1015 
1016 PackageMempoolAcceptResult MemPoolAccept::AcceptMultipleTransactions(
1017  const std::vector<CTransactionRef> &txns, ATMPArgs &args) {
1019 
1020  // These context-free package limits can be done before taking the mempool
1021  // lock.
1022  PackageValidationState package_state;
1023  if (!CheckPackage(txns, package_state)) {
1024  return PackageMempoolAcceptResult(package_state, {});
1025  }
1026 
1027  std::vector<Workspace> workspaces{};
1028  workspaces.reserve(txns.size());
1029  std::transform(
1030  txns.cbegin(), txns.cend(), std::back_inserter(workspaces),
1031  [this](const auto &tx) {
1032  return Workspace(
1033  tx, GetNextBlockScriptFlags(m_active_chainstate.m_chain.Tip(),
1034  m_active_chainstate.m_chainman));
1035  });
1036  std::map<TxId, MempoolAcceptResult> results;
1037 
1038  LOCK(m_pool.cs);
1039 
1040  // Do all PreChecks first and fail fast to avoid running expensive script
1041  // checks when unnecessary.
1042  std::vector<TxId> valid_txids;
1043  for (Workspace &ws : workspaces) {
1044  if (!PreChecks(args, ws)) {
1046  "transaction failed");
1047  // Exit early to avoid doing pointless work. Update the failed tx
1048  // result; the rest are unfinished.
1049  results.emplace(ws.m_ptx->GetId(),
1050  MempoolAcceptResult::Failure(ws.m_state));
1051  return PackageMempoolAcceptResult(package_state,
1052  std::move(results));
1053  }
1054  // Make the coins created by this transaction available for subsequent
1055  // transactions in the package to spend.
1056  m_viewmempool.PackageAddTransaction(ws.m_ptx);
1057  valid_txids.push_back(ws.m_ptx->GetId());
1058  }
1059 
1060  // Transactions must meet two minimum feerates: the mempool minimum fee and
1061  // min relay fee. For transactions consisting of exactly one child and its
1062  // parents, it suffices to use the package feerate
1063  // (total modified fees / total size or vsize) to check this requirement.
1064  // Note that this is an aggregate feerate; this function has not checked
1065  // that there are transactions too low feerate to pay for themselves, or
1066  // that the child transactions are higher feerate than their parents. Using
1067  // aggregate feerate may allow "parents pay for child" behavior and permit
1068  // a child that is below mempool minimum feerate. To avoid these behaviors,
1069  // callers of AcceptMultipleTransactions need to restrict txns topology
1070  // (e.g. to ancestor sets) and check the feerates of individuals and
1071  // subsets.
1072  const auto m_total_size = std::accumulate(
1073  workspaces.cbegin(), workspaces.cend(), int64_t{0},
1074  [](int64_t sum, auto &ws) { return sum + ws.m_ptx->GetTotalSize(); });
1075  const auto m_total_vsize =
1076  std::accumulate(workspaces.cbegin(), workspaces.cend(), int64_t{0},
1077  [](int64_t sum, auto &ws) { return sum + ws.m_vsize; });
1078  const auto m_total_modified_fees = std::accumulate(
1079  workspaces.cbegin(), workspaces.cend(), Amount::zero(),
1080  [](Amount sum, auto &ws) { return sum + ws.m_modified_fees; });
1081  const CFeeRate package_feerate(m_total_modified_fees, m_total_vsize);
1082  std::vector<TxId> all_package_txids;
1083  all_package_txids.reserve(workspaces.size());
1084  std::transform(workspaces.cbegin(), workspaces.cend(),
1085  std::back_inserter(all_package_txids),
1086  [](const auto &ws) { return ws.m_ptx->GetId(); });
1087  TxValidationState placeholder_state;
1088  if (args.m_package_feerates &&
1089  !CheckFeeRate(m_total_size, m_total_vsize, m_total_modified_fees,
1090  placeholder_state)) {
1092  "transaction failed");
1094  package_state, {{workspaces.back().m_ptx->GetId(),
1096  placeholder_state,
1097  CFeeRate(m_total_modified_fees, m_total_vsize),
1098  all_package_txids)}});
1099  }
1100 
1101  for (Workspace &ws : workspaces) {
1102  ws.m_package_feerate = package_feerate;
1103  const TxId &ws_txid = ws.m_ptx->GetId();
1104  if (args.m_test_accept &&
1105  std::find(valid_txids.begin(), valid_txids.end(), ws_txid) !=
1106  valid_txids.end()) {
1107  const auto effective_feerate =
1108  args.m_package_feerates
1109  ? ws.m_package_feerate
1110  : CFeeRate{ws.m_modified_fees,
1111  static_cast<uint32_t>(ws.m_vsize)};
1112  const auto effective_feerate_txids =
1113  args.m_package_feerates ? all_package_txids
1114  : std::vector<TxId>{ws.m_ptx->GetId()};
1115  // When test_accept=true, transactions that pass PreChecks
1116  // are valid because there are no further mempool checks (passing
1117  // PreChecks implies passing ConsensusScriptChecks).
1118  results.emplace(ws_txid,
1120  ws.m_vsize, ws.m_base_fees, effective_feerate,
1121  effective_feerate_txids));
1122  }
1123  }
1124 
1125  if (args.m_test_accept) {
1126  return PackageMempoolAcceptResult(package_state, std::move(results));
1127  }
1128 
1129  if (!SubmitPackage(args, workspaces, package_state, results)) {
1130  // PackageValidationState filled in by SubmitPackage().
1131  return PackageMempoolAcceptResult(package_state, std::move(results));
1132  }
1133 
1134  return PackageMempoolAcceptResult(package_state, std::move(results));
1135 }
1136 
1138 MemPoolAccept::AcceptSubPackage(const std::vector<CTransactionRef> &subpackage,
1139  ATMPArgs &args) {
1141  AssertLockHeld(m_pool.cs);
1142 
1143  auto result = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_pool.cs) {
1144  if (subpackage.size() > 1) {
1145  return AcceptMultipleTransactions(subpackage, args);
1146  }
1147  const auto &tx = subpackage.front();
1148  ATMPArgs single_args = ATMPArgs::SingleInPackageAccept(args);
1149  const auto single_res = AcceptSingleTransaction(tx, single_args);
1150  PackageValidationState package_state_wrapped;
1151  if (single_res.m_result_type !=
1153  package_state_wrapped.Invalid(PackageValidationResult::PCKG_TX,
1154  "transaction failed");
1155  }
1156  return PackageMempoolAcceptResult(package_state_wrapped,
1157  {{tx->GetId(), single_res}});
1158  }();
1159 
1160  // Clean up m_view and m_viewmempool so that other subpackage evaluations
1161  // don't have access to coins they shouldn't. Keep some coins in order to
1162  // minimize re-fetching coins from the UTXO set.
1163  //
1164  // There are 3 kinds of coins in m_view:
1165  // (1) Temporary coins from the transactions in subpackage, constructed by
1166  // m_viewmempool.
1167  // (2) Mempool coins from transactions in the mempool, constructed by
1168  // m_viewmempool.
1169  // (3) Confirmed coins fetched from our current UTXO set.
1170  //
1171  // (1) Temporary coins need to be removed, regardless of whether the
1172  // transaction was submitted. If the transaction was submitted to the
1173  // mempool, m_viewmempool will be able to fetch them from there. If it
1174  // wasn't submitted to mempool, it is incorrect to keep them - future calls
1175  // may try to spend those coins that don't actually exist.
1176  // (2) Mempool coins also need to be removed. If the mempool contents have
1177  // changed as a result of submitting or replacing transactions, coins
1178  // previously fetched from mempool may now be spent or nonexistent. Those
1179  // coins need to be deleted from m_view.
1180  // (3) Confirmed coins don't need to be removed. The chainstate has not
1181  // changed (we are holding cs_main and no blocks have been processed) so the
1182  // confirmed tx cannot disappear like a mempool tx can. The coin may now be
1183  // spent after we submitted a tx to mempool, but we have already checked
1184  // that the package does not have 2 transactions spending the same coin.
1185  // Keeping them in m_view is an optimization to not re-fetch confirmed coins
1186  // if we later look up inputs for this transaction again.
1187  for (const auto &outpoint : m_viewmempool.GetNonBaseCoins()) {
1188  // In addition to resetting m_viewmempool, we also need to manually
1189  // delete these coins from m_view because it caches copies of the coins
1190  // it fetched from m_viewmempool previously.
1191  m_view.Uncache(outpoint);
1192  }
1193  // This deletes the temporary and mempool coins.
1194  m_viewmempool.Reset();
1195  return result;
1196 }
1197 
1198 PackageMempoolAcceptResult MemPoolAccept::AcceptPackage(const Package &package,
1199  ATMPArgs &args) {
1201  // Used if returning a PackageMempoolAcceptResult directly from this
1202  // function.
1203  PackageValidationState package_state_quit_early;
1204 
1205  // Check that the package is well-formed. If it isn't, we won't try to
1206  // validate any of the transactions and thus won't return any
1207  // MempoolAcceptResults, just a package-wide error.
1208 
1209  // Context-free package checks.
1210  if (!CheckPackage(package, package_state_quit_early)) {
1211  return PackageMempoolAcceptResult(package_state_quit_early, {});
1212  }
1213 
1214  // All transactions in the package must be a parent of the last transaction.
1215  // This is just an opportunity for us to fail fast on a context-free check
1216  // without taking the mempool lock.
1217  if (!IsChildWithParents(package)) {
1218  package_state_quit_early.Invalid(PackageValidationResult::PCKG_POLICY,
1219  "package-not-child-with-parents");
1220  return PackageMempoolAcceptResult(package_state_quit_early, {});
1221  }
1222 
1223  // IsChildWithParents() guarantees the package is > 1 transactions.
1224  assert(package.size() > 1);
1225  // The package must be 1 child with all of its unconfirmed parents. The
1226  // package is expected to be sorted, so the last transaction is the child.
1227  const auto &child = package.back();
1228  std::unordered_set<TxId, SaltedTxIdHasher> unconfirmed_parent_txids;
1229  std::transform(
1230  package.cbegin(), package.cend() - 1,
1231  std::inserter(unconfirmed_parent_txids, unconfirmed_parent_txids.end()),
1232  [](const auto &tx) { return tx->GetId(); });
1233 
1234  // All child inputs must refer to a preceding package transaction or a
1235  // confirmed UTXO. The only way to verify this is to look up the child's
1236  // inputs in our current coins view (not including mempool), and enforce
1237  // that all parents not present in the package be available at chain tip.
1238  // Since this check can bring new coins into the coins cache, keep track of
1239  // these coins and uncache them if we don't end up submitting this package
1240  // to the mempool.
1241  const CCoinsViewCache &coins_tip_cache = m_active_chainstate.CoinsTip();
1242  for (const auto &input : child->vin) {
1243  if (!coins_tip_cache.HaveCoinInCache(input.prevout)) {
1244  args.m_coins_to_uncache.push_back(input.prevout);
1245  }
1246  }
1247  // Using the MemPoolAccept m_view cache allows us to look up these same
1248  // coins faster later. This should be connecting directly to CoinsTip, not
1249  // to m_viewmempool, because we specifically require inputs to be confirmed
1250  // if they aren't in the package.
1251  m_view.SetBackend(m_active_chainstate.CoinsTip());
1252  const auto package_or_confirmed = [this, &unconfirmed_parent_txids](
1253  const auto &input) {
1254  return unconfirmed_parent_txids.count(input.prevout.GetTxId()) > 0 ||
1255  m_view.HaveCoin(input.prevout);
1256  };
1257  if (!std::all_of(child->vin.cbegin(), child->vin.cend(),
1258  package_or_confirmed)) {
1259  package_state_quit_early.Invalid(
1261  "package-not-child-with-unconfirmed-parents");
1262  return PackageMempoolAcceptResult(package_state_quit_early, {});
1263  }
1264  // Protect against bugs where we pull more inputs from disk that miss being
1265  // added to coins_to_uncache. The backend will be connected again when
1266  // needed in PreChecks.
1267  m_view.SetBackend(m_dummy);
1268 
1269  LOCK(m_pool.cs);
1270  // Stores results from which we will create the returned
1271  // PackageMempoolAcceptResult. A result may be changed if a mempool
1272  // transaction is evicted later due to LimitMempoolSize().
1273  std::map<TxId, MempoolAcceptResult> results_final;
1274  // Results from individual validation which will be returned if no other
1275  // result is available for this transaction. "Nonfinal" because if a
1276  // transaction fails by itself but succeeds later (i.e. when evaluated with
1277  // a fee-bumping child), the result in this map may be discarded.
1278  std::map<TxId, MempoolAcceptResult> individual_results_nonfinal;
1279  bool quit_early{false};
1280  std::vector<CTransactionRef> txns_package_eval;
1281  for (const auto &tx : package) {
1282  const auto &txid = tx->GetId();
1283  // An already confirmed tx is treated as one not in mempool, because all
1284  // we know is that the inputs aren't available.
1285  if (m_pool.exists(txid)) {
1286  // Exact transaction already exists in the mempool.
1287  // Node operators are free to set their mempool policies however
1288  // they please, nodes may receive transactions in different orders,
1289  // and malicious counterparties may try to take advantage of policy
1290  // differences to pin or delay propagation of transactions. As such,
1291  // it's possible for some package transaction(s) to already be in
1292  // the mempool, and we don't want to reject the entire package in
1293  // that case (as that could be a censorship vector). De-duplicate
1294  // the transactions that are already in the mempool, and only call
1295  // AcceptMultipleTransactions() with the new transactions. This
1296  // ensures we don't double-count transaction counts and sizes when
1297  // checking ancestor/descendant limits, or double-count transaction
1298  // fees for fee-related policy.
1299  auto iter = m_pool.GetIter(txid);
1300  assert(iter != std::nullopt);
1301  results_final.emplace(txid, MempoolAcceptResult::MempoolTx(
1302  (*iter.value())->GetTxSize(),
1303  (*iter.value())->GetFee()));
1304  } else {
1305  // Transaction does not already exist in the mempool.
1306  // Try submitting the transaction on its own.
1307  const auto single_package_res = AcceptSubPackage({tx}, args);
1308  const auto &single_res = single_package_res.m_tx_results.at(txid);
1309  if (single_res.m_result_type ==
1311  // The transaction succeeded on its own and is now in the
1312  // mempool. Don't include it in package validation, because its
1313  // fees should only be "used" once.
1314  assert(m_pool.exists(txid));
1315  results_final.emplace(txid, single_res);
1316  } else if (single_res.m_state.GetResult() !=
1318  single_res.m_state.GetResult() !=
1320  // Package validation policy only differs from individual policy
1321  // in its evaluation of feerate. For example, if a transaction
1322  // fails here due to violation of a consensus rule, the result
1323  // will not change when it is submitted as part of a package. To
1324  // minimize the amount of repeated work, unless the transaction
1325  // fails due to feerate or missing inputs (its parent is a
1326  // previous transaction in the package that failed due to
1327  // feerate), don't run package validation. Note that this
1328  // decision might not make sense if different types of packages
1329  // are allowed in the future. Continue individually validating
1330  // the rest of the transactions, because some of them may still
1331  // be valid.
1332  quit_early = true;
1333  package_state_quit_early.Invalid(
1334  PackageValidationResult::PCKG_TX, "transaction failed");
1335  individual_results_nonfinal.emplace(txid, single_res);
1336  } else {
1337  individual_results_nonfinal.emplace(txid, single_res);
1338  txns_package_eval.push_back(tx);
1339  }
1340  }
1341  }
1342 
1343  auto multi_submission_result =
1344  quit_early || txns_package_eval.empty()
1345  ? PackageMempoolAcceptResult(package_state_quit_early, {})
1346  : AcceptSubPackage(txns_package_eval, args);
1347  PackageValidationState &package_state_final =
1348  multi_submission_result.m_state;
1349 
1350  // Make sure we haven't exceeded max mempool size.
1351  // Package transactions that were submitted to mempool or already in mempool
1352  // may be evicted.
1353  m_pool.LimitSize(m_active_chainstate.CoinsTip());
1354 
1355  for (const auto &tx : package) {
1356  const auto &txid = tx->GetId();
1357  if (multi_submission_result.m_tx_results.count(txid) > 0) {
1358  // We shouldn't have re-submitted if the tx result was already in
1359  // results_final.
1360  Assume(results_final.count(txid) == 0);
1361  // If it was submitted, check to see if the tx is still in the
1362  // mempool. It could have been evicted due to LimitMempoolSize()
1363  // above.
1364  const auto &txresult =
1365  multi_submission_result.m_tx_results.at(txid);
1366  if (txresult.m_result_type ==
1368  !m_pool.exists(txid)) {
1369  package_state_final.Invalid(PackageValidationResult::PCKG_TX,
1370  "transaction failed");
1371  TxValidationState mempool_full_state;
1372  mempool_full_state.Invalid(
1373  TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
1374  results_final.emplace(
1375  txid, MempoolAcceptResult::Failure(mempool_full_state));
1376  } else {
1377  results_final.emplace(txid, txresult);
1378  }
1379  } else if (const auto final_it{results_final.find(txid)};
1380  final_it != results_final.end()) {
1381  // Already-in-mempool transaction. Check to see if it's still there,
1382  // as it could have been evicted when LimitMempoolSize() was called.
1383  Assume(final_it->second.m_result_type !=
1385  Assume(individual_results_nonfinal.count(txid) == 0);
1386  if (!m_pool.exists(tx->GetId())) {
1387  package_state_final.Invalid(PackageValidationResult::PCKG_TX,
1388  "transaction failed");
1389  TxValidationState mempool_full_state;
1390  mempool_full_state.Invalid(
1391  TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
1392  // Replace the previous result.
1393  results_final.erase(txid);
1394  results_final.emplace(
1395  txid, MempoolAcceptResult::Failure(mempool_full_state));
1396  }
1397  } else if (const auto non_final_it{
1398  individual_results_nonfinal.find(txid)};
1399  non_final_it != individual_results_nonfinal.end()) {
1400  Assume(non_final_it->second.m_result_type ==
1402  // Interesting result from previous processing.
1403  results_final.emplace(txid, non_final_it->second);
1404  }
1405  }
1406  Assume(results_final.size() == package.size());
1407  return PackageMempoolAcceptResult(package_state_final,
1408  std::move(results_final));
1409 }
1410 } // namespace
1411 
1413  const CTransactionRef &tx,
1414  int64_t accept_time, bool bypass_limits,
1415  bool test_accept,
1416  unsigned int heightOverride) {
1418  assert(active_chainstate.GetMempool() != nullptr);
1419  CTxMemPool &pool{*active_chainstate.GetMempool()};
1420 
1421  std::vector<COutPoint> coins_to_uncache;
1422  auto args = MemPoolAccept::ATMPArgs::SingleAccept(
1423  active_chainstate.m_chainman.GetConfig(), accept_time, bypass_limits,
1424  coins_to_uncache, test_accept, heightOverride);
1425  const MempoolAcceptResult result = MemPoolAccept(pool, active_chainstate)
1426  .AcceptSingleTransaction(tx, args);
1428  // Remove coins that were not present in the coins cache before calling
1429  // ATMPW; this is to prevent memory DoS in case we receive a large
1430  // number of invalid transactions that attempt to overrun the in-memory
1431  // coins cache
1432  // (`CCoinsViewCache::cacheCoins`).
1433 
1434  for (const COutPoint &outpoint : coins_to_uncache) {
1435  active_chainstate.CoinsTip().Uncache(outpoint);
1436  }
1437  }
1438 
1439  // After we've (potentially) uncached entries, ensure our coins cache is
1440  // still within its size limits
1441  BlockValidationState stateDummy;
1442  active_chainstate.FlushStateToDisk(stateDummy, FlushStateMode::PERIODIC);
1443  return result;
1444 }
1445 
1447  CTxMemPool &pool,
1448  const Package &package,
1449  bool test_accept) {
1451  assert(!package.empty());
1452  assert(std::all_of(package.cbegin(), package.cend(),
1453  [](const auto &tx) { return tx != nullptr; }));
1454 
1455  const Config &config = active_chainstate.m_chainman.GetConfig();
1456 
1457  std::vector<COutPoint> coins_to_uncache;
1458  const auto result = [&]() EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
1460  if (test_accept) {
1461  auto args = MemPoolAccept::ATMPArgs::PackageTestAccept(
1462  config, GetTime(), coins_to_uncache);
1463  return MemPoolAccept(pool, active_chainstate)
1464  .AcceptMultipleTransactions(package, args);
1465  } else {
1466  auto args = MemPoolAccept::ATMPArgs::PackageChildWithParents(
1467  config, GetTime(), coins_to_uncache);
1468  return MemPoolAccept(pool, active_chainstate)
1469  .AcceptPackage(package, args);
1470  }
1471  }();
1472 
1473  // Uncache coins pertaining to transactions that were not submitted to the
1474  // mempool.
1475  if (test_accept || result.m_state.IsInvalid()) {
1476  for (const COutPoint &hashTx : coins_to_uncache) {
1477  active_chainstate.CoinsTip().Uncache(hashTx);
1478  }
1479  }
1480  // Ensure the coins cache is still within limits.
1481  BlockValidationState state_dummy;
1482  active_chainstate.FlushStateToDisk(state_dummy, FlushStateMode::PERIODIC);
1483  return result;
1484 }
1485 
1486 Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams) {
1487  int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1488  // Force block reward to zero when right shift is undefined.
1489  if (halvings >= 64) {
1490  return Amount::zero();
1491  }
1492 
1493  Amount nSubsidy = 50 * COIN;
1494  // Subsidy is cut in half every 210,000 blocks which will occur
1495  // approximately every 4 years.
1496  return ((nSubsidy / SATOSHI) >> halvings) * SATOSHI;
1497 }
1498 
1500  : m_dbview{std::move(db_params), std::move(options)},
1501  m_catcherview(&m_dbview) {}
1502 
1503 void CoinsViews::InitCache() {
1505  m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
1506 }
1507 
1509  ChainstateManager &chainman,
1510  std::optional<BlockHash> from_snapshot_blockhash)
1511  : m_mempool(mempool), m_blockman(blockman), m_chainman(chainman),
1512  m_from_snapshot_blockhash(from_snapshot_blockhash) {}
1513 
1514 void Chainstate::InitCoinsDB(size_t cache_size_bytes, bool in_memory,
1515  bool should_wipe, std::string leveldb_name) {
1517  leveldb_name += node::SNAPSHOT_CHAINSTATE_SUFFIX;
1518  }
1519 
1520  m_coins_views = std::make_unique<CoinsViews>(
1521  DBParams{.path = m_chainman.m_options.datadir / leveldb_name,
1522  .cache_bytes = cache_size_bytes,
1523  .memory_only = in_memory,
1524  .wipe_data = should_wipe,
1525  .obfuscate = true,
1526  .options = m_chainman.m_options.coins_db},
1528 }
1529 
1530 void Chainstate::InitCoinsCache(size_t cache_size_bytes) {
1532  assert(m_coins_views != nullptr);
1533  m_coinstip_cache_size_bytes = cache_size_bytes;
1534  m_coins_views->InitCache();
1535 }
1536 
1537 // Note that though this is marked const, we may end up modifying
1538 // `m_cached_finished_ibd`, which is a performance-related implementation
1539 // detail. This function must be marked `const` so that `CValidationInterface`
1540 // clients (which are given a `const Chainstate*`) can call it.
1541 //
1543  // Optimization: pre-test latch before taking the lock.
1544  if (m_cached_finished_ibd.load(std::memory_order_relaxed)) {
1545  return false;
1546  }
1547 
1548  LOCK(cs_main);
1549  if (m_cached_finished_ibd.load(std::memory_order_relaxed)) {
1550  return false;
1551  }
1553  return true;
1554  }
1555  if (m_chain.Tip() == nullptr) {
1556  return true;
1557  }
1559  return true;
1560  }
1561  if (m_chain.Tip()->Time() <
1562  Now<NodeSeconds>() - m_chainman.m_options.max_tip_age) {
1563  return true;
1564  }
1565  LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1566  m_cached_finished_ibd.store(true, std::memory_order_relaxed);
1567  return false;
1568 }
1569 
1572 
1573  // Before we get past initial download, we cannot reliably alert about forks
1574  // (we assume we don't get stuck on a fork before finishing our initial
1575  // sync)
1576  if (IsInitialBlockDownload()) {
1577  return;
1578  }
1579 
1580  // If our best fork is no longer within 72 blocks (+/- 12 hours if no one
1581  // mines it) of our head, or if it is back on the active chain, drop it
1582  if (m_best_fork_tip && (m_chain.Height() - m_best_fork_tip->nHeight >= 72 ||
1584  m_best_fork_tip = nullptr;
1585  }
1586 
1587  if (m_best_fork_tip ||
1588  (m_chainman.m_best_invalid &&
1589  m_chainman.m_best_invalid->nChainWork >
1590  m_chain.Tip()->nChainWork + (GetBlockProof(*m_chain.Tip()) * 6))) {
1592  std::string warning =
1593  std::string("'Warning: Large-work fork detected, forking after "
1594  "block ") +
1595  m_best_fork_base->phashBlock->ToString() + std::string("'");
1596  m_chainman.GetNotifications().warning(warning);
1597  }
1598 
1600  LogPrintf("%s: Warning: Large fork found\n forking the "
1601  "chain at height %d (%s)\n lasting to height %d "
1602  "(%s).\nChain state database corruption likely.\n",
1603  __func__, m_best_fork_base->nHeight,
1607  SetfLargeWorkForkFound(true);
1608  } else {
1609  LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks "
1610  "longer than our best chain.\nChain state database "
1611  "corruption likely.\n",
1612  __func__);
1614  }
1615  } else {
1616  SetfLargeWorkForkFound(false);
1618  }
1619 }
1620 
1622  CBlockIndex *pindexNewForkTip) {
1624 
1625  // If we are on a fork that is sufficiently large, set a warning flag.
1626  const CBlockIndex *pfork = m_chain.FindFork(pindexNewForkTip);
1627 
1628  // We define a condition where we should warn the user about as a fork of at
1629  // least 7 blocks with a tip within 72 blocks (+/- 12 hours if no one mines
1630  // it) of ours. We use 7 blocks rather arbitrarily as it represents just
1631  // under 10% of sustained network hash rate operating on the fork, or a
1632  // chain that is entirely longer than ours and invalid (note that this
1633  // should be detected by both). We define it this way because it allows us
1634  // to only store the highest fork tip (+ base) which meets the 7-block
1635  // condition and from this always have the most-likely-to-cause-warning fork
1636  if (pfork &&
1637  (!m_best_fork_tip ||
1638  pindexNewForkTip->nHeight > m_best_fork_tip->nHeight) &&
1639  pindexNewForkTip->nChainWork - pfork->nChainWork >
1640  (GetBlockProof(*pfork) * 7) &&
1641  m_chain.Height() - pindexNewForkTip->nHeight < 72) {
1642  m_best_fork_tip = pindexNewForkTip;
1643  m_best_fork_base = pfork;
1644  }
1645 
1647 }
1648 
1649 // Called both upon regular invalid block discovery *and* InvalidateBlock
1652  if (!m_chainman.m_best_invalid ||
1653  pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork) {
1654  m_chainman.m_best_invalid = pindexNew;
1655  }
1656  if (m_chainman.m_best_header != nullptr &&
1657  m_chainman.m_best_header->GetAncestor(pindexNew->nHeight) ==
1658  pindexNew) {
1659  m_chainman.m_best_header = m_chain.Tip();
1660  }
1661 
1662  // If the invalid chain found is supposed to be finalized, we need to move
1663  // back the finalization point.
1664  if (IsBlockAvalancheFinalized(pindexNew)) {
1666  m_avalancheFinalizedBlockIndex = pindexNew->pprev;
1667  }
1668 
1669  LogPrintf("%s: invalid block=%s height=%d log2_work=%f date=%s\n",
1670  __func__, pindexNew->GetBlockHash().ToString(),
1671  pindexNew->nHeight,
1672  log(pindexNew->nChainWork.getdouble()) / log(2.0),
1673  FormatISO8601DateTime(pindexNew->GetBlockTime()));
1674  CBlockIndex *tip = m_chain.Tip();
1675  assert(tip);
1676  LogPrintf("%s: current best=%s height=%d log2_work=%f date=%s\n",
1677  __func__, tip->GetBlockHash().ToString(), m_chain.Height(),
1678  log(tip->nChainWork.getdouble()) / log(2.0),
1680 }
1681 
1682 // Same as InvalidChainFound, above, except not called directly from
1683 // InvalidateBlock, which does its own setBlockIndexCandidates management.
1685  const BlockValidationState &state) {
1688  pindex->nStatus = pindex->nStatus.withFailed();
1689  m_chainman.m_failed_blocks.insert(pindex);
1690  m_blockman.m_dirty_blockindex.insert(pindex);
1691  InvalidChainFound(pindex);
1692  }
1693 }
1694 
1695 void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
1696  int nHeight) {
1697  // Mark inputs spent.
1698  if (tx.IsCoinBase()) {
1699  return;
1700  }
1701 
1702  txundo.vprevout.reserve(tx.vin.size());
1703  for (const CTxIn &txin : tx.vin) {
1704  txundo.vprevout.emplace_back();
1705  bool is_spent = view.SpendCoin(txin.prevout, &txundo.vprevout.back());
1706  assert(is_spent);
1707  }
1708 }
1709 
1710 void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
1711  int nHeight) {
1712  SpendCoins(view, tx, txundo, nHeight);
1713  AddCoins(view, tx, nHeight);
1714 }
1715 
1717  const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1718  if (!VerifyScript(scriptSig, m_tx_out.scriptPubKey, nFlags,
1721  metrics, &error)) {
1722  return false;
1723  }
1724  if ((pTxLimitSigChecks &&
1728  // we can't assign a meaningful script error (since the script
1729  // succeeded), but remove the ScriptError::OK which could be
1730  // misinterpreted.
1732  return false;
1733  }
1734  return true;
1735 }
1736 
1738  const CCoinsViewCache &inputs, const uint32_t flags,
1739  bool sigCacheStore, bool scriptCacheStore,
1740  const PrecomputedTransactionData &txdata,
1741  int &nSigChecksOut, TxSigCheckLimiter &txLimitSigChecks,
1742  CheckInputsLimiter *pBlockLimitSigChecks,
1743  std::vector<CScriptCheck> *pvChecks) {
1745  assert(!tx.IsCoinBase());
1746 
1747  if (pvChecks) {
1748  pvChecks->reserve(tx.vin.size());
1749  }
1750 
1751  // First check if script executions have been cached with the same flags.
1752  // Note that this assumes that the inputs provided are correct (ie that the
1753  // transaction hash which is in tx's prevouts properly commits to the
1754  // scriptPubKey in the inputs view of that transaction).
1755  ScriptCacheKey hashCacheEntry(tx, flags);
1756  if (IsKeyInScriptCache(hashCacheEntry, !scriptCacheStore, nSigChecksOut)) {
1757  if (!txLimitSigChecks.consume_and_check(nSigChecksOut) ||
1758  (pBlockLimitSigChecks &&
1759  !pBlockLimitSigChecks->consume_and_check(nSigChecksOut))) {
1761  "too-many-sigchecks");
1762  }
1763  return true;
1764  }
1765 
1766  int nSigChecksTotal = 0;
1767 
1768  for (size_t i = 0; i < tx.vin.size(); i++) {
1769  const COutPoint &prevout = tx.vin[i].prevout;
1770  const Coin &coin = inputs.AccessCoin(prevout);
1771  assert(!coin.IsSpent());
1772 
1773  // We very carefully only pass in things to CScriptCheck which are
1774  // clearly committed to by tx's hash. This provides a sanity
1775  // check that our caching is not introducing consensus failures through
1776  // additional data in, eg, the coins being spent being checked as a part
1777  // of CScriptCheck.
1778 
1779  // Verify signature
1780  CScriptCheck check(coin.GetTxOut(), tx, i, flags, sigCacheStore, txdata,
1781  &txLimitSigChecks, pBlockLimitSigChecks);
1782 
1783  // If pvChecks is not null, defer the check execution to the caller.
1784  if (pvChecks) {
1785  pvChecks->push_back(std::move(check));
1786  continue;
1787  }
1788 
1789  if (!check()) {
1790  ScriptError scriptError = check.GetScriptError();
1791  // Compute flags without the optional standardness flags.
1792  // This differs from MANDATORY_SCRIPT_VERIFY_FLAGS as it contains
1793  // additional upgrade flags (see AcceptToMemoryPoolWorker variable
1794  // extraFlags).
1795  uint32_t mandatoryFlags =
1797  if (flags != mandatoryFlags) {
1798  // Check whether the failure was caused by a non-mandatory
1799  // script verification check. If so, ensure we return
1800  // NOT_STANDARD instead of CONSENSUS to avoid downstream users
1801  // splitting the network between upgraded and non-upgraded nodes
1802  // by banning CONSENSUS-failing data providers.
1803  CScriptCheck check2(coin.GetTxOut(), tx, i, mandatoryFlags,
1804  sigCacheStore, txdata);
1805  if (check2()) {
1806  return state.Invalid(
1808  strprintf("non-mandatory-script-verify-flag (%s)",
1809  ScriptErrorString(scriptError)));
1810  }
1811  // update the error message to reflect the mandatory violation.
1812  scriptError = check2.GetScriptError();
1813  }
1814 
1815  // MANDATORY flag failures correspond to
1816  // TxValidationResult::TX_CONSENSUS. Because CONSENSUS failures are
1817  // the most serious case of validation failures, we may need to
1818  // consider using RECENT_CONSENSUS_CHANGE for any script failure
1819  // that could be due to non-upgraded nodes which we may want to
1820  // support, to avoid splitting the network (but this depends on the
1821  // details of how net_processing handles such errors).
1822  return state.Invalid(
1824  strprintf("mandatory-script-verify-flag-failed (%s)",
1825  ScriptErrorString(scriptError)));
1826  }
1827 
1828  nSigChecksTotal += check.GetScriptExecutionMetrics().nSigChecks;
1829  }
1830 
1831  nSigChecksOut = nSigChecksTotal;
1832 
1833  if (scriptCacheStore && !pvChecks) {
1834  // We executed all of the provided scripts, and were told to cache the
1835  // result. Do so now.
1836  AddKeyInScriptCache(hashCacheEntry, nSigChecksTotal);
1837  }
1838 
1839  return true;
1840 }
1841 
1842 bool AbortNode(BlockValidationState &state, const std::string &strMessage,
1843  const bilingual_str &userMessage) {
1844  AbortNode(strMessage, userMessage);
1845  return state.Error(strMessage);
1846 }
1847 
1850  const COutPoint &out) {
1851  bool fClean = true;
1852 
1853  if (view.HaveCoin(out)) {
1854  // Overwriting transaction output.
1855  fClean = false;
1856  }
1857 
1858  if (undo.GetHeight() == 0) {
1859  // Missing undo metadata (height and coinbase). Older versions included
1860  // this information only in undo records for the last spend of a
1861  // transactions' outputs. This implies that it must be present for some
1862  // other output of the same tx.
1863  const Coin &alternate = AccessByTxid(view, out.GetTxId());
1864  if (alternate.IsSpent()) {
1865  // Adding output for transaction without known metadata
1866  return DisconnectResult::FAILED;
1867  }
1868 
1869  // This is somewhat ugly, but hopefully utility is limited. This is only
1870  // useful when working from legacy on disck data. In any case, putting
1871  // the correct information in there doesn't hurt.
1872  const_cast<Coin &>(undo) = Coin(undo.GetTxOut(), alternate.GetHeight(),
1873  alternate.IsCoinBase());
1874  }
1875 
1876  // If the coin already exists as an unspent coin in the cache, then the
1877  // possible_overwrite parameter to AddCoin must be set to true. We have
1878  // already checked whether an unspent coin exists above using HaveCoin, so
1879  // we don't need to guess. When fClean is false, an unspent coin already
1880  // existed and it is an overwrite.
1881  view.AddCoin(out, std::move(undo), !fClean);
1882 
1884 }
1885 
1890 DisconnectResult Chainstate::DisconnectBlock(const CBlock &block,
1891  const CBlockIndex *pindex,
1892  CCoinsViewCache &view) {
1894  CBlockUndo blockUndo;
1895  if (!m_blockman.UndoReadFromDisk(blockUndo, *pindex)) {
1896  error("DisconnectBlock(): failure reading undo data");
1897  return DisconnectResult::FAILED;
1898  }
1899 
1900  return ApplyBlockUndo(std::move(blockUndo), block, pindex, view);
1901 }
1902 
1904  const CBlockIndex *pindex,
1905  CCoinsViewCache &view) {
1906  bool fClean = true;
1907 
1908  if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1909  error("DisconnectBlock(): block and undo data inconsistent");
1910  return DisconnectResult::FAILED;
1911  }
1912 
1913  // First, restore inputs.
1914  for (size_t i = 1; i < block.vtx.size(); i++) {
1915  const CTransaction &tx = *(block.vtx[i]);
1916  CTxUndo &txundo = blockUndo.vtxundo[i - 1];
1917  if (txundo.vprevout.size() != tx.vin.size()) {
1918  error("DisconnectBlock(): transaction and undo data inconsistent");
1919  return DisconnectResult::FAILED;
1920  }
1921 
1922  for (size_t j = 0; j < tx.vin.size(); j++) {
1923  const COutPoint &out = tx.vin[j].prevout;
1924  DisconnectResult res =
1925  UndoCoinSpend(std::move(txundo.vprevout[j]), view, out);
1926  if (res == DisconnectResult::FAILED) {
1927  return DisconnectResult::FAILED;
1928  }
1929  fClean = fClean && res != DisconnectResult::UNCLEAN;
1930  }
1931  // At this point, all of txundo.vprevout should have been moved out.
1932  }
1933 
1934  // Second, revert created outputs.
1935  for (const auto &ptx : block.vtx) {
1936  const CTransaction &tx = *ptx;
1937  const TxId &txid = tx.GetId();
1938  const bool is_coinbase = tx.IsCoinBase();
1939 
1940  // Check that all outputs are available and match the outputs in the
1941  // block itself exactly.
1942  for (size_t o = 0; o < tx.vout.size(); o++) {
1943  if (tx.vout[o].scriptPubKey.IsUnspendable()) {
1944  continue;
1945  }
1946 
1947  COutPoint out(txid, o);
1948  Coin coin;
1949  bool is_spent = view.SpendCoin(out, &coin);
1950  if (!is_spent || tx.vout[o] != coin.GetTxOut() ||
1951  uint32_t(pindex->nHeight) != coin.GetHeight() ||
1952  is_coinbase != coin.IsCoinBase()) {
1953  // transaction output mismatch
1954  fClean = false;
1955  }
1956  }
1957  }
1958 
1959  // Move best block pointer to previous block.
1960  view.SetBestBlock(block.hashPrevBlock);
1961 
1963 }
1964 
1966 
1967 void StartScriptCheckWorkerThreads(int threads_num) {
1968  scriptcheckqueue.StartWorkerThreads(threads_num);
1969 }
1970 
1972  scriptcheckqueue.StopWorkerThreads();
1973 }
1974 
1975 // Returns the script flags which should be checked for the block after
1976 // the given block.
1977 static uint32_t GetNextBlockScriptFlags(const CBlockIndex *pindex,
1978  const ChainstateManager &chainman) {
1979  const Consensus::Params &consensusparams = chainman.GetConsensus();
1980 
1981  uint32_t flags = SCRIPT_VERIFY_NONE;
1982 
1983  // Enforce P2SH (BIP16)
1984  if (DeploymentActiveAfter(pindex, chainman, Consensus::DEPLOYMENT_P2SH)) {
1986  }
1987 
1988  // Enforce the DERSIG (BIP66) rule.
1989  if (DeploymentActiveAfter(pindex, chainman, Consensus::DEPLOYMENT_DERSIG)) {
1991  }
1992 
1993  // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule.
1994  if (DeploymentActiveAfter(pindex, chainman, Consensus::DEPLOYMENT_CLTV)) {
1996  }
1997 
1998  // Start enforcing CSV (BIP68, BIP112 and BIP113) rule.
1999  if (DeploymentActiveAfter(pindex, chainman, Consensus::DEPLOYMENT_CSV)) {
2001  }
2002 
2003  // If the UAHF is enabled, we start accepting replay protected txns
2004  if (IsUAHFenabled(consensusparams, pindex)) {
2007  }
2008 
2009  // If the DAA HF is enabled, we start rejecting transaction that use a high
2010  // s in their signature. We also make sure that signature that are supposed
2011  // to fail (for instance in multisig or other forms of smart contracts) are
2012  // null.
2013  if (IsDAAEnabled(consensusparams, pindex)) {
2016  }
2017 
2018  // When the magnetic anomaly fork is enabled, we start accepting
2019  // transactions using the OP_CHECKDATASIG opcode and it's verify
2020  // alternative. We also start enforcing push only signatures and
2021  // clean stack.
2022  if (IsMagneticAnomalyEnabled(consensusparams, pindex)) {
2025  }
2026 
2027  if (IsGravitonEnabled(consensusparams, pindex)) {
2030  }
2031 
2032  if (IsPhononEnabled(consensusparams, pindex)) {
2034  }
2035 
2036  // We make sure this node will have replay protection during the next hard
2037  // fork.
2038  if (IsReplayProtectionEnabled(consensusparams, pindex)) {
2040  }
2041 
2042  return flags;
2043 }
2044 
2045 static int64_t nTimeCheck = 0;
2046 static int64_t nTimeForks = 0;
2047 static int64_t nTimeVerify = 0;
2048 static int64_t nTimeConnect = 0;
2049 static int64_t nTimeIndex = 0;
2050 static int64_t nTimeTotal = 0;
2051 static int64_t nBlocksTotal = 0;
2052 
2059 bool Chainstate::ConnectBlock(const CBlock &block, BlockValidationState &state,
2060  CBlockIndex *pindex, CCoinsViewCache &view,
2061  BlockValidationOptions options, Amount *blockFees,
2062  bool fJustCheck) {
2064  assert(pindex);
2065 
2066  const BlockHash block_hash{block.GetHash()};
2067  assert(*pindex->phashBlock == block_hash);
2068 
2069  int64_t nTimeStart = GetTimeMicros();
2070 
2071  const CChainParams &params{m_chainman.GetParams()};
2072  const Consensus::Params &consensusParams = params.GetConsensus();
2073 
2074  // Check it again in case a previous version let a bad block in
2075  // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
2076  // ContextualCheckBlockHeader() here. This means that if we add a new
2077  // consensus rule that is enforced in one of those two functions, then we
2078  // may have let in a block that violates the rule prior to updating the
2079  // software, and we would NOT be enforcing the rule here. Fully solving
2080  // upgrade from one software version to the next after a consensus rule
2081  // change is potentially tricky and issue-specific.
2082  // Also, currently the rule against blocks more than 2 hours in the future
2083  // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
2084  // re-enforce that rule here (at least until we make it impossible for
2085  // m_adjusted_time_callback() to go backward).
2086  if (!CheckBlock(block, state, consensusParams,
2087  options.withCheckPoW(!fJustCheck)
2088  .withCheckMerkleRoot(!fJustCheck))) {
2090  // We don't write down blocks to disk if they may have been
2091  // corrupted, so this should be impossible unless we're having
2092  // hardware problems.
2093  return AbortNode(state, "Corrupt block found indicating potential "
2094  "hardware failure; shutting down");
2095  }
2096  return error("%s: Consensus::CheckBlock: %s", __func__,
2097  state.ToString());
2098  }
2099 
2100  // Verify that the view's current state corresponds to the previous block
2101  BlockHash hashPrevBlock =
2102  pindex->pprev == nullptr ? BlockHash() : pindex->pprev->GetBlockHash();
2103  assert(hashPrevBlock == view.GetBestBlock());
2104 
2105  nBlocksTotal++;
2106 
2107  // Special case for the genesis block, skipping connection of its
2108  // transactions (its coinbase is unspendable)
2109  if (block_hash == consensusParams.hashGenesisBlock) {
2110  if (!fJustCheck) {
2111  view.SetBestBlock(pindex->GetBlockHash());
2112  }
2113 
2114  return true;
2115  }
2116 
2117  bool fScriptChecks = true;
2118  if (!m_chainman.AssumedValidBlock().IsNull()) {
2119  // We've been configured with the hash of a block which has been
2120  // externally verified to have a valid history. A suitable default value
2121  // is included with the software and updated from time to time. Because
2122  // validity relative to a piece of software is an objective fact these
2123  // defaults can be easily reviewed. This setting doesn't force the
2124  // selection of any particular chain but makes validating some faster by
2125  // effectively caching the result of part of the verification.
2126  BlockMap::const_iterator it{
2127  m_blockman.m_block_index.find(m_chainman.AssumedValidBlock())};
2128  if (it != m_blockman.m_block_index.end()) {
2129  if (it->second.GetAncestor(pindex->nHeight) == pindex &&
2130  m_chainman.m_best_header->GetAncestor(pindex->nHeight) ==
2131  pindex &&
2132  m_chainman.m_best_header->nChainWork >=
2134  // This block is a member of the assumed verified chain and an
2135  // ancestor of the best header.
2136  // Script verification is skipped when connecting blocks under
2137  // the assumevalid block. Assuming the assumevalid block is
2138  // valid this is safe because block merkle hashes are still
2139  // computed and checked, Of course, if an assumed valid block is
2140  // invalid due to false scriptSigs this optimization would allow
2141  // an invalid chain to be accepted.
2142  // The equivalent time check discourages hash power from
2143  // extorting the network via DOS attack into accepting an
2144  // invalid block through telling users they must manually set
2145  // assumevalid. Requiring a software change or burying the
2146  // invalid block, regardless of the setting, makes it hard to
2147  // hide the implication of the demand. This also avoids having
2148  // release candidates that are hardly doing any signature
2149  // verification at all in testing without having to artificially
2150  // set the default assumed verified block further back. The test
2151  // against the minimum chain work prevents the skipping when
2152  // denied access to any chain at least as good as the expected
2153  // chain.
2154  fScriptChecks = (GetBlockProofEquivalentTime(
2155  *m_chainman.m_best_header, *pindex,
2156  *m_chainman.m_best_header,
2157  consensusParams) <= 60 * 60 * 24 * 7 * 2);
2158  }
2159  }
2160  }
2161 
2162  int64_t nTime1 = GetTimeMicros();
2163  nTimeCheck += nTime1 - nTimeStart;
2164  LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n",
2165  MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO,
2167 
2168  // Do not allow blocks that contain transactions which 'overwrite' older
2169  // transactions, unless those are already completely spent. If such
2170  // overwrites are allowed, coinbases and transactions depending upon those
2171  // can be duplicated to remove the ability to spend the first instance --
2172  // even after being sent to another address.
2173  // See BIP30, CVE-2012-1909, and http://r6.ca/blog/20120206T005236Z.html
2174  // for more information. This rule was originally applied to all blocks
2175  // with a timestamp after March 15, 2012, 0:00 UTC. Now that the whole
2176  // chain is irreversibly beyond that time it is applied to all blocks
2177  // except the two in the chain that violate it. This prevents exploiting
2178  // the issue against nodes during their initial block download.
2179  bool fEnforceBIP30 = !((pindex->nHeight == 91842 &&
2180  pindex->GetBlockHash() ==
2181  uint256S("0x00000000000a4d0a398161ffc163c503763"
2182  "b1f4360639393e0e4c8e300e0caec")) ||
2183  (pindex->nHeight == 91880 &&
2184  pindex->GetBlockHash() ==
2185  uint256S("0x00000000000743f190a18c5577a3c2d2a1f"
2186  "610ae9601ac046a38084ccb7cd721")));
2187 
2188  // Once BIP34 activated it was not possible to create new duplicate
2189  // coinbases and thus other than starting with the 2 existing duplicate
2190  // coinbase pairs, not possible to create overwriting txs. But by the time
2191  // BIP34 activated, in each of the existing pairs the duplicate coinbase had
2192  // overwritten the first before the first had been spent. Since those
2193  // coinbases are sufficiently buried it's no longer possible to create
2194  // further duplicate transactions descending from the known pairs either. If
2195  // we're on the known chain at height greater than where BIP34 activated, we
2196  // can save the db accesses needed for the BIP30 check.
2197 
2198  // BIP34 requires that a block at height X (block X) has its coinbase
2199  // scriptSig start with a CScriptNum of X (indicated height X). The above
2200  // logic of no longer requiring BIP30 once BIP34 activates is flawed in the
2201  // case that there is a block X before the BIP34 height of 227,931 which has
2202  // an indicated height Y where Y is greater than X. The coinbase for block
2203  // X would also be a valid coinbase for block Y, which could be a BIP30
2204  // violation. An exhaustive search of all mainnet coinbases before the
2205  // BIP34 height which have an indicated height greater than the block height
2206  // reveals many occurrences. The 3 lowest indicated heights found are
2207  // 209,921, 490,897, and 1,983,702 and thus coinbases for blocks at these 3
2208  // heights would be the first opportunity for BIP30 to be violated.
2209 
2210  // The search reveals a great many blocks which have an indicated height
2211  // greater than 1,983,702, so we simply remove the optimization to skip
2212  // BIP30 checking for blocks at height 1,983,702 or higher. Before we reach
2213  // that block in another 25 years or so, we should take advantage of a
2214  // future consensus change to do a new and improved version of BIP34 that
2215  // will actually prevent ever creating any duplicate coinbases in the
2216  // future.
2217  static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
2218 
2219  // There is no potential to create a duplicate coinbase at block 209,921
2220  // because this is still before the BIP34 height and so explicit BIP30
2221  // checking is still active.
2222 
2223  // The final case is block 176,684 which has an indicated height of
2224  // 490,897. Unfortunately, this issue was not discovered until about 2 weeks
2225  // before block 490,897 so there was not much opportunity to address this
2226  // case other than to carefully analyze it and determine it would not be a
2227  // problem. Block 490,897 was, in fact, mined with a different coinbase than
2228  // block 176,684, but it is important to note that even if it hadn't been or
2229  // is remined on an alternate fork with a duplicate coinbase, we would still
2230  // not run into a BIP30 violation. This is because the coinbase for 176,684
2231  // is spent in block 185,956 in transaction
2232  // d4f7fbbf92f4a3014a230b2dc70b8058d02eb36ac06b4a0736d9d60eaa9e8781. This
2233  // spending transaction can't be duplicated because it also spends coinbase
2234  // 0328dd85c331237f18e781d692c92de57649529bd5edf1d01036daea32ffde29. This
2235  // coinbase has an indicated height of over 4.2 billion, and wouldn't be
2236  // duplicatable until that height, and it's currently impossible to create a
2237  // chain that long. Nevertheless we may wish to consider a future soft fork
2238  // which retroactively prevents block 490,897 from creating a duplicate
2239  // coinbase. The two historical BIP30 violations often provide a confusing
2240  // edge case when manipulating the UTXO and it would be simpler not to have
2241  // another edge case to deal with.
2242 
2243  // testnet3 has no blocks before the BIP34 height with indicated heights
2244  // post BIP34 before approximately height 486,000,000 and presumably will
2245  // be reset before it reaches block 1,983,702 and starts doing unnecessary
2246  // BIP30 checking again.
2247  assert(pindex->pprev);
2248  CBlockIndex *pindexBIP34height =
2249  pindex->pprev->GetAncestor(consensusParams.BIP34Height);
2250  // Only continue to enforce if we're below BIP34 activation height or the
2251  // block hash at that height doesn't correspond.
2252  fEnforceBIP30 =
2253  fEnforceBIP30 &&
2254  (!pindexBIP34height ||
2255  !(pindexBIP34height->GetBlockHash() == consensusParams.BIP34Hash));
2256 
2257  // TODO: Remove BIP30 checking from block height 1,983,702 on, once we have
2258  // a consensus change that ensures coinbases at those heights can not
2259  // duplicate earlier coinbases.
2260  if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
2261  for (const auto &tx : block.vtx) {
2262  for (size_t o = 0; o < tx->vout.size(); o++) {
2263  if (view.HaveCoin(COutPoint(tx->GetId(), o))) {
2264  LogPrintf("ERROR: ConnectBlock(): tried to overwrite "
2265  "transaction\n");
2267  "bad-txns-BIP30");
2268  }
2269  }
2270  }
2271  }
2272 
2273  // Enforce BIP68 (sequence locks).
2274  int nLockTimeFlags = 0;
2275  if (DeploymentActiveAt(*pindex, consensusParams,
2277  nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
2278  }
2279 
2280  const uint32_t flags = GetNextBlockScriptFlags(pindex->pprev, m_chainman);
2281 
2282  int64_t nTime2 = GetTimeMicros();
2283  nTimeForks += nTime2 - nTime1;
2284  LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n",
2285  MILLI * (nTime2 - nTime1), nTimeForks * MICRO,
2287 
2288  std::vector<int> prevheights;
2289  Amount nFees = Amount::zero();
2290  int nInputs = 0;
2291 
2292  // Limit the total executed signature operations in the block, a consensus
2293  // rule. Tracking during the CPU-consuming part (validation of uncached
2294  // inputs) is per-input atomic and validation in each thread stops very
2295  // quickly after the limit is exceeded, so an adversary cannot cause us to
2296  // exceed the limit by much at all.
2297  CheckInputsLimiter nSigChecksBlockLimiter(
2299 
2300  std::vector<TxSigCheckLimiter> nSigChecksTxLimiters;
2301  nSigChecksTxLimiters.resize(block.vtx.size() - 1);
2302 
2303  CBlockUndo blockundo;
2304  blockundo.vtxundo.resize(block.vtx.size() - 1);
2305 
2306  CCheckQueueControl<CScriptCheck> control(fScriptChecks ? &scriptcheckqueue
2307  : nullptr);
2308 
2309  // Add all outputs
2310  try {
2311  for (const auto &ptx : block.vtx) {
2312  AddCoins(view, *ptx, pindex->nHeight);
2313  }
2314  } catch (const std::logic_error &e) {
2315  // This error will be thrown from AddCoin if we try to connect a block
2316  // containing duplicate transactions. Such a thing should normally be
2317  // caught early nowadays (due to ContextualCheckBlock's CTOR
2318  // enforcement) however some edge cases can escape that:
2319  // - ContextualCheckBlock does not get re-run after saving the block to
2320  // disk, and older versions may have saved a weird block.
2321  // - its checks are not applied to pre-CTOR chains, which we might visit
2322  // with checkpointing off.
2323  LogPrintf("ERROR: ConnectBlock(): tried to overwrite transaction\n");
2325  "tx-duplicate");
2326  }
2327 
2328  size_t txIndex = 0;
2329  // nSigChecksRet may be accurate (found in cache) or 0 (checks were
2330  // deferred into vChecks).
2331  int nSigChecksRet;
2332  for (const auto &ptx : block.vtx) {
2333  const CTransaction &tx = *ptx;
2334  const bool isCoinBase = tx.IsCoinBase();
2335  nInputs += tx.vin.size();
2336 
2337  {
2338  Amount txfee = Amount::zero();
2339  TxValidationState tx_state;
2340  if (!isCoinBase &&
2341  !Consensus::CheckTxInputs(tx, tx_state, view, pindex->nHeight,
2342  txfee)) {
2343  // Any transaction validation failure in ConnectBlock is a block
2344  // consensus failure.
2346  tx_state.GetRejectReason(),
2347  tx_state.GetDebugMessage());
2348 
2349  return error("%s: Consensus::CheckTxInputs: %s, %s", __func__,
2350  tx.GetId().ToString(), state.ToString());
2351  }
2352  nFees += txfee;
2353  }
2354 
2355  if (!MoneyRange(nFees)) {
2356  LogPrintf("ERROR: %s: accumulated fee in the block out of range.\n",
2357  __func__);
2359  "bad-txns-accumulated-fee-outofrange");
2360  }
2361 
2362  // The following checks do not apply to the coinbase.
2363  if (isCoinBase) {
2364  continue;
2365  }
2366 
2367  // Check that transaction is BIP68 final BIP68 lock checks (as
2368  // opposed to nLockTime checks) must be in ConnectBlock because they
2369  // require the UTXO set.
2370  prevheights.resize(tx.vin.size());
2371  for (size_t j = 0; j < tx.vin.size(); j++) {
2372  prevheights[j] = view.AccessCoin(tx.vin[j].prevout).GetHeight();
2373  }
2374 
2375  if (!SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
2376  LogPrintf("ERROR: %s: contains a non-BIP68-final transaction\n",
2377  __func__);
2379  "bad-txns-nonfinal");
2380  }
2381 
2382  // Don't cache results if we're actually connecting blocks (still
2383  // consult the cache, though).
2384  bool fCacheResults = fJustCheck;
2385 
2386  const bool fEnforceSigCheck = flags & SCRIPT_ENFORCE_SIGCHECKS;
2387  if (!fEnforceSigCheck) {
2388  // Historically, there has been transactions with a very high
2389  // sigcheck count, so we need to disable this check for such
2390  // transactions.
2391  nSigChecksTxLimiters[txIndex] = TxSigCheckLimiter::getDisabled();
2392  }
2393 
2394  std::vector<CScriptCheck> vChecks;
2395  TxValidationState tx_state;
2396  if (fScriptChecks &&
2397  !CheckInputScripts(tx, tx_state, view, flags, fCacheResults,
2398  fCacheResults, PrecomputedTransactionData(tx),
2399  nSigChecksRet, nSigChecksTxLimiters[txIndex],
2400  &nSigChecksBlockLimiter, &vChecks)) {
2401  // Any transaction validation failure in ConnectBlock is a block
2402  // consensus failure
2404  tx_state.GetRejectReason(),
2405  tx_state.GetDebugMessage());
2406  return error(
2407  "ConnectBlock(): CheckInputScripts on %s failed with %s",
2408  tx.GetId().ToString(), state.ToString());
2409  }
2410 
2411  control.Add(std::move(vChecks));
2412 
2413  // Note: this must execute in the same iteration as CheckTxInputs (not
2414  // in a separate loop) in order to detect double spends. However,
2415  // this does not prevent double-spending by duplicated transaction
2416  // inputs in the same transaction (cf. CVE-2018-17144) -- that check is
2417  // done in CheckBlock (CheckRegularTransaction).
2418  SpendCoins(view, tx, blockundo.vtxundo.at(txIndex), pindex->nHeight);
2419  txIndex++;
2420  }
2421 
2422  int64_t nTime3 = GetTimeMicros();
2423  nTimeConnect += nTime3 - nTime2;
2425  " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) "
2426  "[%.2fs (%.2fms/blk)]\n",
2427  (unsigned)block.vtx.size(), MILLI * (nTime3 - nTime2),
2428  MILLI * (nTime3 - nTime2) / block.vtx.size(),
2429  nInputs <= 1 ? 0 : MILLI * (nTime3 - nTime2) / (nInputs - 1),
2431 
2432  const Amount blockReward =
2433  nFees + GetBlockSubsidy(pindex->nHeight, consensusParams);
2434  if (block.vtx[0]->GetValueOut() > blockReward) {
2435  LogPrintf("ERROR: ConnectBlock(): coinbase pays too much (actual=%d vs "
2436  "limit=%d)\n",
2437  block.vtx[0]->GetValueOut(), blockReward);
2439  "bad-cb-amount");
2440  }
2441 
2442  if (blockFees) {
2443  *blockFees = nFees;
2444  }
2445 
2446  if (!control.Wait()) {
2448  "blk-bad-inputs", "parallel script check failed");
2449  }
2450 
2451  int64_t nTime4 = GetTimeMicros();
2452  nTimeVerify += nTime4 - nTime2;
2453  LogPrint(
2454  BCLog::BENCH,
2455  " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n",
2456  nInputs - 1, MILLI * (nTime4 - nTime2),
2457  nInputs <= 1 ? 0 : MILLI * (nTime4 - nTime2) / (nInputs - 1),
2459 
2460  if (fJustCheck) {
2461  return true;
2462  }
2463 
2464  if (!m_blockman.WriteUndoDataForBlock(blockundo, state, *pindex)) {
2465  return false;
2466  }
2467 
2468  if (!pindex->IsValid(BlockValidity::SCRIPTS)) {
2470  m_blockman.m_dirty_blockindex.insert(pindex);
2471  }
2472 
2473  // add this block to the view's block chain
2474  view.SetBestBlock(pindex->GetBlockHash());
2475 
2476  int64_t nTime5 = GetTimeMicros();
2477  nTimeIndex += nTime5 - nTime4;
2478  LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n",
2479  MILLI * (nTime5 - nTime4), nTimeIndex * MICRO,
2481 
2482  TRACE6(validation, block_connected, block_hash.data(), pindex->nHeight,
2483  block.vtx.size(), nInputs, nSigChecksRet,
2484  // in microseconds (µs)
2485  nTime5 - nTimeStart);
2486 
2487  return true;
2488 }
2489 
2490 CoinsCacheSizeState Chainstate::GetCoinsCacheSizeState() {
2492  return this->GetCoinsCacheSizeState(m_coinstip_cache_size_bytes,
2494  : 0);
2495 }
2496 
2498 Chainstate::GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes,
2499  size_t max_mempool_size_bytes) {
2501  int64_t nMempoolUsage = m_mempool ? m_mempool->DynamicMemoryUsage() : 0;
2502  int64_t cacheSize = CoinsTip().DynamicMemoryUsage();
2503  int64_t nTotalSpace =
2504  max_coins_cache_size_bytes +
2505  std::max<int64_t>(int64_t(max_mempool_size_bytes) - nMempoolUsage, 0);
2506 
2508  static constexpr int64_t MAX_BLOCK_COINSDB_USAGE_BYTES =
2509  10 * 1024 * 1024; // 10MB
2510  int64_t large_threshold = std::max(
2511  (9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE_BYTES);
2512 
2513  if (cacheSize > nTotalSpace) {
2514  LogPrintf("Cache size (%s) exceeds total space (%s)\n", cacheSize,
2515  nTotalSpace);
2517  } else if (cacheSize > large_threshold) {
2519  }
2520  return CoinsCacheSizeState::OK;
2521 }
2522 
2524  FlushStateMode mode, int nManualPruneHeight) {
2525  LOCK(cs_main);
2526  assert(this->CanFlushToDisk());
2527  std::set<int> setFilesToPrune;
2528  bool full_flush_completed = false;
2529 
2530  const size_t coins_count = CoinsTip().GetCacheSize();
2531  const size_t coins_mem_usage = CoinsTip().DynamicMemoryUsage();
2532 
2533  try {
2534  {
2535  bool fFlushForPrune = false;
2536  bool fDoFullFlush = false;
2537 
2538  CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
2540  if (m_blockman.IsPruneMode() &&
2541  (m_blockman.m_check_for_pruning || nManualPruneHeight > 0) &&
2542  !fReindex) {
2543  // Make sure we don't prune any of the prune locks bestblocks.
2544  // Pruning is height-based.
2545  int last_prune{m_chain.Height()};
2546  // prune lock that actually was the limiting factor, only used
2547  // for logging
2548  std::optional<std::string> limiting_lock;
2549 
2550  for (const auto &prune_lock : m_blockman.m_prune_locks) {
2551  if (prune_lock.second.height_first ==
2552  std::numeric_limits<int>::max()) {
2553  continue;
2554  }
2555  // Remove the buffer and one additional block here to get
2556  // actual height that is outside of the buffer
2557  const int lock_height{prune_lock.second.height_first -
2558  PRUNE_LOCK_BUFFER - 1};
2559  last_prune = std::max(1, std::min(last_prune, lock_height));
2560  if (last_prune == lock_height) {
2561  limiting_lock = prune_lock.first;
2562  }
2563  }
2564 
2565  if (limiting_lock) {
2566  LogPrint(BCLog::PRUNE, "%s limited pruning to height %d\n",
2567  limiting_lock.value(), last_prune);
2568  }
2569 
2570  if (nManualPruneHeight > 0) {
2572  "find files to prune (manual)", BCLog::BENCH);
2574  setFilesToPrune,
2575  std::min(last_prune, nManualPruneHeight),
2576  m_chain.Height());
2577  } else {
2578  LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune",
2579  BCLog::BENCH);
2581  setFilesToPrune,
2583  m_chain.Height(), last_prune, IsInitialBlockDownload());
2585  }
2586  if (!setFilesToPrune.empty()) {
2587  fFlushForPrune = true;
2588  if (!m_blockman.m_have_pruned) {
2589  m_blockman.m_block_tree_db->WriteFlag(
2590  "prunedblockfiles", true);
2591  m_blockman.m_have_pruned = true;
2592  }
2593  }
2594  }
2595  const auto nNow = GetTime<std::chrono::microseconds>();
2596  // Avoid writing/flushing immediately after startup.
2597  if (m_last_write.count() == 0) {
2598  m_last_write = nNow;
2599  }
2600  if (m_last_flush.count() == 0) {
2601  m_last_flush = nNow;
2602  }
2603  // The cache is large and we're within 10% and 10 MiB of the limit,
2604  // but we have time now (not in the middle of a block processing).
2605  bool fCacheLarge = mode == FlushStateMode::PERIODIC &&
2606  cache_state >= CoinsCacheSizeState::LARGE;
2607  // The cache is over the limit, we have to write now.
2608  bool fCacheCritical = mode == FlushStateMode::IF_NEEDED &&
2609  cache_state >= CoinsCacheSizeState::CRITICAL;
2610  // It's been a while since we wrote the block index to disk. Do this
2611  // frequently, so we don't need to redownload after a crash.
2612  bool fPeriodicWrite = mode == FlushStateMode::PERIODIC &&
2614  // It's been very long since we flushed the cache. Do this
2615  // infrequently, to optimize cache usage.
2616  bool fPeriodicFlush = mode == FlushStateMode::PERIODIC &&
2618  // Combine all conditions that result in a full cache flush.
2619  fDoFullFlush = (mode == FlushStateMode::ALWAYS) || fCacheLarge ||
2620  fCacheCritical || fPeriodicFlush || fFlushForPrune;
2621  // Write blocks and block index to disk.
2622  if (fDoFullFlush || fPeriodicWrite) {
2623  // Ensure we can write block index
2625  return AbortNode(state, "Disk space is too low!",
2626  _("Disk space is too low!"));
2627  }
2628 
2629  {
2631  "write block and undo data to disk", BCLog::BENCH);
2632 
2633  // First make sure all block and undo data is flushed to
2634  // disk.
2636  }
2637  // Then update all block file information (which may refer to
2638  // block and undo files).
2639  {
2640  LOG_TIME_MILLIS_WITH_CATEGORY("write block index to disk",
2641  BCLog::BENCH);
2642 
2643  if (!m_blockman.WriteBlockIndexDB()) {
2644  return AbortNode(
2645  state, "Failed to write to block index database");
2646  }
2647  }
2648 
2649  // Finally remove any pruned files
2650  if (fFlushForPrune) {
2651  LOG_TIME_MILLIS_WITH_CATEGORY("unlink pruned files",
2652  BCLog::BENCH);
2653 
2654  m_blockman.UnlinkPrunedFiles(setFilesToPrune);
2655  }
2656  m_last_write = nNow;
2657  }
2658  // Flush best chain related state. This can only be done if the
2659  // blocks / block index write was also done.
2660  if (fDoFullFlush && !CoinsTip().GetBestBlock().IsNull()) {
2662  strprintf("write coins cache to disk (%d coins, %.2fkB)",
2663  coins_count, coins_mem_usage / 1000),
2664  BCLog::BENCH);
2665 
2666  // Typical Coin structures on disk are around 48 bytes in size.
2667  // Pushing a new one to the database can cause it to be written
2668  // twice (once in the log, and once in the tables). This is
2669  // already an overestimation, as most will delete an existing
2670  // entry or overwrite one. Still, use a conservative safety
2671  // factor of 2.
2673  48 * 2 * 2 * CoinsTip().GetCacheSize())) {
2674  return AbortNode(state, "Disk space is too low!",
2675  _("Disk space is too low!"));
2676  }
2677 
2678  // Flush the chainstate (which may refer to block index
2679  // entries).
2680  if (!CoinsTip().Flush()) {
2681  return AbortNode(state, "Failed to write to coin database");
2682  }
2683  m_last_flush = nNow;
2684  full_flush_completed = true;
2685  }
2686 
2687  TRACE5(utxocache, flush,
2688  // in microseconds (µs)
2689  GetTimeMicros() - nNow.count(), uint32_t(mode), coins_count,
2690  uint64_t(coins_mem_usage), fFlushForPrune);
2691  }
2692 
2693  if (full_flush_completed) {
2694  // Update best block in wallet (so we can detect restored wallets).
2696  }
2697  } catch (const std::runtime_error &e) {
2698  return AbortNode(state, std::string("System error while flushing: ") +
2699  e.what());
2700  }
2701  return true;
2702 }
2703 
2705  BlockValidationState state;
2706  if (!this->FlushStateToDisk(state, FlushStateMode::ALWAYS)) {
2707  LogPrintf("%s: failed to flush state (%s)\n", __func__,
2708  state.ToString());
2709  }
2710 }
2711 
2713  BlockValidationState state;
2715  if (!this->FlushStateToDisk(state, FlushStateMode::NONE)) {
2716  LogPrintf("%s: failed to flush state (%s)\n", __func__,
2717  state.ToString());
2718  }
2719 }
2720 
2721 static void UpdateTipLog(const CCoinsViewCache &coins_tip,
2722  const CBlockIndex *tip, const CChainParams &params,
2723  const std::string &func_name,
2724  const std::string &prefix)
2727  LogPrintf("%s%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%ld "
2728  "date='%s' progress=%f cache=%.1fMiB(%utxo)\n",
2729  prefix, func_name, tip->GetBlockHash().ToString(), tip->nHeight,
2730  tip->nVersion, log(tip->nChainWork.getdouble()) / log(2.0),
2731  tip->GetChainTxCount(),
2733  GuessVerificationProgress(params.TxData(), tip),
2734  coins_tip.DynamicMemoryUsage() * (1.0 / (1 << 20)),
2735  coins_tip.GetCacheSize());
2736 }
2737 
2738 void Chainstate::UpdateTip(const CBlockIndex *pindexNew) {
2740  const auto &coins_tip = CoinsTip();
2741 
2742  const CChainParams &params{m_chainman.GetParams()};
2743 
2744  // The remainder of the function isn't relevant if we are not acting on
2745  // the active chainstate, so return if need be.
2746  if (this != &m_chainman.ActiveChainstate()) {
2747  // Only log every so often so that we don't bury log messages at the
2748  // tip.
2749  constexpr int BACKGROUND_LOG_INTERVAL = 2000;
2750  if (pindexNew->nHeight % BACKGROUND_LOG_INTERVAL == 0) {
2751  UpdateTipLog(coins_tip, pindexNew, params, __func__,
2752  "[background validation] ");
2753  }
2754  return;
2755  }
2756 
2757  // New best block
2758  if (m_mempool) {
2760  }
2761 
2762  {
2764  g_best_block = pindexNew;
2765  g_best_block_cv.notify_all();
2766  }
2767 
2768  UpdateTipLog(coins_tip, pindexNew, params, __func__, "");
2769 }
2770 
2783  DisconnectedBlockTransactions *disconnectpool) {
2785  if (m_mempool) {
2787  }
2788 
2789  CBlockIndex *pindexDelete = m_chain.Tip();
2790 
2791  assert(pindexDelete);
2792  assert(pindexDelete->pprev);
2793 
2794  // Read block from disk.
2795  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2796  CBlock &block = *pblock;
2797  if (!m_blockman.ReadBlockFromDisk(block, *pindexDelete)) {
2798  return error("DisconnectTip(): Failed to read block");
2799  }
2800 
2801  // Apply the block atomically to the chain state.
2802  int64_t nStart = GetTimeMicros();
2803  {
2804  CCoinsViewCache view(&CoinsTip());
2805  assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2806  if (DisconnectBlock(block, pindexDelete, view) !=
2808  return error("DisconnectTip(): DisconnectBlock %s failed",
2809  pindexDelete->GetBlockHash().ToString());
2810  }
2811 
2812  bool flushed = view.Flush();
2813  assert(flushed);
2814  }
2815 
2816  LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n",
2817  (GetTimeMicros() - nStart) * MILLI);
2818 
2819  {
2820  // Prune locks that began at or after the tip should be moved backward
2821  // so they get a chance to reorg
2822  const int max_height_first{pindexDelete->nHeight - 1};
2823  for (auto &prune_lock : m_blockman.m_prune_locks) {
2824  if (prune_lock.second.height_first <= max_height_first) {
2825  continue;
2826  }
2827 
2828  prune_lock.second.height_first = max_height_first;
2829  LogPrint(BCLog::PRUNE, "%s prune lock moved back to %d\n",
2830  prune_lock.first, max_height_first);
2831  }
2832  }
2833 
2834  // Write the chain state to disk, if necessary.
2836  return false;
2837  }
2838 
2839  if (m_mempool) {
2840  // If this block is deactivating a fork, we move all mempool
2841  // transactions in front of disconnectpool for reprocessing in a future
2842  // updateMempoolForReorg call
2843  if (pindexDelete->pprev != nullptr &&
2844  GetNextBlockScriptFlags(pindexDelete, m_chainman) !=
2845  GetNextBlockScriptFlags(pindexDelete->pprev, m_chainman)) {
2847  "Disconnecting mempool due to rewind of upgrade block\n");
2848  if (disconnectpool) {
2849  disconnectpool->importMempool(*m_mempool);
2850  }
2851  m_mempool->clear();
2852  }
2853 
2854  if (disconnectpool) {
2855  disconnectpool->addForBlock(block.vtx, *m_mempool);
2856  }
2857  }
2858 
2859  m_chain.SetTip(*pindexDelete->pprev);
2860 
2861  UpdateTip(pindexDelete->pprev);
2862  // Let wallets know transactions went from 1-confirmed to
2863  // 0-confirmed or conflicted:
2864  GetMainSignals().BlockDisconnected(pblock, pindexDelete);
2865  return true;
2866 }
2867 
2868 static int64_t nTimeReadFromDisk = 0;
2869 static int64_t nTimeConnectTotal = 0;
2870 static int64_t nTimeFlush = 0;
2871 static int64_t nTimeChainState = 0;
2872 static int64_t nTimePostConnect = 0;
2873 
2875  CBlockIndex *pindex = nullptr;
2876  std::shared_ptr<const CBlock> pblock;
2878 };
2879 
2888 private:
2889  std::vector<PerBlockConnectTrace> blocksConnected;
2890 
2891 public:
2892  explicit ConnectTrace() : blocksConnected(1) {}
2893 
2895  std::shared_ptr<const CBlock> pblock) {
2896  assert(!blocksConnected.back().pindex);
2897  assert(pindex);
2898  assert(pblock);
2899  blocksConnected.back().pindex = pindex;
2900  blocksConnected.back().pblock = std::move(pblock);
2901  blocksConnected.emplace_back();
2902  }
2903 
2904  std::vector<PerBlockConnectTrace> &GetBlocksConnected() {
2905  // We always keep one extra block at the end of our list because blocks
2906  // are added after all the conflicted transactions have been filled in.
2907  // Thus, the last entry should always be an empty one waiting for the
2908  // transactions from the next block. We pop the last entry here to make
2909  // sure the list we return is sane.
2910  assert(!blocksConnected.back().pindex);
2911  blocksConnected.pop_back();
2912  return blocksConnected;
2913  }
2914 };
2915 
2923  BlockPolicyValidationState &blockPolicyState,
2924  CBlockIndex *pindexNew,
2925  const std::shared_ptr<const CBlock> &pblock,
2926  ConnectTrace &connectTrace,
2927  DisconnectedBlockTransactions &disconnectpool,
2928  const avalanche::Processor *const avalanche) {
2930  if (m_mempool) {
2932  }
2933 
2934  const Consensus::Params &consensusParams = m_chainman.GetConsensus();
2935 
2936  assert(pindexNew->pprev == m_chain.Tip());
2937  // Read block from disk.
2938  int64_t nTime1 = GetTimeMicros();
2939  std::shared_ptr<const CBlock> pthisBlock;
2940  if (!pblock) {
2941  std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2942  if (!m_blockman.ReadBlockFromDisk(*pblockNew, *pindexNew)) {
2943  return AbortNode(state, "Failed to read block");
2944  }
2945  pthisBlock = pblockNew;
2946  } else {
2947  pthisBlock = pblock;
2948  }
2949 
2950  const CBlock &blockConnecting = *pthisBlock;
2951 
2952  // Apply the block atomically to the chain state.
2953  int64_t nTime2 = GetTimeMicros();
2954  nTimeReadFromDisk += nTime2 - nTime1;
2955  int64_t nTime3;
2956  LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n",
2957  (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
2958  {
2959  Amount blockFees{Amount::zero()};
2960  CCoinsViewCache view(&CoinsTip());
2961  bool rv = ConnectBlock(blockConnecting, state, pindexNew, view,
2963  &blockFees);
2964  GetMainSignals().BlockChecked(blockConnecting, state);
2965  if (!rv) {
2966  if (state.IsInvalid()) {
2967  InvalidBlockFound(pindexNew, state);
2968  }
2969 
2970  return error("%s: ConnectBlock %s failed, %s", __func__,
2971  pindexNew->GetBlockHash().ToString(),
2972  state.ToString());
2973  }
2974 
2986  const BlockHash blockhash = pindexNew->GetBlockHash();
2987  if (!IsInitialBlockDownload() &&
2990 
2991  const Amount blockReward =
2992  blockFees +
2993  GetBlockSubsidy(pindexNew->nHeight, consensusParams);
2994 
2995  std::vector<std::unique_ptr<ParkingPolicy>> parkingPolicies;
2996  parkingPolicies.emplace_back(std::make_unique<MinerFundPolicy>(
2997  consensusParams, *pindexNew, blockConnecting, blockReward));
2998 
2999  if (avalanche) {
3000  parkingPolicies.emplace_back(
3001  std::make_unique<StakingRewardsPolicy>(
3002  *avalanche, consensusParams, *pindexNew,
3003  blockConnecting, blockReward));
3004 
3005  if (m_mempool) {
3006  parkingPolicies.emplace_back(
3007  std::make_unique<PreConsensusPolicy>(
3008  *pindexNew, blockConnecting, m_mempool));
3009  }
3010  }
3011 
3012  // If any block policy is violated, bail on the first one found
3013  if (std::find_if_not(parkingPolicies.begin(), parkingPolicies.end(),
3014  [&](const auto &policy) {
3015  bool ret = (*policy)(blockPolicyState);
3016  if (!ret) {
3017  LogPrintf(
3018  "Park block because it "
3019  "violated a block policy: %s\n",
3020  blockPolicyState.ToString());
3021  }
3022  return ret;
3023  }) != parkingPolicies.end()) {
3024  pindexNew->nStatus = pindexNew->nStatus.withParked();
3025  m_blockman.m_dirty_blockindex.insert(pindexNew);
3026  return false;
3027  }
3028  }
3029 
3030  nTime3 = GetTimeMicros();
3031  nTimeConnectTotal += nTime3 - nTime2;
3032  assert(nBlocksTotal > 0);
3034  " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n",
3035  (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO,
3037  bool flushed = view.Flush();
3038  assert(flushed);
3039  }
3040 
3041  int64_t nTime4 = GetTimeMicros();
3042  nTimeFlush += nTime4 - nTime3;
3043  LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n",
3044  (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO,
3046 
3047  // Write the chain state to disk, if necessary.
3048  if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
3049  return false;
3050  }
3051 
3052  int64_t nTime5 = GetTimeMicros();
3053  nTimeChainState += nTime5 - nTime4;
3055  " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n",
3056  (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO,
3058 
3059  // Remove conflicting transactions from the mempool;
3060  if (m_mempool) {
3061  disconnectpool.removeForBlock(blockConnecting.vtx, *m_mempool);
3062 
3063  // If this block is activating a fork, we move all mempool transactions
3064  // in front of disconnectpool for reprocessing in a future
3065  // updateMempoolForReorg call
3066  if (pindexNew->pprev != nullptr &&
3067  GetNextBlockScriptFlags(pindexNew, m_chainman) !=
3068  GetNextBlockScriptFlags(pindexNew->pprev, m_chainman)) {
3069  LogPrint(
3071  "Disconnecting mempool due to acceptance of upgrade block\n");
3072  disconnectpool.importMempool(*m_mempool);
3073  }
3074  }
3075 
3076  // Update m_chain & related variables.
3077  m_chain.SetTip(*pindexNew);
3078  UpdateTip(pindexNew);
3079 
3080  int64_t nTime6 = GetTimeMicros();
3081  nTimePostConnect += nTime6 - nTime5;
3082  nTimeTotal += nTime6 - nTime1;
3084  " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n",
3085  (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO,
3087  LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n",
3088  (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO,
3090 
3091  // If we are the background validation chainstate, check to see if we are
3092  // done validating the snapshot (i.e. our tip has reached the snapshot's
3093  // base block).
3094  if (this != &m_chainman.ActiveChainstate()) {
3095  // This call may set `m_disabled`, which is referenced immediately
3096  // afterwards in ActivateBestChain, so that we stop connecting blocks
3097  // past the snapshot base.
3098  m_chainman.MaybeCompleteSnapshotValidation();
3099  }
3100 
3101  connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
3102  return true;
3103 }
3104 
3110  std::vector<const CBlockIndex *> &blocksToReconcile, bool fAutoUnpark) {
3112  do {
3113  CBlockIndex *pindexNew = nullptr;
3114 
3115  // Find the best candidate header.
3116  {
3117  std::set<CBlockIndex *, CBlockIndexWorkComparator>::reverse_iterator
3118  it = setBlockIndexCandidates.rbegin();
3119  if (it == setBlockIndexCandidates.rend()) {
3120  return nullptr;
3121  }
3122  pindexNew = *it;
3123  }
3124 
3125  // If this block will cause an avalanche finalized block to be reorged,
3126  // then we park it.
3127  {
3129  if (m_avalancheFinalizedBlockIndex &&
3130  !AreOnTheSameFork(pindexNew, m_avalancheFinalizedBlockIndex)) {
3131  LogPrintf("Park block %s because it forks prior to the "
3132  "avalanche finalized chaintip.\n",
3133  pindexNew->GetBlockHash().ToString());
3134  pindexNew->nStatus = pindexNew->nStatus.withParked();
3135  m_blockman.m_dirty_blockindex.insert(pindexNew);
3136  }
3137  }
3138 
3139  const CBlockIndex *pindexFork = m_chain.FindFork(pindexNew);
3140 
3141  // Check whether all blocks on the path between the currently active
3142  // chain and the candidate are valid. Just going until the active chain
3143  // is an optimization, as we know all blocks in it are valid already.
3144  CBlockIndex *pindexTest = pindexNew;
3145  bool hasValidAncestor = true;
3146  while (hasValidAncestor && pindexTest && pindexTest != pindexFork) {
3147  assert(pindexTest->HaveTxsDownloaded() || pindexTest->nHeight == 0);
3148 
3149  // If this is a parked chain, but it has enough PoW, clear the park
3150  // state.
3151  bool fParkedChain = pindexTest->nStatus.isOnParkedChain();
3152  if (fAutoUnpark && fParkedChain) {
3153  const CBlockIndex *pindexTip = m_chain.Tip();
3154 
3155  // During initialization, pindexTip and/or pindexFork may be
3156  // null. In this case, we just ignore the fact that the chain is
3157  // parked.
3158  if (!pindexTip || !pindexFork) {
3159  UnparkBlock(pindexTest);
3160  continue;
3161  }
3162 
3163  // A parked chain can be unparked if it has twice as much PoW
3164  // accumulated as the main chain has since the fork block.
3165  CBlockIndex const *pindexExtraPow = pindexTip;
3166  arith_uint256 requiredWork = pindexTip->nChainWork;
3167  switch (pindexTip->nHeight - pindexFork->nHeight) {
3168  // Limit the penality for depth 1, 2 and 3 to half a block
3169  // worth of work to ensure we don't fork accidentally.
3170  case 3:
3171  case 2:
3172  pindexExtraPow = pindexExtraPow->pprev;
3173  // FALLTHROUGH
3174  case 1: {
3175  const arith_uint256 deltaWork =
3176  pindexExtraPow->nChainWork - pindexFork->nChainWork;
3177  requiredWork += (deltaWork >> 1);
3178  break;
3179  }
3180  default:
3181  requiredWork +=
3182  pindexExtraPow->nChainWork - pindexFork->nChainWork;
3183  break;
3184  }
3185 
3186  if (pindexNew->nChainWork > requiredWork) {
3187  // We have enough, clear the parked state.
3188  LogPrintf("Unpark chain up to block %s as it has "
3189  "accumulated enough PoW.\n",
3190  pindexNew->GetBlockHash().ToString());
3191  fParkedChain = false;
3192  UnparkBlock(pindexTest);
3193  }
3194  }
3195 
3196  // Pruned nodes may have entries in setBlockIndexCandidates for
3197  // which block files have been deleted. Remove those as candidates
3198  // for the most work chain if we come across them; we can't switch
3199  // to a chain unless we have all the non-active-chain parent blocks.
3200  bool fInvalidChain = pindexTest->nStatus.isInvalid();
3201  bool fMissingData = !pindexTest->nStatus.hasData();
3202  if (!(fInvalidChain || fParkedChain || fMissingData)) {
3203  // The current block is acceptable, move to the parent, up to
3204  // the fork point.
3205  pindexTest = pindexTest->pprev;
3206  continue;
3207  }
3208 
3209  // Candidate chain is not usable (either invalid or parked or
3210  // missing data)
3211  hasValidAncestor = false;
3212  setBlockIndexCandidates.erase(pindexTest);
3213 
3214  if (fInvalidChain && (m_chainman.m_best_invalid == nullptr ||
3215  pindexNew->nChainWork >
3216  m_chainman.m_best_invalid->nChainWork)) {
3217  m_chainman.m_best_invalid = pindexNew;
3218  }
3219 
3220  if (fParkedChain && (m_chainman.m_best_parked == nullptr ||
3221  pindexNew->nChainWork >
3222  m_chainman.m_best_parked->nChainWork)) {
3223  m_chainman.m_best_parked = pindexNew;
3224  }
3225 
3226  LogPrintf("Considered switching to better tip %s but that chain "
3227  "contains a%s%s%s block.\n",
3228  pindexNew->GetBlockHash().ToString(),
3229  fInvalidChain ? "n invalid" : "",
3230  fParkedChain ? " parked" : "",
3231  fMissingData ? " missing-data" : "");
3232 
3233  CBlockIndex *pindexFailed = pindexNew;
3234  // Remove the entire chain from the set.
3235  while (pindexTest != pindexFailed) {
3236  if (fInvalidChain || fParkedChain) {
3237  pindexFailed->nStatus =
3238  pindexFailed->nStatus.withFailedParent(fInvalidChain)
3239  .withParkedParent(fParkedChain);
3240  } else if (fMissingData) {
3241  // If we're missing data, then add back to
3242  // m_blocks_unlinked, so that if the block arrives in the
3243  // future we can try adding to setBlockIndexCandidates
3244  // again.
3246  std::make_pair(pindexFailed->pprev, pindexFailed));
3247  }
3248  setBlockIndexCandidates.erase(pindexFailed);
3249  pindexFailed = pindexFailed->pprev;
3250  }
3251 
3252  if (fInvalidChain || fParkedChain) {
3253  // We discovered a new chain tip that is either parked or
3254  // invalid, we may want to warn.
3256  }
3257  }
3258 
3259  blocksToReconcile.push_back(pindexNew);
3260 
3261  // We found a candidate that has valid ancestors. This is our guy.
3262  if (hasValidAncestor) {
3263  return pindexNew;
3264  }
3265  } while (true);
3266 }
3267 
3273  // Note that we can't delete the current block itself, as we may need to
3274  // return to it later in case a reorganization to a better block fails.
3275  auto it = setBlockIndexCandidates.begin();
3276  while (it != setBlockIndexCandidates.end() &&
3277  setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) {
3278  setBlockIndexCandidates.erase(it++);
3279  }
3280 
3281  // Either the current tip or a successor of it we're working towards is left
3282  // in setBlockIndexCandidates.
3283  assert(!setBlockIndexCandidates.empty());
3284 }
3285 
3294  BlockValidationState &state, CBlockIndex *pindexMostWork,
3295  const std::shared_ptr<const CBlock> &pblock, bool &fInvalidFound,
3296  ConnectTrace &connectTrace, const avalanche::Processor *const avalanche) {
3298  if (m_mempool) {
3300  }
3301 
3302  const CBlockIndex *pindexOldTip = m_chain.Tip();
3303  const CBlockIndex *pindexFork = m_chain.FindFork(pindexMostWork);
3304 
3305  // Disconnect active blocks which are no longer in the best chain.
3306  bool fBlocksDisconnected = false;
3307  DisconnectedBlockTransactions disconnectpool;
3308  while (m_chain.Tip() && m_chain.Tip() != pindexFork) {
3309  if (!fBlocksDisconnected) {
3310  // Import and clear mempool; we must do this to preserve
3311  // topological ordering in the mempool index. This is ok since
3312  // inserts into the mempool are very fast now in our new
3313  // implementation.
3314  disconnectpool.importMempool(*m_mempool);
3315  }
3316 
3317  if (!DisconnectTip(state, &disconnectpool)) {
3318  // This is likely a fatal error, but keep the mempool consistent,
3319  // just in case. Only remove from the mempool in this case.
3320  if (m_mempool) {
3321  disconnectpool.updateMempoolForReorg(*this, false, *m_mempool);
3322  }
3323 
3324  // If we're unable to disconnect a block during normal operation,
3325  // then that is a failure of our local system -- we should abort
3326  // rather than stay on a less work chain.
3327  AbortNode(state,
3328  "Failed to disconnect block; see debug.log for details");
3329  return false;
3330  }
3331 
3332  fBlocksDisconnected = true;
3333  }
3334 
3335  // Build list of new blocks to connect.
3336  std::vector<CBlockIndex *> vpindexToConnect;
3337  bool fContinue = true;
3338  int nHeight = pindexFork ? pindexFork->nHeight : -1;
3339  while (fContinue && nHeight != pindexMostWork->nHeight) {
3340  // Don't iterate the entire list of potential improvements toward the
3341  // best tip, as we likely only need a few blocks along the way.
3342  int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
3343  vpindexToConnect.clear();
3344  vpindexToConnect.reserve(nTargetHeight - nHeight);
3345  CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
3346  while (pindexIter && pindexIter->nHeight != nHeight) {
3347  vpindexToConnect.push_back(pindexIter);
3348  pindexIter = pindexIter->pprev;
3349  }
3350 
3351  nHeight = nTargetHeight;
3352 
3353  // Connect new blocks.
3354  for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
3355  BlockPolicyValidationState blockPolicyState;
3356  if (!ConnectTip(state, blockPolicyState, pindexConnect,
3357  pindexConnect == pindexMostWork
3358  ? pblock
3359  : std::shared_ptr<const CBlock>(),
3360  connectTrace, disconnectpool, avalanche)) {
3361  if (state.IsInvalid()) {
3362  // The block violates a consensus rule.
3363  if (state.GetResult() !=
3365  InvalidChainFound(vpindexToConnect.back());
3366  }
3367  state = BlockValidationState();
3368  fInvalidFound = true;
3369  fContinue = false;
3370  break;
3371  }
3372 
3373  if (blockPolicyState.IsInvalid()) {
3374  // The block violates a policy rule.
3375  fContinue = false;
3376  break;
3377  }
3378 
3379  // A system error occurred (disk space, database error, ...).
3380  // Make the mempool consistent with the current tip, just in
3381  // case any observers try to use it before shutdown.
3382  if (m_mempool) {
3383  disconnectpool.updateMempoolForReorg(*this, false,
3384  *m_mempool);
3385  }
3386  return false;
3387  } else {
3389  if (!pindexOldTip ||
3390  m_chain.Tip()->nChainWork > pindexOldTip->nChainWork) {
3391  // We're in a better position than we were. Return
3392  // temporarily to release the lock.
3393  fContinue = false;
3394  break;
3395  }
3396  }
3397  }
3398  }
3399 
3400  if (m_mempool) {
3401  if (fBlocksDisconnected || !disconnectpool.isEmpty()) {
3402  // If any blocks were disconnected, we need to update the mempool
3403  // even if disconnectpool is empty. The disconnectpool may also be
3404  // non-empty if the mempool was imported due to new validation rules
3405  // being in effect.
3407  "Updating mempool due to reorganization or "
3408  "rules upgrade/downgrade\n");
3409  disconnectpool.updateMempoolForReorg(*this, true, *m_mempool);
3410  }
3411 
3412  m_mempool->check(this->CoinsTip(), this->m_chain.Height() + 1);
3413  }
3414 
3415  // Callbacks/notifications for a new best chain.
3416  if (fInvalidFound) {
3417  CheckForkWarningConditionsOnNewFork(pindexMostWork);
3418  } else {
3420  }
3421 
3422  return true;
3423 }
3424 
3426  if (!init) {
3428  }
3429  if (::fReindex) {
3431  }
3433 }
3434 
3436  bool fNotify = false;
3437  bool fInitialBlockDownload = false;
3438  static CBlockIndex *pindexHeaderOld = nullptr;
3439  CBlockIndex *pindexHeader = nullptr;
3440  {
3441  LOCK(cs_main);
3442  pindexHeader = chainstate.m_chainman.m_best_header;
3443 
3444  if (pindexHeader != pindexHeaderOld) {
3445  fNotify = true;
3446  fInitialBlockDownload = chainstate.IsInitialBlockDownload();
3447  pindexHeaderOld = pindexHeader;
3448  }
3449  }
3450 
3451  // Send block tip changed notifications without cs_main
3452  if (fNotify) {
3453  chainstate.m_chainman.GetNotifications().headerTip(
3454  GetSynchronizationState(fInitialBlockDownload),
3455  pindexHeader->nHeight, pindexHeader->nTime, false);
3456  }
3457  return fNotify;
3458 }
3459 
3462 
3463  if (GetMainSignals().CallbacksPending() > 10) {
3465  }
3466 }
3467 
3469  std::shared_ptr<const CBlock> pblock,
3471  bool skip_checkblockindex) {
3473 
3474  // Note that while we're often called here from ProcessNewBlock, this is
3475  // far from a guarantee. Things in the P2P/RPC will often end up calling
3476  // us in the middle of ProcessNewBlock - do not assume pblock is set
3477  // sanely for performance or correctness!
3479 
3480  // ABC maintains a fair degree of expensive-to-calculate internal state
3481  // because this function periodically releases cs_main so that it does not
3482  // lock up other threads for too long during large connects - and to allow
3483  // for e.g. the callback queue to drain we use m_chainstate_mutex to enforce
3484  // mutual exclusion so that only one caller may execute this function at a
3485  // time
3487 
3488  // Belt-and-suspenders check that we aren't attempting to advance the
3489  // background chainstate past the snapshot base block.
3490  if (WITH_LOCK(::cs_main, return m_disabled)) {
3491  LogPrintf("m_disabled is set - this chainstate should not be in "
3492  "operation. Please report this as a bug. %s\n",
3493  PACKAGE_BUGREPORT);
3494  return false;
3495  }
3496 
3497  CBlockIndex *pindexMostWork = nullptr;
3498  CBlockIndex *pindexNewTip = nullptr;
3499  int nStopAtHeight = gArgs.GetIntArg("-stopatheight", DEFAULT_STOPATHEIGHT);
3500  do {
3501  // Block until the validation queue drains. This should largely
3502  // never happen in normal operation, however may happen during
3503  // reindex, causing memory blowup if we run too far ahead.
3504  // Note that if a validationinterface callback ends up calling
3505  // ActivateBestChain this may lead to a deadlock! We should
3506  // probably have a DEBUG_LOCKORDER test for this in the future.
3508 
3509  std::vector<const CBlockIndex *> blocksToReconcile;
3510  bool blocks_connected = false;
3511 
3512  const bool fAutoUnpark =
3513  gArgs.GetBoolArg("-automaticunparking", !avalanche);
3514 
3515  {
3516  LOCK(cs_main);
3517  // Lock transaction pool for at least as long as it takes for
3518  // connectTrace to be consumed
3519  LOCK(MempoolMutex());
3520  CBlockIndex *starting_tip = m_chain.Tip();
3521  do {
3522  // We absolutely may not unlock cs_main until we've made forward
3523  // progress (with the exception of shutdown due to hardware
3524  // issues, low disk space, etc).
3525 
3526  // Destructed before cs_main is unlocked
3527  ConnectTrace connectTrace;
3528 
3529  if (pindexMostWork == nullptr) {
3530  pindexMostWork =
3531  FindMostWorkChain(blocksToReconcile, fAutoUnpark);
3532  }
3533 
3534  // Whether we have anything to do at all.
3535  if (pindexMostWork == nullptr ||
3536  pindexMostWork == m_chain.Tip()) {
3537  break;
3538  }
3539 
3540  bool fInvalidFound = false;
3541  std::shared_ptr<const CBlock> nullBlockPtr;
3542  if (!ActivateBestChainStep(
3543  state, pindexMostWork,
3544  pblock && pblock->GetHash() ==
3545  pindexMostWork->GetBlockHash()
3546  ? pblock
3547  : nullBlockPtr,
3548  fInvalidFound, connectTrace, avalanche)) {
3549  // A system error occurred
3550  return false;
3551  }
3552  blocks_connected = true;
3553 
3554  if (fInvalidFound ||
3555  (pindexMostWork && pindexMostWork->nStatus.isParked())) {
3556  // Wipe cache, we may need another branch now.
3557  pindexMostWork = nullptr;
3558  }
3559 
3560  pindexNewTip = m_chain.Tip();
3561  for (const PerBlockConnectTrace &trace :
3562  connectTrace.GetBlocksConnected()) {
3563  assert(trace.pblock && trace.pindex);
3564  GetMainSignals().BlockConnected(trace.pblock, trace.pindex);
3565  }
3566 
3567  // This will have been toggled in
3568  // ActivateBestChainStep -> ConnectTip ->
3569  // MaybeCompleteSnapshotValidation, if at all, so we should
3570  // catch it here.
3571  //
3572  // Break this do-while to ensure we don't advance past the base
3573  // snapshot.
3574  if (m_disabled) {
3575  break;
3576  }
3577  } while (!m_chain.Tip() ||
3578  (starting_tip && CBlockIndexWorkComparator()(
3579  m_chain.Tip(), starting_tip)));
3580 
3581  // Check the index once we're done with the above loop, since
3582  // we're going to release cs_main soon. If the index is in a bad
3583  // state now, then it's better to know immediately rather than
3584  // randomly have it cause a problem in a race.
3585  if (!skip_checkblockindex) {
3586  CheckBlockIndex();
3587  }
3588 
3589  if (blocks_connected) {
3590  const CBlockIndex *pindexFork = m_chain.FindFork(starting_tip);
3591  bool fInitialDownload = IsInitialBlockDownload();
3592 
3593  // Notify external listeners about the new tip.
3594  // Enqueue while holding cs_main to ensure that UpdatedBlockTip
3595  // is called in the order in which blocks are connected
3596  if (pindexFork != pindexNewTip) {
3597  // Notify ValidationInterface subscribers
3598  GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork,
3599  fInitialDownload);
3600 
3601  // Always notify the UI if a new block tip was connected
3603  GetSynchronizationState(fInitialDownload),
3604  *pindexNewTip);
3605  }
3606  }
3607  }
3608  // When we reach this point, we switched to a new tip (stored in
3609  // pindexNewTip).
3610  if (avalanche) {
3611  for (const CBlockIndex *pindex : blocksToReconcile) {
3612  avalanche->addToReconcile(pindex);
3613  avalanche->computeStakingReward(pindex);
3614  }
3615  }
3616 
3617  if (!blocks_connected) {
3618  return true;
3619  }
3620 
3621  if (nStopAtHeight && pindexNewTip &&
3622  pindexNewTip->nHeight >= nStopAtHeight) {
3623  StartShutdown();
3624  }
3625 
3626  if (WITH_LOCK(::cs_main, return m_disabled)) {
3627  // Background chainstate has reached the snapshot base block, so
3628  // exit.
3629  break;
3630  }
3631 
3632  // We check shutdown only after giving ActivateBestChainStep a chance to
3633  // run once so that we never shutdown before connecting the genesis
3634  // block during LoadChainTip(). Previously this caused an assert()
3635  // failure during shutdown in such cases as the UTXO DB flushing checks
3636  // that the best block hash is non-null.
3637  if (ShutdownRequested()) {
3638  break;
3639  }
3640  } while (pindexNewTip != pindexMostWork);
3641 
3642  // Write changes periodically to disk, after relay.
3644  return false;
3645  }
3646 
3647  return true;
3648 }
3649 
3654  {
3655  LOCK(cs_main);
3656  if (pindex->nChainWork < m_chain.Tip()->nChainWork) {
3657  // Nothing to do, this block is not at the tip.
3658  return true;
3659  }
3660 
3662  // The chain has been extended since the last call, reset the
3663  // counter.
3665  }
3666 
3668  setBlockIndexCandidates.erase(pindex);
3670  if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
3671  // We can't keep reducing the counter if somebody really wants to
3672  // call preciousblock 2**31-1 times on the same set of tips...
3674  }
3675 
3676  // In case this was parked, unpark it.
3677  UnparkBlock(pindex);
3678 
3679  // Make sure it is added to the candidate list if appropriate.
3680  if (pindex->IsValid(BlockValidity::TRANSACTIONS) &&
3681  pindex->HaveTxsDownloaded()) {
3682  setBlockIndexCandidates.insert(pindex);
3684  }
3685  }
3686 
3687  return ActivateBestChain(state, /*pblock=*/nullptr, avalanche);
3688 }
3689 
3690 namespace {
3691 // Leverage RAII to run a functor at scope end
3692 template <typename Func> struct Defer {
3693  Func func;
3694  Defer(Func &&f) : func(std::move(f)) {}
3695  ~Defer() { func(); }
3696 };
3697 } // namespace
3698 
3700  bool invalidate) {
3701  // Genesis block can't be invalidated or parked
3702  assert(pindex);
3703  if (pindex->nHeight == 0) {
3704  return false;
3705  }
3706 
3707  CBlockIndex *to_mark_failed_or_parked = pindex;
3708  bool pindex_was_in_chain = false;
3709  int disconnected = 0;
3710 
3711  // We do not allow ActivateBestChain() to run while UnwindBlock() is
3712  // running, as that could cause the tip to change while we disconnect
3713  // blocks. (Note for backport of Core PR16849: we acquire
3714  // LOCK(m_chainstate_mutex) in the Park, Invalidate and FinalizeBlock
3715  // functions due to differences in our code)
3717 
3718  // We'll be acquiring and releasing cs_main below, to allow the validation
3719  // callbacks to run. However, we should keep the block index in a
3720  // consistent state as we disconnect blocks -- in particular we need to
3721  // add equal-work blocks to setBlockIndexCandidates as we disconnect.
3722  // To avoid walking the block index repeatedly in search of candidates,
3723  // build a map once so that we can look up candidate blocks by chain
3724  // work as we go.
3725  std::multimap<const arith_uint256, CBlockIndex *> candidate_blocks_by_work;
3726 
3727  {
3728  LOCK(cs_main);
3729  for (auto &entry : m_blockman.m_block_index) {
3730  CBlockIndex *candidate = &entry.second;
3731  // We don't need to put anything in our active chain into the
3732  // multimap, because those candidates will be found and considered
3733  // as we disconnect.
3734  // Instead, consider only non-active-chain blocks that have at
3735  // least as much work as where we expect the new tip to end up.
3736  if (!m_chain.Contains(candidate) &&
3737  !CBlockIndexWorkComparator()(candidate, pindex->pprev) &&
3738  candidate->IsValid(BlockValidity::TRANSACTIONS) &&
3739  candidate->HaveTxsDownloaded()) {
3740  candidate_blocks_by_work.insert(
3741  std::make_pair(candidate->nChainWork, candidate));
3742  }
3743  }
3744  }
3745 
3746  {
3747  LOCK(cs_main);
3748  // Lock for as long as disconnectpool is in scope to make sure
3749  // UpdateMempoolForReorg is called after DisconnectTip without unlocking
3750  // in between
3751  LOCK(MempoolMutex());
3752 
3753  constexpr int maxDisconnectPoolBlocks = 10;
3754  bool ret = false;
3755  DisconnectedBlockTransactions disconnectpool;
3756  // After 10 blocks this becomes nullptr, so that DisconnectTip will
3757  // stop giving us unwound block txs if we are doing a deep unwind.
3758  DisconnectedBlockTransactions *optDisconnectPool = &disconnectpool;
3759 
3760  // Disable thread safety analysis because we can't require m_mempool->cs
3761  // as m_mempool can be null. We keep the runtime analysis though.
3762  Defer deferred([&]() NO_THREAD_SAFETY_ANALYSIS {
3764  if (m_mempool && !disconnectpool.isEmpty()) {
3766  // DisconnectTip will add transactions to disconnectpool.
3767  // When all unwinding is done and we are on a new tip, we must
3768  // add all transactions back to the mempool against the new tip.
3769  disconnectpool.updateMempoolForReorg(*this,
3770  /* fAddToMempool = */ ret,
3771  *m_mempool);
3772  }
3773  });
3774 
3775  // Disconnect (descendants of) pindex, and mark them invalid.
3776  while (true) {
3777  if (ShutdownRequested()) {
3778  break;
3779  }
3780 
3781  // Make sure the queue of validation callbacks doesn't grow
3782  // unboundedly.
3783  // FIXME this commented code is a regression and could cause OOM if
3784  // a very old block is invalidated via the invalidateblock RPC.
3785  // This can be uncommented if the main signals are moved away from
3786  // cs_main or this code is refactored so that cs_main can be
3787  // released at this point.
3788  //
3789  // LimitValidationInterfaceQueue();
3790 
3791  if (!m_chain.Contains(pindex)) {
3792  break;
3793  }
3794 
3795  if (m_mempool && disconnected == 0) {
3796  // On first iteration, we grab all the mempool txs to preserve
3797  // topological ordering. This has the side-effect of temporarily
3798  // clearing the mempool, but we will re-add later in
3799  // updateMempoolForReorg() (above). This technique guarantees
3800  // mempool consistency as well as ensures that our topological
3801  // entry_id index is always correct.
3802  disconnectpool.importMempool(*m_mempool);
3803  }
3804 
3805  pindex_was_in_chain = true;
3806  CBlockIndex *invalid_walk_tip = m_chain.Tip();
3807 
3808  // ActivateBestChain considers blocks already in m_chain
3809  // unconditionally valid already, so force disconnect away from it.
3810 
3811  ret = DisconnectTip(state, optDisconnectPool);
3812  ++disconnected;
3813 
3814  if (optDisconnectPool && disconnected > maxDisconnectPoolBlocks) {
3815  // Stop using the disconnect pool after 10 blocks. After 10
3816  // blocks we no longer add block tx's to the disconnectpool.
3817  // However, when this scope ends we will reconcile what's
3818  // in the pool with the new tip (in the deferred d'tor above).
3819  optDisconnectPool = nullptr;
3820  }
3821 
3822  if (!ret) {
3823  return false;
3824  }
3825 
3826  assert(invalid_walk_tip->pprev == m_chain.Tip());
3827 
3828  // We immediately mark the disconnected blocks as invalid.
3829  // This prevents a case where pruned nodes may fail to
3830  // invalidateblock and be left unable to start as they have no tip
3831  // candidates (as there are no blocks that meet the "have data and
3832  // are not invalid per nStatus" criteria for inclusion in
3833  // setBlockIndexCandidates).
3834 
3835  invalid_walk_tip->nStatus =
3836  invalidate ? invalid_walk_tip->nStatus.withFailed()
3837  : invalid_walk_tip->nStatus.withParked();
3838 
3839  m_blockman.m_dirty_blockindex.insert(invalid_walk_tip);
3840  setBlockIndexCandidates.insert(invalid_walk_tip->pprev);
3841 
3842  if (invalid_walk_tip == to_mark_failed_or_parked->pprev &&
3843  (invalidate ? to_mark_failed_or_parked->nStatus.hasFailed()
3844  : to_mark_failed_or_parked->nStatus.isParked())) {
3845  // We only want to mark the last disconnected block as
3846  // Failed (or Parked); its children need to be FailedParent (or
3847  // ParkedParent) instead.
3848  to_mark_failed_or_parked->nStatus =
3849  (invalidate
3850  ? to_mark_failed_or_parked->nStatus.withFailed(false)
3851  .withFailedParent()
3852  : to_mark_failed_or_parked->nStatus.withParked(false)
3853  .withParkedParent());
3854 
3855  m_blockman.m_dirty_blockindex.insert(to_mark_failed_or_parked);
3856  }
3857 
3858  // Add any equal or more work headers to setBlockIndexCandidates
3859  auto candidate_it = candidate_blocks_by_work.lower_bound(
3860  invalid_walk_tip->pprev->nChainWork);
3861  while (candidate_it != candidate_blocks_by_work.end()) {
3862  if (!CBlockIndexWorkComparator()(candidate_it->second,
3863  invalid_walk_tip->pprev)) {
3864  setBlockIndexCandidates.insert(candidate_it->second);
3865  candidate_it = candidate_blocks_by_work.erase(candidate_it);
3866  } else {
3867  ++candidate_it;
3868  }
3869  }
3870 
3871  // Track the last disconnected block, so we can correct its
3872  // FailedParent (or ParkedParent) status in future iterations, or,
3873  // if it's the last one, call InvalidChainFound on it.
3874  to_mark_failed_or_parked = invalid_walk_tip;
3875  }
3876  }
3877 
3878  CheckBlockIndex();
3879 
3880  {
3881  LOCK(cs_main);
3882  if (m_chain.Contains(to_mark_failed_or_parked)) {
3883  // If the to-be-marked invalid block is in the active chain,
3884  // something is interfering and we can't proceed.
3885  return false;
3886  }
3887 
3888  // Mark pindex (or the last disconnected block) as invalid (or parked),
3889  // even when it never was in the main chain.
3890  to_mark_failed_or_parked->nStatus =
3891  invalidate ? to_mark_failed_or_parked->nStatus.withFailed()
3892  : to_mark_failed_or_parked->nStatus.withParked();
3893  m_blockman.m_dirty_blockindex.insert(to_mark_failed_or_parked);
3894  if (invalidate) {
3895  m_chainman.m_failed_blocks.insert(to_mark_failed_or_parked);
3896  }
3897 
3898  // If any new blocks somehow arrived while we were disconnecting
3899  // (above), then the pre-calculation of what should go into
3900  // setBlockIndexCandidates may have missed entries. This would
3901  // technically be an inconsistency in the block index, but if we clean
3902  // it up here, this should be an essentially unobservable error.
3903  // Loop back over all block index entries and add any missing entries
3904  // to setBlockIndexCandidates.
3905  for (auto &[_, block_index] : m_blockman.m_block_index) {
3906  if (block_index.IsValid(BlockValidity::TRANSACTIONS) &&
3907  block_index.HaveTxsDownloaded() &&
3908  !setBlockIndexCandidates.value_comp()(&block_index,
3909  m_chain.Tip())) {
3910  setBlockIndexCandidates.insert(&block_index);
3911  }
3912  }
3913 
3914  if (invalidate) {
3915  InvalidChainFound(to_mark_failed_or_parked);
3916  }
3917  }
3918 
3919  // Only notify about a new block tip if the active chain was modified.
3920  if (pindex_was_in_chain) {
3923  *to_mark_failed_or_parked->pprev);
3924  }
3925  return true;
3926 }
3927 
3929  CBlockIndex *pindex) {
3932  // See 'Note for backport of Core PR16849' in Chainstate::UnwindBlock
3934 
3935  return UnwindBlock(state, pindex, true);
3936 }
3937 
3941  // See 'Note for backport of Core PR16849' in Chainstate::UnwindBlock
3943 
3944  return UnwindBlock(state, pindex, false);
3945 }
3946 
3947 template <typename F>
3949  CBlockIndex *pindex, F f) {
3950  BlockStatus newStatus = f(pindex->nStatus);
3951  if (pindex->nStatus != newStatus &&
3952  (!pindexBase ||
3953  pindex->GetAncestor(pindexBase->nHeight) == pindexBase)) {
3954  pindex->nStatus = newStatus;
3955  m_blockman.m_dirty_blockindex.insert(pindex);
3956  if (newStatus.isValid()) {
3957  m_chainman.m_failed_blocks.erase(pindex);
3958  }
3959 
3960  if (pindex->IsValid(BlockValidity::TRANSACTIONS) &&
3961  pindex->HaveTxsDownloaded() &&
3962  setBlockIndexCandidates.value_comp()(m_chain.Tip(), pindex)) {
3963  setBlockIndexCandidates.insert(pindex);
3964  }
3965  return true;
3966  }
3967  return false;
3968 }
3969 
3970 template <typename F, typename C, typename AC>
3972  F f, C fChild, AC fAncestorWasChanged) {
3974 
3975  // Update the current block and ancestors; while we're doing this, identify
3976  // which was the deepest ancestor we changed.
3977  CBlockIndex *pindexDeepestChanged = pindex;
3978  for (auto pindexAncestor = pindex; pindexAncestor != nullptr;
3979  pindexAncestor = pindexAncestor->pprev) {
3980  if (UpdateFlagsForBlock(nullptr, pindexAncestor, f)) {
3981  pindexDeepestChanged = pindexAncestor;
3982  }
3983  }
3984 
3985  if (pindexReset &&
3986  pindexReset->GetAncestor(pindexDeepestChanged->nHeight) ==
3987  pindexDeepestChanged) {
3988  // reset pindexReset if it had a modified ancestor.
3989  pindexReset = nullptr;
3990  }
3991 
3992  // Update all blocks under modified blocks.
3993  for (auto &[_, block_index] : m_blockman.m_block_index) {
3994  UpdateFlagsForBlock(pindex, &block_index, fChild);
3995  UpdateFlagsForBlock(pindexDeepestChanged, &block_index,
3996  fAncestorWasChanged);
3997  }
3998 }
3999 
4002 
4003  UpdateFlags(
4004  pindex, m_chainman.m_best_invalid,
4005  [](const BlockStatus status) {
4006  return status.withClearedFailureFlags();
4007  },
4008  [](const BlockStatus status) {
4009  return status.withClearedFailureFlags();
4010  },
4011  [](const BlockStatus status) {
4012  return status.withFailedParent(false);
4013  });
4014 }
4015 
4016 void Chainstate::UnparkBlockImpl(CBlockIndex *pindex, bool fClearChildren) {
4018 
4019  UpdateFlags(
4020  pindex, m_chainman.m_best_parked,
4021  [](const BlockStatus status) {
4022  return status.withClearedParkedFlags();
4023  },
4024  [fClearChildren](const BlockStatus status) {
4025  return fClearChildren ? status.withClearedParkedFlags()
4026  : status.withParkedParent(false);
4027  },
4028  [](const BlockStatus status) {
4029  return status.withParkedParent(false);
4030  });
4031 }
4032 
4034  return UnparkBlockImpl(pindex, true);
4035 }
4036 
4038  return UnparkBlockImpl(pindex, false);
4039 }
4040 
4043  if (!pindex) {
4044  return false;
4045  }
4046 
4047  if (!m_chain.Contains(pindex)) {
4049  "The block to mark finalized by avalanche is not on the "
4050  "active chain: %s\n",
4051  pindex->GetBlockHash().ToString());
4052  return false;
4053  }
4054 
4055  avalanche.cleanupStakingRewards(pindex->nHeight);
4056 
4057  if (IsBlockAvalancheFinalized(pindex)) {
4058  return true;
4059  }
4060 
4061  {
4063  m_avalancheFinalizedBlockIndex = pindex;
4064  }
4065 
4066  GetMainSignals().BlockFinalized(pindex);
4067 
4068  return true;
4069 }
4070 
4073  m_avalancheFinalizedBlockIndex = nullptr;
4074 }
4075 
4078  return pindex && m_avalancheFinalizedBlockIndex &&
4079  m_avalancheFinalizedBlockIndex->GetAncestor(pindex->nHeight) ==
4080  pindex;
4081 }
4082 
4088  CBlockIndex *pindexNew,
4089  const FlatFilePos &pos) {
4090  pindexNew->nTx = block.vtx.size();
4091  pindexNew->nSize = ::GetSerializeSize(block, PROTOCOL_VERSION);
4092  pindexNew->nFile = pos.nFile;
4093  pindexNew->nDataPos = pos.nPos;
4094  pindexNew->nUndoPos = 0;
4095  pindexNew->nStatus = pindexNew->nStatus.withData();
4097  m_blockman.m_dirty_blockindex.insert(pindexNew);
4098 
4099  if (pindexNew->UpdateChainStats()) {
4100  // If pindexNew is the genesis block or all parents are
4101  // BLOCK_VALID_TRANSACTIONS.
4102  std::deque<CBlockIndex *> queue;
4103  queue.push_back(pindexNew);
4104 
4105  // Recursively process any descendant blocks that now may be eligible to
4106  // be connected.
4107  while (!queue.empty()) {
4108  CBlockIndex *pindex = queue.front();
4109  queue.pop_front();
4110  pindex->UpdateChainStats();
4111  if (pindex->nSequenceId == 0) {
4112  // We assign a sequence is when transaction are received to
4113  // prevent a miner from being able to broadcast a block but not
4114  // its content. However, a sequence id may have been set
4115  // manually, for instance via PreciousBlock, in which case, we
4116  // don't need to assign one.
4117  pindex->nSequenceId = nBlockSequenceId++;
4118  }
4119 
4120  if (m_chain.Tip() == nullptr ||
4121  !setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) {
4122  setBlockIndexCandidates.insert(pindex);
4123  }
4124 
4125  std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
4126  std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
4127  range = m_blockman.m_blocks_unlinked.equal_range(pindex);
4128  while (range.first != range.second) {
4129  std::multimap<CBlockIndex *, CBlockIndex *>::iterator it =
4130  range.first;
4131  queue.push_back(it->second);
4132  range.first++;
4133  m_blockman.m_blocks_unlinked.erase(it);
4134  }
4135  }
4136  } else if (pindexNew->pprev &&
4137  pindexNew->pprev->IsValid(BlockValidity::TREE)) {
4139  std::make_pair(pindexNew->pprev, pindexNew));
4140  }
4141 }
4142 
4151 static bool CheckBlockHeader(const CBlockHeader &block,
4152  BlockValidationState &state,
4153  const Consensus::Params &params,
4154  BlockValidationOptions validationOptions) {
4155  // Check proof of work matches claimed amount
4156  if (validationOptions.shouldValidatePoW() &&
4157  !CheckProofOfWork(block.GetHash(), block.nBits, params)) {
4159  "high-hash", "proof of work failed");
4160  }
4161 
4162  return true;
4163 }
4164 
4165 bool CheckBlock(const CBlock &block, BlockValidationState &state,
4166  const Consensus::Params &params,
4167  BlockValidationOptions validationOptions) {
4168  // These are checks that are independent of context.
4169  if (block.fChecked) {
4170  return true;
4171  }
4172 
4173  // Check that the header is valid (particularly PoW). This is mostly
4174  // redundant with the call in AcceptBlockHeader.
4175  if (!CheckBlockHeader(block, state, params, validationOptions)) {
4176  return false;
4177  }
4178 
4179  // Check the merkle root.
4180  if (validationOptions.shouldValidateMerkleRoot()) {
4181  bool mutated;
4182  uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
4183  if (block.hashMerkleRoot != hashMerkleRoot2) {
4185  "bad-txnmrklroot", "hashMerkleRoot mismatch");
4186  }
4187 
4188  // Check for merkle tree malleability (CVE-2012-2459): repeating
4189  // sequences of transactions in a block without affecting the merkle
4190  // root of a block, while still invalidating it.
4191  if (mutated) {
4193  "bad-txns-duplicate", "duplicate transaction");
4194  }
4195  }
4196 
4197  // All potential-corruption validation must be done before we do any
4198  // transaction validation, as otherwise we may mark the header as invalid
4199  // because we receive the wrong transactions for it.
4200 
4201  // First transaction must be coinbase.
4202  if (block.vtx.empty()) {
4204  "bad-cb-missing", "first tx is not coinbase");
4205  }
4206 
4207  // Size limits.
4208  auto nMaxBlockSize = validationOptions.getExcessiveBlockSize();
4209 
4210  // Bail early if there is no way this block is of reasonable size.
4211  if ((block.vtx.size() * MIN_TRANSACTION_SIZE) > nMaxBlockSize) {
4213  "bad-blk-length", "size limits failed");
4214  }
4215 
4216  auto currentBlockSize = ::GetSerializeSize(block, PROTOCOL_VERSION);
4217  if (currentBlockSize > nMaxBlockSize) {
4219  "bad-blk-length", "size limits failed");
4220  }
4221 
4222  // And a valid coinbase.
4223  TxValidationState tx_state;
4224  if (!CheckCoinbase(*block.vtx[0], tx_state)) {
4226  tx_state.GetRejectReason(),
4227  strprintf("Coinbase check failed (txid %s) %s",
4228  block.vtx[0]->GetId().ToString(),
4229  tx_state.GetDebugMessage()));
4230  }
4231 
4232  // Check transactions for regularity, skipping the first. Note that this
4233  // is the first time we check that all after the first are !IsCoinBase.
4234  for (size_t i = 1; i < block.vtx.size(); i++) {
4235  auto *tx = block.vtx[i].get();
4236  if (!CheckRegularTransaction(*tx, tx_state)) {
4237  return state.Invalid(
4239  tx_state.GetRejectReason(),
4240  strprintf("Transaction check failed (txid %s) %s",
4241  tx->GetId().ToString(), tx_state.GetDebugMessage()));
4242  }
4243  }
4244 
4245  if (validationOptions.shouldValidatePoW() &&
4246  validationOptions.shouldValidateMerkleRoot()) {
4247  block.fChecked = true;
4248  }
4249 
4250  return true;
4251 }
4252 
4253 bool HasValidProofOfWork(const std::vector<CBlockHeader> &headers,
4254  const Consensus::Params &consensusParams) {
4255  return std::all_of(headers.cbegin(), headers.cend(),
4256  [&](const auto &header) {
4257  return CheckProofOfWork(
4258  header.GetHash(), header.nBits, consensusParams);
4259  });
4260 }
4261 
4262 arith_uint256 CalculateHeadersWork(const std::vector<CBlockHeader> &headers) {
4263  arith_uint256 total_work{0};
4264  for (const CBlockHeader &header : headers) {
4265  CBlockIndex dummy(header);
4266  total_work += GetBlockProof(dummy);
4267  }
4268  return total_work;
4269 }
4270 
4282  const CBlockHeader &block, BlockValidationState &state,
4283  BlockManager &blockman, ChainstateManager &chainman,
4284  const CBlockIndex *pindexPrev, NodeClock::time_point now,
4285  const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
4288  assert(pindexPrev != nullptr);
4289  const int nHeight = pindexPrev->nHeight + 1;
4290 
4291  const CChainParams &params = chainman.GetParams();
4292 
4293  // Check proof of work
4294  if (block.nBits != GetNextWorkRequired(pindexPrev, &block, params)) {
4295  LogPrintf("bad bits after height: %d\n", pindexPrev->nHeight);
4297  "bad-diffbits", "incorrect proof of work");
4298  }
4299 
4300  // Check against checkpoints
4301  if (chainman.m_options.checkpoints_enabled) {
4302  const CCheckpointData &checkpoints =
4303  test_checkpoints ? test_checkpoints.value() : params.Checkpoints();
4304 
4305  // Check that the block chain matches the known block chain up to a
4306  // checkpoint.
4307  if (!Checkpoints::CheckBlock(checkpoints, nHeight, block.GetHash())) {
4309  "ERROR: %s: rejected by checkpoint lock-in at %d\n",
4310  __func__, nHeight);
4312  "checkpoint mismatch");
4313  }
4314 
4315  // Don't accept any forks from the main chain prior to last checkpoint.
4316  // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's
4317  // in our BlockIndex().
4318 
4319  const CBlockIndex *pcheckpoint =
4320  blockman.GetLastCheckpoint(checkpoints);
4321  if (pcheckpoint && nHeight < pcheckpoint->nHeight) {
4323  "ERROR: %s: forked chain older than last checkpoint "
4324  "(height %d)\n",
4325  __func__, nHeight);
4327  "bad-fork-prior-to-checkpoint");
4328  }
4329  }
4330 
4331  // Check timestamp against prev
4332  if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast()) {
4334  "time-too-old", "block's timestamp is too early");
4335  }
4336 
4337  // Check timestamp
4338  if (block.Time() > now + std::chrono::seconds{MAX_FUTURE_BLOCK_TIME}) {
4340  "time-too-new",
4341  "block timestamp too far in the future");
4342  }
4343 
4344  // Reject blocks with outdated version
4345  if ((block.nVersion < 2 &&
4346  DeploymentActiveAfter(pindexPrev, chainman,
4348  (block.nVersion < 3 &&
4349  DeploymentActiveAfter(pindexPrev, chainman,
4351  (block.nVersion < 4 &&
4352  DeploymentActiveAfter(pindexPrev, chainman,
4354  return state.Invalid(
4356  strprintf("bad-version(0x%08x)", block.nVersion),
4357  strprintf("rejected nVersion=0x%08x block", block.nVersion));
4358  }
4359 
4360  return true;
4361 }
4362 
4364  const CBlockIndex &active_chain_tip, const Consensus::Params &params,
4365  const CTransaction &tx, TxValidationState &state) {
4367 
4368  // ContextualCheckTransactionForCurrentBlock() uses
4369  // active_chain_tip.Height()+1 to evaluate nLockTime because when
4370  // IsFinalTx() is called within AcceptBlock(), the height of the
4371  // block *being* evaluated is what is used. Thus if we want to know if a
4372  // transaction can be part of the *next* block, we need to call
4373  // ContextualCheckTransaction() with one more than
4374  // active_chain_tip.Height().
4375  const int nBlockHeight = active_chain_tip.nHeight + 1;
4376 
4377  // BIP113 will require that time-locked transactions have nLockTime set to
4378  // less than the median time of the previous block they're contained in.
4379  // When the next block is created its previous block will be the current
4380  // chain tip, so we use that to calculate the median time passed to
4381  // ContextualCheckTransaction().
4382  // This time can also be used for consensus upgrades.
4383  const int64_t nMedianTimePast{active_chain_tip.GetMedianTimePast()};
4384 
4385  return ContextualCheckTransaction(params, tx, state, nBlockHeight,
4386  nMedianTimePast);
4387 }
4388 
4396 static bool ContextualCheckBlock(const CBlock &block,
4397  BlockValidationState &state,
4398  const ChainstateManager &chainman,
4399  const CBlockIndex *pindexPrev) {
4400  const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
4401 
4402  // Enforce BIP113 (Median Time Past).
4403  bool enforce_locktime_median_time_past{false};
4404  if (DeploymentActiveAfter(pindexPrev, chainman,
4406  assert(pindexPrev != nullptr);
4407  enforce_locktime_median_time_past = true;
4408  }
4409 
4410  const int64_t nMedianTimePast =
4411  pindexPrev == nullptr ? 0 : pindexPrev->GetMedianTimePast();
4412 
4413  const int64_t nLockTimeCutoff{enforce_locktime_median_time_past
4414  ? nMedianTimePast
4415  : block.GetBlockTime()};
4416 
4417  const Consensus::Params params = chainman.GetConsensus();
4418  const bool fIsMagneticAnomalyEnabled =
4419  IsMagneticAnomalyEnabled(params, pindexPrev);
4420 
4421  // Check transactions:
4422  // - canonical ordering
4423  // - ensure they are finalized
4424  // - check they have the minimum size
4425  const CTransaction *prevTx = nullptr;
4426  for (const auto &ptx : block.vtx) {
4427  const CTransaction &tx = *ptx;
4428  if (fIsMagneticAnomalyEnabled) {
4429  if (prevTx && (tx.GetId() <= prevTx->GetId())) {
4430  if (tx.GetId() == prevTx->GetId()) {
4432  "tx-duplicate",
4433  strprintf("Duplicated transaction %s",
4434  tx.GetId().ToString()));
4435  }
4436 
4437  return state.Invalid(
4439  strprintf("Transaction order is invalid (%s < %s)",
4440  tx.GetId().ToString(),
4441  prevTx->GetId().ToString()));
4442  }
4443 
4444  if (prevTx || !tx.IsCoinBase()) {
4445  prevTx = &tx;
4446  }
4447  }
4448 
4449  TxValidationState tx_state;
4450  if (!ContextualCheckTransaction(params, tx, tx_state, nHeight,
4451  nLockTimeCutoff)) {
4453  tx_state.GetRejectReason(),
4454  tx_state.GetDebugMessage());
4455  }
4456  }
4457 
4458  // Enforce rule that the coinbase starts with serialized block height
4459  if (DeploymentActiveAfter(pindexPrev, chainman,
4461  CScript expect = CScript() << nHeight;
4462  if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
4463  !std::equal(expect.begin(), expect.end(),
4464  block.vtx[0]->vin[0].scriptSig.begin())) {
4466  "bad-cb-height",
4467  "block height mismatch in coinbase");
4468  }
4469  }
4470 
4471  return true;
4472 }
4473 
4480  const CBlockHeader &block, BlockValidationState &state,
4481  CBlockIndex **ppindex, bool min_pow_checked,
4482  const std::optional<CCheckpointData> &test_checkpoints) {
4484  const Config &config = this->GetConfig();
4485  const CChainParams &chainparams = config.GetChainParams();
4486 
4487  // Check for duplicate
4488  BlockHash hash = block.GetHash();
4489  BlockMap::iterator miSelf{m_blockman.m_block_index.find(hash)};
4490  if (hash != chainparams.GetConsensus().hashGenesisBlock) {
4491  if (miSelf != m_blockman.m_block_index.end()) {
4492  // Block header is already known.
4493  CBlockIndex *pindex = &(miSelf->second);
4494  if (ppindex) {
4495  *ppindex = pindex;
4496  }
4497 
4498  if (pindex->nStatus.isInvalid()) {
4499  LogPrint(BCLog::VALIDATION, "%s: block %s is marked invalid\n",
4500  __func__, hash.ToString());
4501  return state.Invalid(
4503  }
4504 
4505  return true;
4506  }
4507 
4508  if (!CheckBlockHeader(block, state, chainparams.GetConsensus(),
4509  BlockValidationOptions(config))) {
4511  "%s: Consensus::CheckBlockHeader: %s, %s\n", __func__,
4512  hash.ToString(), state.ToString());
4513  return false;
4514  }
4515 
4516  // Get prev block index
4517  BlockMap::iterator mi{
4518  m_blockman.m_block_index.find(block.hashPrevBlock)};
4519  if (mi == m_blockman.m_block_index.end()) {
4521  "header %s has prev block not found: %s\n",
4522  hash.ToString(), block.hashPrevBlock.ToString());
4524  "prev-blk-not-found");
4525  }
4526 
4527  CBlockIndex *pindexPrev = &((*mi).second);
4528  assert(pindexPrev);
4529  if (pindexPrev->nStatus.isInvalid()) {
4531  "header %s has prev block invalid: %s\n", hash.ToString(),
4532  block.hashPrevBlock.ToString());
4534  "bad-prevblk");
4535  }
4536 
4538  block, state, m_blockman, *this, pindexPrev,
4539  m_options.adjusted_time_callback(), test_checkpoints)) {
4541  "%s: Consensus::ContextualCheckBlockHeader: %s, %s\n",
4542  __func__, hash.ToString(), state.ToString());
4543  return false;
4544  }
4545 
4546  /* Determine if this block descends from any block which has been found
4547  * invalid (m_failed_blocks), then mark pindexPrev and any blocks
4548  * between them as failed. For example:
4549  *
4550  * D3
4551  * /
4552  * B2 - C2
4553  * / \
4554  * A D2 - E2 - F2
4555  * \
4556  * B1 - C1 - D1 - E1
4557  *
4558  * In the case that we attempted to reorg from E1 to F2, only to find
4559  * C2 to be invalid, we would mark D2, E2, and F2 as BLOCK_FAILED_CHILD
4560  * but NOT D3 (it was not in any of our candidate sets at the time).
4561  *
4562  * In any case D3 will also be marked as BLOCK_FAILED_CHILD at restart
4563  * in LoadBlockIndex.
4564  */
4565  if (!pindexPrev->IsValid(BlockValidity::SCRIPTS)) {
4566  // The above does not mean "invalid": it checks if the previous
4567  // block hasn't been validated up to BlockValidity::SCRIPTS. This is
4568  // a performance optimization, in the common case of adding a new
4569  // block to the tip, we don't need to iterate over the failed blocks
4570  // list.
4571  for (const CBlockIndex *failedit : m_failed_blocks) {
4572  if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
4573  assert(failedit->nStatus.hasFailed());
4574  CBlockIndex *invalid_walk = pindexPrev;
4575  while (invalid_walk != failedit) {
4576  invalid_walk->nStatus =
4577  invalid_walk->nStatus.withFailedParent();
4578  m_blockman.m_dirty_blockindex.insert(invalid_walk);
4579  invalid_walk = invalid_walk->pprev;
4580  }
4582  "header %s has prev block invalid: %s\n",
4583  hash.ToString(), block.hashPrevBlock.ToString());
4584  return state.Invalid(
4586  "bad-prevblk");
4587  }
4588  }
4589  }
4590  }
4591  if (!min_pow_checked) {
4593  "%s: not adding new block header %s, missing anti-dos "
4594  "proof-of-work validation\n",
4595  __func__, hash.ToString());
4597  "too-little-chainwork");
4598  }
4599  CBlockIndex *pindex{m_blockman.AddToBlockIndex(block, m_best_header)};
4600 
4601  if (ppindex) {
4602  *ppindex = pindex;
4603  }
4604 
4605  return true;
4606 }
4607 
4608 // Exposed wrapper for AcceptBlockHeader
4610  const std::vector<CBlockHeader> &headers, bool min_pow_checked,
4611  BlockValidationState &state, const CBlockIndex **ppindex,
4612  const std::optional<CCheckpointData> &test_checkpoints) {
4614  {
4615  LOCK(cs_main);
4616  for (const CBlockHeader &header : headers) {
4617  // Use a temp pindex instead of ppindex to avoid a const_cast
4618  CBlockIndex *pindex = nullptr;
4619  bool accepted = AcceptBlockHeader(
4620  header, state, &pindex, min_pow_checked, test_checkpoints);
4621  ActiveChainstate().CheckBlockIndex();
4622 
4623  if (!accepted) {
4624  return false;
4625  }
4626 
4627  if (ppindex) {
4628  *ppindex = pindex;
4629  }
4630  }
4631  }
4632 
4633  if (NotifyHeaderTip(ActiveChainstate())) {
4634  if (ActiveChainstate().IsInitialBlockDownload() && ppindex &&
4635  *ppindex) {
4636  const CBlockIndex &last_accepted{**ppindex};
4637  const int64_t blocks_left{
4638  (GetTime() - last_accepted.GetBlockTime()) /
4640  const double progress{100.0 * last_accepted.nHeight /
4641  (last_accepted.nHeight + blocks_left)};
4642  LogPrintf("Synchronizing blockheaders, height: %d (~%.2f%%)\n",
4643  last_accepted.nHeight, progress);
4644  }
4645  }
4646  return true;
4647 }
4648 
4649 void ChainstateManager::ReportHeadersPresync(const arith_uint256 &work,
4650  int64_t height,
4651  int64_t timestamp) {
4653  const auto &chainstate = ActiveChainstate();
4654  {
4655  LOCK(cs_main);
4656  // Don't report headers presync progress if we already have a
4657  // post-minchainwork header chain.
4658  // This means we lose reporting for potentially legimate, but unlikely,
4659  // deep reorgs, but prevent attackers that spam low-work headers from
4660  // filling our logs.
4661  if (m_best_header->nChainWork >=
4662  UintToArith256(GetConsensus().nMinimumChainWork)) {
4663  return;
4664  }
4665  // Rate limit headers presync updates to 4 per second, as these are not
4666  // subject to DoS protection.
4667  auto now = Now<SteadyMilliseconds>();
4668  if (now < m_last_presync_update + 250ms) {
4669  return;
4670  }
4671  m_last_presync_update = now;
4672  }
4673  bool initial_download = chainstate.IsInitialBlockDownload();
4675  height, timestamp, /*presync=*/true);
4676  if (initial_download) {
4677  const int64_t blocks_left{(GetTime() - timestamp) /
4679  const double progress{100.0 * height / (height + blocks_left)};
4680  LogPrintf("Pre-synchronizing blockheaders, height: %d (~%.2f%%)\n",
4681  height, progress);
4682  }
4683 }
4684 
4697 bool Chainstate::AcceptBlock(const std::shared_ptr<const CBlock> &pblock,
4698  BlockValidationState &state, bool fRequested,
4699  const FlatFilePos *dbp, bool *fNewBlock,
4700  bool min_pow_checked) {
4702 
4703  const CBlock &block = *pblock;
4704  if (fNewBlock) {
4705  *fNewBlock = false;
4706  }
4707 
4708  CBlockIndex *pindex = nullptr;
4709 
4710  bool accepted_header{
4711  m_chainman.AcceptBlockHeader(block, state, &pindex, min_pow_checked)};
4712  CheckBlockIndex();
4713 
4714  if (!accepted_header) {
4715  return false;
4716  }
4717 
4718  // Try to process all requested blocks that we don't have, but only
4719  // process an unrequested block if it's new and has enough work to
4720  // advance our tip, and isn't too many blocks ahead.
4721  bool fAlreadyHave = pindex->nStatus.hasData();
4722 
4723  // TODO: deal better with return value and error conditions for duplicate
4724  // and unrequested blocks.
4725  if (fAlreadyHave) {
4726  return true;
4727  }
4728 
4729  // Compare block header timestamps and received times of the block and the
4730  // chaintip. If they have the same chain height, use these diffs as a
4731  // tie-breaker, attempting to pick the more honestly-mined block.
4732  int64_t newBlockTimeDiff = std::llabs(pindex->GetReceivedTimeDiff());
4733  int64_t chainTipTimeDiff =
4734  m_chain.Tip() ? std::llabs(m_chain.Tip()->GetReceivedTimeDiff()) : 0;
4735 
4736  bool isSameHeight =
4737  m_chain.Tip() && (pindex->nChainWork == m_chain.Tip()->nChainWork);
4738  if (isSameHeight) {
4739  LogPrintf("Chain tip timestamp-to-received-time difference: hash=%s, "
4740  "diff=%d\n",
4741  m_chain.Tip()->GetBlockHash().ToString(), chainTipTimeDiff);
4742  LogPrintf("New block timestamp-to-received-time difference: hash=%s, "
4743  "diff=%d\n",
4744  pindex->GetBlockHash().ToString(), newBlockTimeDiff);
4745  }
4746 
4747  bool fHasMoreOrSameWork =
4748  (m_chain.Tip() ? pindex->nChainWork >= m_chain.Tip()->nChainWork
4749  : true);
4750 
4751  // Blocks that are too out-of-order needlessly limit the effectiveness of
4752  // pruning, because pruning will not delete block files that contain any
4753  // blocks which are too close in height to the tip. Apply this test
4754  // regardless of whether pruning is enabled; it should generally be safe to
4755  // not process unrequested blocks.
4756  bool fTooFarAhead{pindex->nHeight >
4757  m_chain.Height() + int(MIN_BLOCKS_TO_KEEP)};
4758 
4759  // TODO: Decouple this function from the block download logic by removing
4760  // fRequested
4761  // This requires some new chain data structure to efficiently look up if a
4762  // block is in a chain leading to a candidate for best tip, despite not
4763  // being such a candidate itself.
4764  // Note that this would break the getblockfrompeer RPC
4765 
4766  // If we didn't ask for it:
4767  if (!fRequested) {
4768  // This is a previously-processed block that was pruned.
4769  if (pindex->nTx != 0) {
4770  return true;
4771  }
4772 
4773  // Don't process less-work chains.
4774  if (!fHasMoreOrSameWork) {
4775  return true;
4776  }
4777 
4778  // Block height is too high.
4779  if (fTooFarAhead) {
4780  return true;
4781  }
4782 
4783  // Protect against DoS attacks from low-work chains.
4784  // If our tip is behind, a peer could try to send us
4785  // low-work blocks on a fake chain that we would never
4786  // request; don't process these.
4787  if (pindex->nChainWork < m_chainman.MinimumChainWork()) {
4788  return true;
4789  }
4790  }
4791 
4792  const CChainParams &params{m_chainman.GetParams()};
4793  const Consensus::Params &consensusParams = params.GetConsensus();
4794 
4795  if (!CheckBlock(block, state, consensusParams,
4797  !ContextualCheckBlock(block, state, m_chainman, pindex->pprev)) {
4798  if (state.IsInvalid() &&
4800  pindex->nStatus = pindex->nStatus.withFailed();
4801  m_blockman.m_dirty_blockindex.insert(pindex);
4802  }
4803 
4804  return error("%s: %s (block %s)", __func__, state.ToString(),
4805  block.GetHash().ToString());
4806  }
4807 
4808  // If connecting the new block would require rewinding more than one block
4809  // from the active chain (i.e., a "deep reorg"), then mark the new block as
4810  // parked. If it has enough work then it will be automatically unparked
4811  // later, during FindMostWorkChain. We mark the block as parked at the very
4812  // last minute so we can make sure everything is ready to be reorged if
4813  // needed.
4814  if (gArgs.GetBoolArg("-parkdeepreorg", true)) {
4815  const CBlockIndex *pindexFork = m_chain.FindFork(pindex);
4816  if (pindexFork && pindexFork->nHeight + 1 < m_chain.Height()) {
4817  LogPrintf("Park block %s as it would cause a deep reorg.\n",
4818  pindex->GetBlockHash().ToString());
4819  pindex->nStatus = pindex->nStatus.withParked();
4820  m_blockman.m_dirty_blockindex.insert(pindex);
4821  }
4822  }
4823 
4824  // Header is valid/has work and the merkle tree is good.
4825  // Relay now, but if it does not build on our best tip, let the
4826  // SendMessages loop relay it.
4827  if (!IsInitialBlockDownload() && m_chain.Tip() == pindex->pprev) {
4828  GetMainSignals().NewPoWValidBlock(pindex, pblock);
4829  }
4830 
4831  // Write block to history file
4832  if (fNewBlock) {
4833  *fNewBlock = true;
4834  }
4835  try {
4836  FlatFilePos blockPos{
4837  m_blockman.SaveBlockToDisk(block, pindex->nHeight, m_chain, dbp)};
4838  if (blockPos.IsNull()) {
4839  state.Error(strprintf(
4840  "%s: Failed to find position to write new block to disk",
4841  __func__));
4842  return false;
4843  }
4844  ReceivedBlockTransactions(block, pindex, blockPos);
4845  } catch (const std::runtime_error &e) {
4846  return AbortNode(state, std::string("System error: ") + e.what());
4847  }
4848 
4850 
4851  CheckBlockIndex();
4852 
4853  return true;
4854 }
4855 
4857  const std::shared_ptr<const CBlock> &block, bool force_processing,
4858  bool min_pow_checked, bool *new_block,
4861 
4862  {
4863  if (new_block) {
4864  *new_block = false;
4865  }
4866 
4867  BlockValidationState state;
4868 
4869  // CheckBlock() does not support multi-threaded block validation
4870  // because CBlock::fChecked can cause data race.
4871  // Therefore, the following critical section must include the
4872  // CheckBlock() call as well.
4873  LOCK(cs_main);
4874 
4875  // Skipping AcceptBlock() for CheckBlock() failures means that we will
4876  // never mark a block as invalid if CheckBlock() fails. This is
4877  // protective against consensus failure if there are any unknown form
4878  // s of block malleability that cause CheckBlock() to fail; see e.g.
4879  // CVE-2012-2459 and
4880  // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-February/016697.html.
4881  // Because CheckBlock() is not very expensive, the anti-DoS benefits of
4882  // caching failure (of a definitely-invalid block) are not substantial.
4883  bool ret = CheckBlock(*block, state, this->GetConsensus(),
4885  if (ret) {
4886  // Store to disk
4887  ret = ActiveChainstate().AcceptBlock(block, state, force_processing,
4888  nullptr, new_block,
4889  min_pow_checked);
4890  }
4891 
4892  if (!ret) {
4893  GetMainSignals().BlockChecked(*block, state);
4894  return error("%s: AcceptBlock FAILED (%s)", __func__,
4895  state.ToString());
4896  }
4897  }
4898 
4899  NotifyHeaderTip(ActiveChainstate());
4900 
4901  // Only used to report errors, not invalidity - ignore it
4902  BlockValidationState state;
4903  if (!ActiveChainstate().ActivateBestChain(state, block, avalanche)) {
4904  return error("%s: ActivateBestChain failed (%s)", __func__,
4905  state.ToString());
4906  }
4907 
4908  return true;
4909 }
4910 
4913  bool test_accept) {
4915  Chainstate &active_chainstate = ActiveChainstate();
4916  if (!active_chainstate.GetMempool()) {
4917  TxValidationState state;
4918  state.Invalid(TxValidationResult::TX_NO_MEMPOOL, "no-mempool");
4919  return MempoolAcceptResult::Failure(state);
4920  }
4921  auto result = AcceptToMemoryPool(active_chainstate, tx, GetTime(),
4922  /*bypass_limits=*/false, test_accept);
4923  active_chainstate.GetMempool()->check(
4924  active_chainstate.CoinsTip(), active_chainstate.m_chain.Height() + 1);
4925  return result;
4926 }
4927 
4929  BlockValidationState &state, const CChainParams &params,
4930  Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev,
4931  const std::function<NodeClock::time_point()> &adjusted_time_callback,
4932  BlockValidationOptions validationOptions) {
4934  assert(pindexPrev && pindexPrev == chainstate.m_chain.Tip());
4935  CCoinsViewCache viewNew(&chainstate.CoinsTip());
4936  BlockHash block_hash(block.GetHash());
4937  CBlockIndex indexDummy(block);
4938  indexDummy.pprev = pindexPrev;
4939  indexDummy.nHeight = pindexPrev->nHeight + 1;
4940  indexDummy.phashBlock = &block_hash;
4941 
4942  // NOTE: CheckBlockHeader is called by CheckBlock
4943  if (!ContextualCheckBlockHeader(block, state, chainstate.m_blockman,
4944  chainstate.m_chainman, pindexPrev,
4945  adjusted_time_callback())) {
4946  return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__,
4947  state.ToString());
4948  }
4949 
4950  if (!CheckBlock(block, state, params.GetConsensus(), validationOptions)) {
4951  return error("%s: Consensus::CheckBlock: %s", __func__,
4952  state.ToString());
4953  }
4954 
4955  if (!ContextualCheckBlock(block, state, chainstate.m_chainman,
4956  pindexPrev)) {
4957  return error("%s: Consensus::ContextualCheckBlock: %s", __func__,
4958  state.ToString());
4959  }
4960 
4961  if (!chainstate.ConnectBlock(block, state, &indexDummy, viewNew,
4962  validationOptions, nullptr, true)) {
4963  return false;
4964  }
4965 
4966  assert(state.IsValid());
4967  return true;
4968 }
4969 
4970 /* This function is called from the RPC code for pruneblockchain */
4971 void PruneBlockFilesManual(Chainstate &active_chainstate,
4972  int nManualPruneHeight) {
4973  BlockValidationState state;
4974  if (active_chainstate.FlushStateToDisk(state, FlushStateMode::NONE,
4975  nManualPruneHeight)) {
4976  LogPrintf("%s: failed to flush state (%s)\n", __func__,
4977  state.ToString());
4978  }
4979 }
4980 
4981 void Chainstate::LoadMempool(const fs::path &load_path,
4982  FopenFn mockable_fopen_function) {
4983  if (!m_mempool) {
4984  return;
4985  }
4986  ::LoadMempool(*m_mempool, load_path, *this, mockable_fopen_function);
4988 }
4989 
4992  const CCoinsViewCache &coins_cache = CoinsTip();
4993  // Never called when the coins view is empty
4994  assert(!coins_cache.GetBestBlock().IsNull());
4995  const CBlockIndex *tip = m_chain.Tip();
4996 
4997  if (tip && tip->GetBlockHash() == coins_cache.GetBestBlock()) {
4998  return true;
4999  }
5000 
5001  // Load pointer to end of best chain
5002  CBlockIndex *pindex =
5003  m_blockman.LookupBlockIndex(coins_cache.GetBestBlock());
5004  if (!pindex) {
5005  return false;
5006  }
5007  m_chain.SetTip(*pindex);
5009 
5010  tip = m_chain.Tip();
5011  LogPrintf(
5012  "Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
5013  tip->GetBlockHash().ToString(), m_chain.Height(),
5016  return true;
5017 }
5018 
5020  : m_notifications{notifications} {
5021  m_notifications.progress(_("Verifying blocks…"), 0, false);
5022 }
5023 
5025  m_notifications.progress(bilingual_str{}, 100, false);
5026 }
5027 
5029  CCoinsView &coinsview, int nCheckLevel,
5030  int nCheckDepth) {
5032 
5033  const Config &config = chainstate.m_chainman.GetConfig();
5034  const CChainParams &params = config.GetChainParams();
5035  const Consensus::Params &consensusParams = params.GetConsensus();
5036 
5037  if (chainstate.m_chain.Tip() == nullptr ||
5038  chainstate.m_chain.Tip()->pprev == nullptr) {
5039  return VerifyDBResult::SUCCESS;
5040  }
5041 
5042  // Verify blocks in the best chain
5043  if (nCheckDepth <= 0 || nCheckDepth > chainstate.m_chain.Height()) {
5044  nCheckDepth = chainstate.m_chain.Height();
5045  }
5046 
5047  nCheckLevel = std::max(0, std::min(4, nCheckLevel));
5048  LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth,
5049  nCheckLevel);
5050 
5051  CCoinsViewCache coins(&coinsview);
5052  CBlockIndex *pindex;
5053  CBlockIndex *pindexFailure = nullptr;
5054  int nGoodTransactions = 0;
5055  BlockValidationState state;
5056  int reportDone = 0;
5057  bool skipped_no_block_data{false};
5058  bool skipped_l3_checks{false};
5059  LogPrintf("Verification progress: 0%%\n");
5060 
5061  const bool is_snapshot_cs{!chainstate.m_from_snapshot_blockhash};
5062 
5063  for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev;
5064  pindex = pindex->pprev) {
5065  const int percentageDone = std::max(
5066  1, std::min(99, (int)(((double)(chainstate.m_chain.Height() -
5067  pindex->nHeight)) /
5068  (double)nCheckDepth *
5069  (nCheckLevel >= 4 ? 50 : 100))));
5070  if (reportDone < percentageDone / 10) {
5071  // report every 10% step
5072  LogPrintf("Verification progress: %d%%\n", percentageDone);
5073  reportDone = percentageDone / 10;
5074  }
5075 
5076  m_notifications.progress(_("Verifying blocks…"), percentageDone, false);
5077  if (pindex->nHeight <= chainstate.m_chain.Height() - nCheckDepth) {
5078  break;
5079  }
5080 
5081  if ((chainstate.m_blockman.IsPruneMode() || is_snapshot_cs) &&
5082  !pindex->nStatus.hasData()) {
5083  // If pruning or running under an assumeutxo snapshot, only go
5084  // back as far as we have data.
5085  LogPrintf("VerifyDB(): block verification stopping at height %d "
5086  "(no data). This could be due to pruning or use of an "
5087  "assumeutxo snapshot.\n",
5088  pindex->nHeight);
5089  skipped_no_block_data = true;
5090  break;
5091  }
5092 
5093  CBlock block;
5094 
5095  // check level 0: read from disk
5096  if (!chainstate.m_blockman.ReadBlockFromDisk(block, *pindex)) {
5097  LogPrintf(
5098  "Verification error: ReadBlockFromDisk failed at %d, hash=%s\n",
5099  pindex->nHeight, pindex->GetBlockHash().ToString());
5101  }
5102 
5103  // check level 1: verify block validity
5104  if (nCheckLevel >= 1 && !CheckBlock(block, state, consensusParams,
5105  BlockValidationOptions(config))) {
5106  LogPrintf(
5107  "Verification error: found bad block at %d, hash=%s (%s)\n",
5108  pindex->nHeight, pindex->GetBlockHash().ToString(),
5109  state.ToString());
5111  }
5112 
5113  // check level 2: verify undo validity
5114  if (nCheckLevel >= 2 && pindex) {
5115  CBlockUndo undo;
5116  if (!pindex->GetUndoPos().IsNull()) {
5117  if (!chainstate.m_blockman.UndoReadFromDisk(undo, *pindex)) {
5118  LogPrintf("Verification error: found bad undo data at %d, "
5119  "hash=%s\n",
5120  pindex->nHeight,
5121  pindex->GetBlockHash().ToString());
5123  }
5124  }
5125  }
5126  // check level 3: check for inconsistencies during memory-only
5127  // disconnect of tip blocks
5128  size_t curr_coins_usage = coins.DynamicMemoryUsage() +
5129  chainstate.CoinsTip().DynamicMemoryUsage();
5130 
5131  if (nCheckLevel >= 3) {
5132  if (curr_coins_usage <= chainstate.m_coinstip_cache_size_bytes) {
5133  assert(coins.GetBestBlock() == pindex->GetBlockHash());
5134  DisconnectResult res =
5135  chainstate.DisconnectBlock(block, pindex, coins);
5136  if (res == DisconnectResult::FAILED) {
5137  LogPrintf("Verification error: irrecoverable inconsistency "
5138  "in block data at %d, hash=%s\n",
5139  pindex->nHeight,
5140  pindex->GetBlockHash().ToString());
5142  }
5143  if (res == DisconnectResult::UNCLEAN) {
5144  nGoodTransactions = 0;
5145  pindexFailure = pindex;
5146  } else {
5147  nGoodTransactions += block.vtx.size();
5148  }
5149  } else {
5150  skipped_l3_checks = true;
5151  }
5152  }
5153 
5154  if (ShutdownRequested()) {
5156  }
5157  }
5158 
5159  if (pindexFailure) {
5160  LogPrintf("Verification error: coin database inconsistencies found "
5161  "(last %i blocks, %i good transactions before that)\n",
5162  chainstate.m_chain.Height() - pindexFailure->nHeight + 1,
5163  nGoodTransactions);
5165  }
5166  if (skipped_l3_checks) {
5167  LogPrintf("Skipped verification of level >=3 (insufficient database "
5168  "cache size). Consider increasing -dbcache.\n");
5169  }
5170 
5171  // store block count as we move pindex at check level >= 4
5172  int block_count = chainstate.m_chain.Height() - pindex->nHeight;
5173 
5174  // check level 4: try reconnecting blocks
5175  if (nCheckLevel >= 4 && !skipped_l3_checks) {
5176  while (pindex != chainstate.m_chain.Tip()) {
5177  const int percentageDone = std::max(
5178  1, std::min(99, 100 - int(double(chainstate.m_chain.Height() -
5179  pindex->nHeight) /
5180  double(nCheckDepth) * 50)));
5181  if (reportDone < percentageDone / 10) {
5182  // report every 10% step
5183  LogPrintf("Verification progress: %d%%\n", percentageDone);
5184  reportDone = percentageDone / 10;
5185  }
5186  m_notifications.progress(_("Verifying blocks…"), percentageDone,
5187  false);
5188  pindex = chainstate.m_chain.Next(pindex);
5189  CBlock block;
5190  if (!chainstate.m_blockman.ReadBlockFromDisk(block, *pindex)) {
5191  LogPrintf("Verification error: ReadBlockFromDisk failed at %d, "
5192  "hash=%s\n",
5193  pindex->nHeight, pindex->GetBlockHash().ToString());
5195  }
5196  if (!chainstate.ConnectBlock(block, state, pindex, coins,
5197  BlockValidationOptions(config))) {
5198  LogPrintf("Verification error: found unconnectable block at "
5199  "%d, hash=%s (%s)\n",
5200  pindex->nHeight, pindex->GetBlockHash().ToString(),
5201  state.ToString());
5203  }
5204  if (ShutdownRequested()) {
5206  }
5207  }
5208  }
5209 
5210  LogPrintf("Verification: No coin database inconsistencies in last %i "
5211  "blocks (%i transactions)\n",
5212  block_count, nGoodTransactions);
5213 
5214  if (skipped_l3_checks) {
5216  }
5217  if (skipped_no_block_data) {
5219  }
5220  return VerifyDBResult::SUCCESS;
5221 }
5222 
5228  CCoinsViewCache &view) {
5230  // TODO: merge with ConnectBlock
5231  CBlock block;
5232  if (!m_blockman.ReadBlockFromDisk(block, *pindex)) {
5233  return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s",
5234  pindex->nHeight, pindex->GetBlockHash().ToString());
5235  }
5236 
5237  for (const CTransactionRef &tx : block.vtx) {
5238  // Pass check = true as every addition may be an overwrite.
5239  AddCoins(view, *tx, pindex->nHeight, true);
5240  }
5241 
5242  for (const CTransactionRef &tx : block.vtx) {
5243  if (tx->IsCoinBase()) {
5244  continue;
5245  }
5246 
5247  for (const CTxIn &txin : tx->vin) {
5248  view.SpendCoin(txin.prevout);
5249  }
5250  }
5251 
5252  return true;
5253 }
5254 
5256  LOCK(cs_main);
5257 
5258  CCoinsView &db = this->CoinsDB();
5259  CCoinsViewCache cache(&db);
5260 
5261  std::vector<BlockHash> hashHeads = db.GetHeadBlocks();
5262  if (hashHeads.empty()) {
5263  // We're already in a consistent state.
5264  return true;
5265  }
5266  if (hashHeads.size() != 2) {
5267  return error("ReplayBlocks(): unknown inconsistent state");
5268  }
5269 
5270  m_chainman.GetNotifications().progress(_("Replaying blocks…"), 0, false);
5271  LogPrintf("Replaying blocks\n");
5272 
5273  // Old tip during the interrupted flush.
5274  const CBlockIndex *pindexOld = nullptr;
5275  // New tip during the interrupted flush.
5276  const CBlockIndex *pindexNew;
5277  // Latest block common to both the old and the new tip.
5278  const CBlockIndex *pindexFork = nullptr;
5279 
5280  if (m_blockman.m_block_index.count(hashHeads[0]) == 0) {
5281  return error(
5282  "ReplayBlocks(): reorganization to unknown block requested");
5283  }
5284 
5285  pindexNew = &(m_blockman.m_block_index[hashHeads[0]]);
5286 
5287  if (!hashHeads[1].IsNull()) {
5288  // The old tip is allowed to be 0, indicating it's the first flush.
5289  if (m_blockman.m_block_index.count(hashHeads[1]) == 0) {
5290  return error(
5291  "ReplayBlocks(): reorganization from unknown block requested");
5292  }
5293 
5294  pindexOld = &(m_blockman.m_block_index[hashHeads[1]]);
5295  pindexFork = LastCommonAncestor(pindexOld, pindexNew);
5296  assert(pindexFork != nullptr);
5297  }
5298 
5299  // Rollback along the old branch.
5300  while (pindexOld != pindexFork) {
5301  if (pindexOld->nHeight > 0) {
5302  // Never disconnect the genesis block.
5303  CBlock block;
5304  if (!m_blockman.ReadBlockFromDisk(block, *pindexOld)) {
5305  return error("RollbackBlock(): ReadBlockFromDisk() failed at "
5306  "%d, hash=%s",
5307  pindexOld->nHeight,
5308  pindexOld->GetBlockHash().ToString());
5309  }
5310 
5311  LogPrintf("Rolling back %s (%i)\n",
5312  pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
5313  DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
5314  if (res == DisconnectResult::FAILED) {
5315  return error(
5316  "RollbackBlock(): DisconnectBlock failed at %d, hash=%s",
5317  pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
5318  }
5319 
5320  // If DisconnectResult::UNCLEAN is returned, it means a non-existing
5321  // UTXO was deleted, or an existing UTXO was overwritten. It
5322  // corresponds to cases where the block-to-be-disconnect never had
5323  // all its operations applied to the UTXO set. However, as both
5324  // writing a UTXO and deleting a UTXO are idempotent operations, the
5325  // result is still a version of the UTXO set with the effects of
5326  // that block undone.
5327  }
5328  pindexOld = pindexOld->pprev;
5329  }
5330 
5331  // Roll forward from the forking point to the new tip.
5332  int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
5333  for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight;
5334  ++nHeight) {
5335  const CBlockIndex &pindex{*Assert(pindexNew->GetAncestor(nHeight))};
5336  LogPrintf("Rolling forward %s (%i)\n", pindex.GetBlockHash().ToString(),
5337  nHeight);
5339  _("Replaying blocks…"),
5340  (int)((nHeight - nForkHeight) * 100.0 /
5341  (pindexNew->nHeight - nForkHeight)),
5342  false);
5343  if (!RollforwardBlock(&pindex, cache)) {
5344  return false;
5345  }
5346  }
5347 
5348  cache.SetBestBlock(pindexNew->GetBlockHash());
5349  cache.Flush();
5351  return true;
5352 }
5353 
5354 // May NOT be used after any connections are up as much of the peer-processing
5355 // logic assumes a consistent block index state
5358  nBlockSequenceId = 1;
5359  m_best_fork_tip = nullptr;
5360  m_best_fork_base = nullptr;
5361  setBlockIndexCandidates.clear();
5362 }
5363 
5366  // Load block index from databases
5367  bool needs_init = fReindex;
5368  if (!fReindex) {
5369  bool ret = m_blockman.LoadBlockIndexDB();
5370  if (!ret) {
5371  return false;
5372  }
5373 
5374  m_blockman.ScanAndUnlinkAlreadyPrunedFiles();
5375 
5376  std::vector<CBlockIndex *> vSortedByHeight{
5377  m_blockman.GetAllBlockIndices()};
5378  std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
5380 
5381  // Find start of assumed-valid region.
5382  int first_assumed_valid_height = std::numeric_limits<int>::max();
5383 
5384  for (const CBlockIndex *block : vSortedByHeight) {
5385  if (block->IsAssumedValid()) {
5386  auto chainstates = GetAll();
5387 
5388  // If we encounter an assumed-valid block index entry, ensure
5389  // that we have one chainstate that tolerates assumed-valid
5390  // entries and another that does not (i.e. the background
5391  // validation chainstate), since assumed-valid entries should
5392  // always be pending validation by a fully-validated chainstate.
5393  auto any_chain = [&](auto fnc) {
5394  return std::any_of(chainstates.cbegin(), chainstates.cend(),
5395  fnc);
5396  };
5397  assert(any_chain([](auto chainstate) {
5398  return chainstate->reliesOnAssumedValid();
5399  }));
5400  assert(any_chain([](auto chainstate) {
5401  return !chainstate->reliesOnAssumedValid();
5402  }));
5403 
5404  first_assumed_valid_height = block->nHeight;
5405  LogPrintf("Saw first assumedvalid block at height %d (%s)\n",
5406  first_assumed_valid_height, block->ToString());
5407  break;
5408  }
5409  }
5410 
5411  for (CBlockIndex *pindex : vSortedByHeight) {
5412  if (ShutdownRequested()) {
5413  return false;
5414  }
5415  if (pindex->IsAssumedValid() ||
5417  (pindex->HaveTxsDownloaded() || pindex->pprev == nullptr))) {
5418  // Fill each chainstate's block candidate set. Only add
5419  // assumed-valid blocks to the tip candidate set if the
5420  // chainstate is allowed to rely on assumed-valid blocks.
5421  //
5422  // If all setBlockIndexCandidates contained the assumed-valid
5423  // blocks, the background chainstate's ActivateBestChain() call
5424  // would add assumed-valid blocks to the chain (based on how
5425  // FindMostWorkChain() works). Obviously we don't want this
5426  // since the purpose of the background validation chain is to
5427  // validate assumed-valid blocks.
5428  //
5429  // Note: This is considering all blocks whose height is greater
5430  // or equal to the first assumed-valid block to be assumed-valid
5431  // blocks, and excluding them from the background chainstate's
5432  // setBlockIndexCandidates set. This does mean that some blocks
5433  // which are not technically assumed-valid (later blocks on a
5434  // fork beginning before the first assumed-valid block) might
5435  // not get added to the background chainstate, but this is ok,
5436  // because they will still be attached to the active chainstate
5437  // if they actually contain more work.
5438  //
5439  // Instead of this height-based approach, an earlier attempt was
5440  // made at detecting "holistically" whether the block index
5441  // under consideration relied on an assumed-valid ancestor, but
5442  // this proved to be too slow to be practical.
5443  for (Chainstate *chainstate : GetAll()) {
5444  if (chainstate->reliesOnAssumedValid() ||
5445  pindex->nHeight < first_assumed_valid_height) {
5446  chainstate->setBlockIndexCandidates.insert(pindex);
5447  }
5448  }
5449  }
5450 
5451  if (pindex->nStatus.isInvalid() &&
5452  (!m_best_invalid ||
5453  pindex->nChainWork > m_best_invalid->nChainWork)) {
5454  m_best_invalid = pindex;
5455  }
5456 
5457  if (pindex->nStatus.isOnParkedChain() &&
5458  (!m_best_parked ||
5459  pindex->nChainWork > m_best_parked->nChainWork)) {
5460  m_best_parked = pindex;
5461  }
5462 
5463  if (pindex->IsValid(BlockValidity::TREE) &&
5464  (m_best_header == nullptr ||
5465  CBlockIndexWorkComparator()(m_best_header, pindex))) {
5466  m_best_header = pindex;
5467  }
5468  }
5469 
5470  needs_init = m_blockman.m_block_index.empty();
5471  }
5472 
5473  if (needs_init) {
5474  // Everything here is for *new* reindex/DBs. Thus, though
5475  // LoadBlockIndexDB may have set fReindex if we shut down
5476  // mid-reindex previously, we don't check fReindex and
5477  // instead only check it prior to LoadBlockIndexDB to set
5478  // needs_init.
5479 
5480  LogPrintf("Initializing databases...\n");
5481  }
5482  return true;
5483 }
5484 
5486  LOCK(cs_main);
5487 
5488  const CChainParams &params{m_chainman.GetParams()};
5489 
5490  // Check whether we're already initialized by checking for genesis in
5491  // m_blockman.m_block_index. Note that we can't use m_chain here, since it
5492  // is set based on the coins db, not the block index db, which is the only
5493  // thing loaded at this point.
5494  if (m_blockman.m_block_index.count(params.GenesisBlock().GetHash())) {
5495  return true;
5496  }
5497 
5498  try {
5499  const CBlock &block = params.GenesisBlock();
5500  FlatFilePos blockPos{
5501  m_blockman.SaveBlockToDisk(block, 0, m_chain, nullptr)};
5502  if (blockPos.IsNull()) {
5503  return error("%s: writing genesis block to disk failed", __func__);
5504  }
5505  CBlockIndex *pindex =
5506  m_blockman.AddToBlockIndex(block, m_chainman.m_best_header);
5507  ReceivedBlockTransactions(block, pindex, blockPos);
5508  } catch (const std::runtime_error &e) {
5509  return error("%s: failed to write genesis block: %s", __func__,
5510  e.what());
5511  }
5512 
5513  return true;
5514 }
5515 
5517  FILE *fileIn, FlatFilePos *dbp,
5518  std::multimap<BlockHash, FlatFilePos> *blocks_with_unknown_parent,
5521 
5522  // Either both should be specified (-reindex), or neither (-loadblock).
5523  assert(!dbp == !blocks_with_unknown_parent);
5524 
5525  int64_t nStart = GetTimeMillis();
5526  const CChainParams &params{m_chainman.GetParams()};
5527 
5528  int nLoaded = 0;
5529  try {
5530  // This takes over fileIn and calls fclose() on it in the CBufferedFile
5531  // destructor. Make sure we have at least 2*MAX_TX_SIZE space in there
5532  // so any transaction can fit in the buffer.
5533  CBufferedFile blkdat(fileIn, 2 * MAX_TX_SIZE, MAX_TX_SIZE + 8, SER_DISK,
5534  CLIENT_VERSION);
5535  // nRewind indicates where to resume scanning in case something goes
5536  // wrong, such as a block fails to deserialize.
5537  uint64_t nRewind = blkdat.GetPos();
5538  while (!blkdat.eof()) {
5539  if (ShutdownRequested()) {
5540  return;
5541  }
5542 
5543  blkdat.SetPos(nRewind);
5544  // Start one byte further next time, in case of failure.
5545  nRewind++;
5546  // Remove former limit.
5547  blkdat.SetLimit();
5548  unsigned int nSize = 0;
5549  try {
5550  // Locate a header.
5552  blkdat.FindByte(std::byte(params.DiskMagic()[0]));
5553  nRewind = blkdat.GetPos() + 1;
5554  blkdat >> buf;
5555  if (memcmp(buf, params.DiskMagic().data(),
5557  continue;
5558  }
5559 
5560  // Read size.
5561  blkdat >> nSize;
5562  if (nSize < 80) {
5563  continue;
5564  }
5565  } catch (const std::exception &) {
5566  // No valid block header found; don't complain.
5567  // (this happens at the end of every blk.dat file)
5568  break;
5569  }
5570 
5571  try {
5572  // read block header
5573  const uint64_t nBlockPos{blkdat.GetPos()};
5574  if (dbp) {
5575  dbp->nPos = nBlockPos;
5576  }
5577  blkdat.SetLimit(nBlockPos + nSize);
5578  CBlockHeader header;
5579  blkdat >> header;
5580  const BlockHash hash{header.GetHash()};
5581  // Skip the rest of this block (this may read from disk
5582  // into memory); position to the marker before the next block,
5583  // but it's still possible to rewind to the start of the
5584  // current block (without a disk read).
5585  nRewind = nBlockPos + nSize;
5586  blkdat.SkipTo(nRewind);
5587 
5588  // needs to remain available after the cs_main lock is released
5589  // to avoid duplicate reads from disk
5590  std::shared_ptr<CBlock> pblock{};
5591 
5592  {
5593  LOCK(cs_main);
5594  // detect out of order blocks, and store them for later
5595  if (hash != params.GetConsensus().hashGenesisBlock &&
5597  LogPrint(
5599  "%s: Out of order block %s, parent %s not known\n",
5600  __func__, hash.ToString(),
5601  header.hashPrevBlock.ToString());
5602  if (dbp && blocks_with_unknown_parent) {
5603  blocks_with_unknown_parent->emplace(
5604  header.hashPrevBlock, *dbp);
5605  }
5606  continue;
5607  }
5608 
5609  // process in case the block isn't known yet
5610  const CBlockIndex *pindex =
5612  if (!pindex || !pindex->nStatus.hasData()) {
5613  // This block can be processed immediately; rewind to
5614  // its start, read and deserialize it.
5615  blkdat.SetPos(nBlockPos);
5616  pblock = std::make_shared<CBlock>();
5617  blkdat >> *pblock;
5618  nRewind = blkdat.GetPos();
5619 
5620  BlockValidationState state;
5621  if (AcceptBlock(pblock, state, true, dbp, nullptr,
5622  true)) {
5623  nLoaded++;
5624  }
5625  if (state.IsError()) {
5626  break;
5627  }
5628  } else if (hash != params.GetConsensus().hashGenesisBlock &&
5629  pindex->nHeight % 1000 == 0) {
5630  LogPrint(
5632  "Block Import: already had block %s at height %d\n",
5633  hash.ToString(), pindex->nHeight);
5634  }
5635  }
5636 
5637  // Activate the genesis block so normal node progress can
5638  // continue
5639  if (hash == params.GetConsensus().hashGenesisBlock) {
5640  BlockValidationState state;
5641  if (!ActivateBestChain(state, nullptr, avalanche)) {
5642  break;
5643  }
5644  }
5645 
5646  if (m_blockman.IsPruneMode() && !fReindex && pblock) {
5647  // Must update the tip for pruning to work while importing
5648  // with -loadblock. This is a tradeoff to conserve disk
5649  // space at the expense of time spent updating the tip to be
5650  // able to prune. Otherwise, ActivateBestChain won't be
5651  // called by the import process until after all of the block
5652  // files are loaded. ActivateBestChain can be called by
5653  // concurrent network message processing, but that is not
5654  // reliable for the purpose of pruning while importing.
5655  BlockValidationState state;
5656  if (!ActivateBestChain(state, pblock, avalanche)) {
5658  "failed to activate chain (%s)\n",
5659  state.ToString());
5660  break;
5661  }
5662  }
5663 
5664  NotifyHeaderTip(*this);
5665 
5666  if (!blocks_with_unknown_parent) {
5667  continue;
5668  }
5669 
5670  // Recursively process earlier encountered successors of this
5671  // block
5672  std::deque<BlockHash> queue;
5673  queue.push_back(hash);
5674  while (!queue.empty()) {
5675  BlockHash head = queue.front();
5676  queue.pop_front();
5677  auto range = blocks_with_unknown_parent->equal_range(head);
5678  while (range.first != range.second) {
5679  std::multimap<BlockHash, FlatFilePos>::iterator it =
5680  range.first;
5681  std::shared_ptr<CBlock> pblockrecursive =
5682  std::make_shared<CBlock>();
5683  if (m_blockman.ReadBlockFromDisk(*pblockrecursive,
5684  it->second)) {
5685  LogPrint(
5687  "%s: Processing out of order child %s of %s\n",
5688  __func__, pblockrecursive->GetHash().ToString(),
5689  head.ToString());
5690  LOCK(cs_main);
5691  BlockValidationState dummy;
5692  if (AcceptBlock(pblockrecursive, dummy, true,
5693  &it->second, nullptr, true)) {
5694  nLoaded++;
5695  queue.push_back(pblockrecursive->GetHash());
5696  }
5697  }
5698  range.first++;
5699  blocks_with_unknown_parent->erase(it);
5700  NotifyHeaderTip(*this);
5701  }
5702  }
5703  } catch (const std::exception &e) {
5704  // Historical bugs added extra data to the block files that does
5705  // not deserialize cleanly. Commonly this data is between
5706  // readable blocks, but it does not really matter. Such data is
5707  // not fatal to the import process. The code that reads the
5708  // block files deals with invalid data by simply ignoring it. It
5709  // continues to search for the next {4 byte magic message start
5710  // bytes + 4 byte length + block} that does deserialize cleanly
5711  // and passes all of the other block validation checks dealing
5712  // with POW and the merkle root, etc... We merely note with this
5713  // informational log message when unexpected data is
5714  // encountered. We could also be experiencing a storage system
5715  // read error, or a read of a previous bad write. These are
5716  // possible, but less likely scenarios. We don't have enough
5717  // information to tell a difference here. The reindex process is
5718  // not the place to attempt to clean and/or compact the block
5719  // files. If so desired, a studious node operator may use
5720  // knowledge of the fact that the block files are not entirely
5721  // pristine in order to prepare a set of pristine, and perhaps
5722  // ordered, block files for later reindexing.
5724  "%s: unexpected data at file offset 0x%x - %s. "
5725  "continuing\n",
5726  __func__, (nRewind - 1), e.what());
5727  }
5728  }
5729  } catch (const std::runtime_error &e) {
5730  AbortNode(std::string("System error: ") + e.what());
5731  }
5732 
5733  LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded,
5734  GetTimeMillis() - nStart);
5735 }
5736 
5739  return;
5740  }
5741 
5742  LOCK(cs_main);
5743 
5744  // During a reindex, we read the genesis block and call CheckBlockIndex
5745  // before ActivateBestChain, so we have the genesis block in
5746  // m_blockman.m_block_index but no active chain. (A few of the tests when
5747  // iterating the block tree require that m_chain has been initialized.)
5748  if (m_chain.Height() < 0) {
5749  assert(m_blockman.m_block_index.size() <= 1);
5750  return;
5751  }
5752 
5753  // Build forward-pointing map of the entire block tree.
5754  std::multimap<CBlockIndex *, CBlockIndex *> forward;
5755  for (auto &[_, block_index] : m_blockman.m_block_index) {
5756  forward.emplace(block_index.pprev, &block_index);
5757  }
5758 
5759  assert(forward.size() == m_blockman.m_block_index.size());
5760 
5761  std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
5762  std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
5763  rangeGenesis = forward.equal_range(nullptr);
5764  CBlockIndex *pindex = rangeGenesis.first->second;
5765  rangeGenesis.first++;
5766  // There is only one index entry with parent nullptr.
5767  assert(rangeGenesis.first == rangeGenesis.second);
5768 
5769  // Iterate over the entire block tree, using depth-first search.
5770  // Along the way, remember whether there are blocks on the path from genesis
5771  // block being explored which are the first to have certain properties.
5772  size_t nNodes = 0;
5773  int nHeight = 0;
5774  // Oldest ancestor of pindex which is invalid.
5775  CBlockIndex *pindexFirstInvalid = nullptr;
5776  // Oldest ancestor of pindex which is parked.
5777  CBlockIndex *pindexFirstParked = nullptr;
5778  // Oldest ancestor of pindex which does not have data available.
5779  CBlockIndex *pindexFirstMissing = nullptr;
5780  // Oldest ancestor of pindex for which nTx == 0.
5781  CBlockIndex *pindexFirstNeverProcessed = nullptr;
5782  // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE
5783  // (regardless of being valid or not).
5784  CBlockIndex *pindexFirstNotTreeValid = nullptr;
5785  // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS
5786  // (regardless of being valid or not).
5787  CBlockIndex *pindexFirstNotTransactionsValid = nullptr;
5788  // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN
5789  // (regardless of being valid or not).
5790  CBlockIndex *pindexFirstNotChainValid = nullptr;
5791  // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS
5792  // (regardless of being valid or not).
5793  CBlockIndex *pindexFirstNotScriptsValid = nullptr;
5794  while (pindex != nullptr) {
5795  nNodes++;
5796  if (pindexFirstInvalid == nullptr && pindex->nStatus.hasFailed()) {
5797  pindexFirstInvalid = pindex;
5798  }
5799  if (pindexFirstParked == nullptr && pindex->nStatus.isParked()) {
5800  pindexFirstParked = pindex;
5801  }
5802  // Assumed-valid index entries will not have data since we haven't
5803  // downloaded the full block yet.
5804  if (pindexFirstMissing == nullptr && !pindex->nStatus.hasData() &&
5805  !pindex->IsAssumedValid()) {
5806  pindexFirstMissing = pindex;
5807  }
5808  if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) {
5809  pindexFirstNeverProcessed = pindex;
5810  }
5811  if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr &&
5812  pindex->nStatus.getValidity() < BlockValidity::TREE) {
5813  pindexFirstNotTreeValid = pindex;
5814  }
5815  if (pindex->pprev != nullptr && !pindex->IsAssumedValid()) {
5816  if (pindexFirstNotTransactionsValid == nullptr &&
5817  pindex->nStatus.getValidity() < BlockValidity::TRANSACTIONS) {
5818  pindexFirstNotTransactionsValid = pindex;
5819  }
5820  if (pindexFirstNotChainValid == nullptr &&
5821  pindex->nStatus.getValidity() < BlockValidity::CHAIN) {
5822  pindexFirstNotChainValid = pindex;
5823  }
5824  if (pindexFirstNotScriptsValid == nullptr &&
5825  pindex->nStatus.getValidity() < BlockValidity::SCRIPTS) {
5826  pindexFirstNotScriptsValid = pindex;
5827  }
5828  }
5829 
5830  // Begin: actual consistency checks.
5831  if (pindex->pprev == nullptr) {
5832  // Genesis block checks.
5833  // Genesis block's hash must match.
5834  assert(pindex->GetBlockHash() ==
5836  // The current active chain's genesis block must be this block.
5837  assert(pindex == m_chain.Genesis());
5838  }
5839  if (!pindex->HaveTxsDownloaded()) {
5840  // nSequenceId can't be set positive for blocks that aren't linked
5841  // (negative is used for preciousblock)
5842  assert(pindex->nSequenceId <= 0);
5843  }
5844  // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or
5845  // not pruning has occurred). HAVE_DATA is only equivalent to nTx > 0
5846  // (or VALID_TRANSACTIONS) if no pruning has occurred.
5847  // Unless these indexes are assumed valid and pending block download on
5848  // a background chainstate.
5849  if (!m_blockman.m_have_pruned && !pindex->IsAssumedValid()) {
5850  // If we've never pruned, then HAVE_DATA should be equivalent to nTx
5851  // > 0
5852  assert(pindex->nStatus.hasData() == (pindex->nTx > 0));
5853  assert(pindexFirstMissing == pindexFirstNeverProcessed);
5854  } else if (pindex->nStatus.hasData()) {
5855  // If we have pruned, then we can only say that HAVE_DATA implies
5856  // nTx > 0
5857  assert(pindex->nTx > 0);
5858  }
5859  if (pindex->nStatus.hasUndo()) {
5860  assert(pindex->nStatus.hasData());
5861  }
5862  if (pindex->IsAssumedValid()) {
5863  // Assumed-valid blocks should have some nTx value.
5864  assert(pindex->nTx > 0);
5865  // Assumed-valid blocks should connect to the main chain.
5866  assert(pindex->nStatus.getValidity() >= BlockValidity::TREE);
5867  } else {
5868  // Otherwise there should only be an nTx value if we have
5869  // actually seen a block's transactions.
5870  // This is pruning-independent.
5871  assert((pindex->nStatus.getValidity() >=
5872  BlockValidity::TRANSACTIONS) == (pindex->nTx > 0));
5873  }
5874  // All parents having had data (at some point) is equivalent to all
5875  // parents being VALID_TRANSACTIONS, which is equivalent to
5876  // HaveTxsDownloaded(). All parents having had data (at some point) is
5877  // equivalent to all parents being VALID_TRANSACTIONS, which is
5878  // equivalent to HaveTxsDownloaded().
5879  assert((pindexFirstNeverProcessed == nullptr) ==
5880  (pindex->HaveTxsDownloaded()));
5881  assert((pindexFirstNotTransactionsValid == nullptr) ==
5882  (pindex->HaveTxsDownloaded()));
5883  // nHeight must be consistent.
5884  assert(pindex->nHeight == nHeight);
5885  // For every block except the genesis block, the chainwork must be
5886  // larger than the parent's.
5887  assert(pindex->pprev == nullptr ||
5888  pindex->nChainWork >= pindex->pprev->nChainWork);
5889  // The pskip pointer must point back for all but the first 2 blocks.
5890  assert(nHeight < 2 ||
5891  (pindex->pskip && (pindex->pskip->nHeight < nHeight)));
5892  // All m_blockman.m_block_index entries must at least be TREE valid
5893  assert(pindexFirstNotTreeValid == nullptr);
5894  if (pindex->nStatus.getValidity() >= BlockValidity::TREE) {
5895  // TREE valid implies all parents are TREE valid
5896  assert(pindexFirstNotTreeValid == nullptr);
5897  }
5898  if (pindex->nStatus.getValidity() >= BlockValidity::CHAIN) {
5899  // CHAIN valid implies all parents are CHAIN valid
5900  assert(pindexFirstNotChainValid == nullptr);
5901  }
5902  if (pindex->nStatus.getValidity() >= BlockValidity::SCRIPTS) {
5903  // SCRIPTS valid implies all parents are SCRIPTS valid
5904  assert(pindexFirstNotScriptsValid == nullptr);
5905  }
5906  if (pindexFirstInvalid == nullptr) {
5907  // Checks for not-invalid blocks.
5908  // The failed mask cannot be set for blocks without invalid parents.
5909  assert(!pindex->nStatus.isInvalid());
5910  }
5911  if (pindexFirstParked == nullptr) {
5912  // Checks for not-parked blocks.
5913  // The parked mask cannot be set for blocks without parked parents.
5914  // (i.e., hasParkedParent only if an ancestor is properly parked).
5915  assert(!pindex->nStatus.isOnParkedChain());
5916  }
5917  if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) &&
5918  pindexFirstNeverProcessed == nullptr) {
5919  if (pindexFirstInvalid == nullptr) {
5920  // Don't perform this check for the background chainstate since
5921  // its setBlockIndexCandidates shouldn't have some entries (i.e.
5922  // those past the snapshot block) which do exist in the block
5923  // index for the active chainstate.
5924  if (this == &m_chainman.ActiveChainstate()) {
5925  // If this block sorts at least as good as the current tip
5926  // and is valid and we have all data for its parents, it
5927  // must be in setBlockIndexCandidates or be parked.
5928  if (pindexFirstMissing == nullptr) {
5929  assert(pindex->nStatus.isOnParkedChain() ||
5930  setBlockIndexCandidates.count(pindex));
5931  }
5932  // m_chain.Tip() must also be there even if some data has
5933  // been pruned.
5934  if (pindex == m_chain.Tip()) {
5935  assert(setBlockIndexCandidates.count(pindex));
5936  }
5937  }
5938  // If some parent is missing, then it could be that this block
5939  // was in setBlockIndexCandidates but had to be removed because
5940  // of the missing data. In this case it must be in
5941  // m_blocks_unlinked -- see test below.
5942  }
5943  } else {
5944  // If this block sorts worse than the current tip or some ancestor's
5945  // block has never been seen, it cannot be in
5946  // setBlockIndexCandidates.
5947  assert(setBlockIndexCandidates.count(pindex) == 0);
5948  }
5949  // Check whether this block is in m_blocks_unlinked.
5950  std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
5951  std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
5952  rangeUnlinked =
5953  m_blockman.m_blocks_unlinked.equal_range(pindex->pprev);
5954  bool foundInUnlinked = false;
5955  while (rangeUnlinked.first != rangeUnlinked.second) {
5956  assert(rangeUnlinked.first->first == pindex->pprev);
5957  if (rangeUnlinked.first->second == pindex) {
5958  foundInUnlinked = true;
5959  break;
5960  }
5961  rangeUnlinked.first++;
5962  }
5963  if (pindex->pprev && pindex->nStatus.hasData() &&
5964  pindexFirstNeverProcessed != nullptr &&
5965  pindexFirstInvalid == nullptr) {
5966  // If this block has block data available, some parent was never
5967  // received, and has no invalid parents, it must be in
5968  // m_blocks_unlinked.
5969  assert(foundInUnlinked);
5970  }
5971  if (!pindex->nStatus.hasData()) {
5972  // Can't be in m_blocks_unlinked if we don't HAVE_DATA
5973  assert(!foundInUnlinked);
5974  }
5975  if (pindexFirstMissing == nullptr) {
5976  // We aren't missing data for any parent -- cannot be in
5977  // m_blocks_unlinked.
5978  assert(!foundInUnlinked);
5979  }
5980  if (pindex->pprev && pindex->nStatus.hasData() &&
5981  pindexFirstNeverProcessed == nullptr &&
5982  pindexFirstMissing != nullptr) {
5983  // We HAVE_DATA for this block, have received data for all parents
5984  // at some point, but we're currently missing data for some parent.
5985  // We must have pruned.
5987  // This block may have entered m_blocks_unlinked if:
5988  // - it has a descendant that at some point had more work than the
5989  // tip, and
5990  // - we tried switching to that descendant but were missing
5991  // data for some intermediate block between m_chain and the
5992  // tip.
5993  // So if this block is itself better than m_chain.Tip() and it
5994  // wasn't in
5995  // setBlockIndexCandidates, then it must be in m_blocks_unlinked.
5996  if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) &&
5997  setBlockIndexCandidates.count(pindex) == 0) {
5998  if (pindexFirstInvalid == nullptr) {
5999  assert(foundInUnlinked);
6000  }
6001  }
6002  }
6003  // Perhaps too slow
6004  // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash());
6005  // End: actual consistency checks.
6006 
6007  // Try descending into the first subnode.
6008  std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
6009  std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
6010  range = forward.equal_range(pindex);
6011  if (range.first != range.second) {
6012  // A subnode was found.
6013  pindex = range.first->second;
6014  nHeight++;
6015  continue;
6016  }
6017  // This is a leaf node. Move upwards until we reach a node of which we
6018  // have not yet visited the last child.
6019  while (pindex) {
6020  // We are going to either move to a parent or a sibling of pindex.
6021  // If pindex was the first with a certain property, unset the
6022  // corresponding variable.
6023  if (pindex == pindexFirstInvalid) {
6024  pindexFirstInvalid = nullptr;
6025  }
6026  if (pindex == pindexFirstParked) {
6027  pindexFirstParked = nullptr;
6028  }
6029  if (pindex == pindexFirstMissing) {
6030  pindexFirstMissing = nullptr;
6031  }
6032  if (pindex == pindexFirstNeverProcessed) {
6033  pindexFirstNeverProcessed = nullptr;
6034  }
6035  if (pindex == pindexFirstNotTreeValid) {
6036  pindexFirstNotTreeValid = nullptr;
6037  }
6038  if (pindex == pindexFirstNotTransactionsValid) {
6039  pindexFirstNotTransactionsValid = nullptr;
6040  }
6041  if (pindex == pindexFirstNotChainValid) {
6042  pindexFirstNotChainValid = nullptr;
6043  }
6044  if (pindex == pindexFirstNotScriptsValid) {
6045  pindexFirstNotScriptsValid = nullptr;
6046  }
6047  // Find our parent.
6048  CBlockIndex *pindexPar = pindex->pprev;
6049  // Find which child we just visited.
6050  std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
6051  std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
6052  rangePar = forward.equal_range(pindexPar);
6053  while (rangePar.first->second != pindex) {
6054  // Our parent must have at least the node we're coming from as
6055  // child.
6056  assert(rangePar.first != rangePar.second);
6057  rangePar.first++;
6058  }
6059  // Proceed to the next one.
6060  rangePar.first++;
6061  if (rangePar.first != rangePar.second) {
6062  // Move to the sibling.
6063  pindex = rangePar.first->second;
6064  break;
6065  } else {
6066  // Move up further.
6067  pindex = pindexPar;
6068  nHeight--;
6069  continue;
6070  }
6071  }
6072  }
6073 
6074  // Check that we actually traversed the entire map.
6075  assert(nNodes == forward.size());
6076 }
6077 
6078 std::string Chainstate::ToString() {
6080  CBlockIndex *tip = m_chain.Tip();
6081  return strprintf("Chainstate [%s] @ height %d (%s)",
6082  m_from_snapshot_blockhash ? "snapshot" : "ibd",
6083  tip ? tip->nHeight : -1,
6084  tip ? tip->GetBlockHash().ToString() : "null");
6085 }
6086 
6087 bool Chainstate::ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size) {
6089  if (coinstip_size == m_coinstip_cache_size_bytes &&
6090  coinsdb_size == m_coinsdb_cache_size_bytes) {
6091  // Cache sizes are unchanged, no need to continue.
6092  return true;
6093  }
6094  size_t old_coinstip_size = m_coinstip_cache_size_bytes;
6095  m_coinstip_cache_size_bytes = coinstip_size;
6096  m_coinsdb_cache_size_bytes = coinsdb_size;
6097  CoinsDB().ResizeCache(coinsdb_size);
6098 
6099  LogPrintf("[%s] resized coinsdb cache to %.1f MiB\n", this->ToString(),
6100  coinsdb_size * (1.0 / 1024 / 1024));
6101  LogPrintf("[%s] resized coinstip cache to %.1f MiB\n", this->ToString(),
6102  coinstip_size * (1.0 / 1024 / 1024));
6103 
6104  BlockValidationState state;
6105  bool ret;
6106 
6107  if (coinstip_size > old_coinstip_size) {
6108  // Likely no need to flush if cache sizes have grown.
6110  } else {
6111  // Otherwise, flush state to disk and deallocate the in-memory coins
6112  // map.
6114  }
6115  return ret;
6116 }
6117 
6123  const CBlockIndex *pindex) {
6124  if (pindex == nullptr) {
6125  return 0.0;
6126  }
6127 
6128  int64_t nNow = time(nullptr);
6129 
6130  double fTxTotal;
6131  if (pindex->GetChainTxCount() <= data.nTxCount) {
6132  fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
6133  } else {
6134  fTxTotal = pindex->GetChainTxCount() +
6135  (nNow - pindex->GetBlockTime()) * data.dTxRate;
6136  }
6137 
6138  return std::min<double>(pindex->GetChainTxCount() / fTxTotal, 1.0);
6139 }
6140 
6141 std::optional<BlockHash> ChainstateManager::SnapshotBlockhash() const {
6142  LOCK(::cs_main);
6143  if (m_active_chainstate && m_active_chainstate->m_from_snapshot_blockhash) {
6144  // If a snapshot chainstate exists, it will always be our active.
6145  return m_active_chainstate->m_from_snapshot_blockhash;
6146  }
6147  return std::nullopt;
6148 }
6149 
6150 std::vector<Chainstate *> ChainstateManager::GetAll() {
6151  LOCK(::cs_main);
6152  std::vector<Chainstate *> out;
6153 
6154  for (Chainstate *pchainstate :
6155  {m_ibd_chainstate.get(), m_snapshot_chainstate.get()}) {
6156  if (this->IsUsable(pchainstate)) {
6157  out.push_back(pchainstate);
6158  }
6159  }
6160 
6161  return out;
6162 }
6163 
6164 Chainstate &ChainstateManager::InitializeChainstate(CTxMemPool *mempool) {
6166  assert(!m_ibd_chainstate);
6167  assert(!m_active_chainstate);
6168 
6169  m_ibd_chainstate = std::make_unique<Chainstate>(mempool, m_blockman, *this);
6170  m_active_chainstate = m_ibd_chainstate.get();
6171  return *m_active_chainstate;
6172 }
6173 
6174 const AssumeutxoData *ExpectedAssumeutxo(const int height,
6175  const CChainParams &chainparams) {
6176  const MapAssumeutxo &valid_assumeutxos_map = chainparams.Assumeutxo();
6177  const auto assumeutxo_found = valid_assumeutxos_map.find(height);
6178 
6179  if (assumeutxo_found != valid_assumeutxos_map.end()) {
6180  return &assumeutxo_found->second;
6181  }
6182  return nullptr;
6183 }
6184 
6185 static bool DeleteCoinsDBFromDisk(const fs::path &db_path, bool is_snapshot)
6188 
6189  if (is_snapshot) {
6190  fs::path base_blockhash_path =
6192 
6193  try {
6194  const bool existed{fs::remove(base_blockhash_path)};
6195  if (!existed) {
6196  LogPrintf("[snapshot] snapshot chainstate dir being removed "
6197  "lacks %s file\n",
6199  }
6200  } catch (const fs::filesystem_error &e) {
6201  LogPrintf("[snapshot] failed to remove file %s: %s\n",
6202  fs::PathToString(base_blockhash_path),
6204  }
6205  }
6206 
6207  std::string path_str = fs::PathToString(db_path);
6208  LogPrintf("Removing leveldb dir at %s\n", path_str);
6209 
6210  // We have to destruct before this call leveldb::DB in order to release the
6211  // db lock, otherwise `DestroyDB` will fail. See `leveldb::~DBImpl()`.
6212  const bool destroyed = dbwrapper::DestroyDB(path_str, {}).ok();
6213 
6214  if (!destroyed) {
6215  LogPrintf("error: leveldb DestroyDB call failed on %s\n", path_str);
6216  }
6217 
6218  // Datadir should be removed from filesystem; otherwise initialization may
6219  // detect it on subsequent statups and get confused.
6220  //
6221  // If the base_blockhash_path removal above fails in the case of snapshot
6222  // chainstates, this will return false since leveldb won't remove a
6223  // non-empty directory.
6224  return destroyed && !fs::exists(db_path);
6225 }
6226 
6228  const SnapshotMetadata &metadata,
6229  bool in_memory) {
6230  BlockHash base_blockhash = metadata.m_base_blockhash;
6231 
6232  if (this->SnapshotBlockhash()) {
6233  LogPrintf("[snapshot] can't activate a snapshot-based chainstate more "
6234  "than once\n");
6235  return false;
6236  }
6237 
6238  int64_t current_coinsdb_cache_size{0};
6239  int64_t current_coinstip_cache_size{0};
6240 
6241  // Cache percentages to allocate to each chainstate.
6242  //
6243  // These particular percentages don't matter so much since they will only be
6244  // relevant during snapshot activation; caches are rebalanced at the
6245  // conclusion of this function. We want to give (essentially) all available
6246  // cache capacity to the snapshot to aid the bulk load later in this
6247  // function.
6248  static constexpr double IBD_CACHE_PERC = 0.01;
6249  static constexpr double SNAPSHOT_CACHE_PERC = 0.99;
6250 
6251  {
6252  LOCK(::cs_main);
6253  // Resize the coins caches to ensure we're not exceeding memory limits.
6254  //
6255  // Allocate the majority of the cache to the incoming snapshot
6256  // chainstate, since (optimistically) getting to its tip will be the top
6257  // priority. We'll need to call `MaybeRebalanceCaches()` once we're done
6258  // with this function to ensure the right allocation (including the
6259  // possibility that no snapshot was activated and that we should restore
6260  // the active chainstate caches to their original size).
6261  //
6262  current_coinsdb_cache_size =
6263  this->ActiveChainstate().m_coinsdb_cache_size_bytes;
6264  current_coinstip_cache_size =
6265  this->ActiveChainstate().m_coinstip_cache_size_bytes;
6266 
6267  // Temporarily resize the active coins cache to make room for the
6268  // newly-created snapshot chain.
6269  this->ActiveChainstate().ResizeCoinsCaches(
6270  static_cast<size_t>(current_coinstip_cache_size * IBD_CACHE_PERC),
6271  static_cast<size_t>(current_coinsdb_cache_size * IBD_CACHE_PERC));
6272  }
6273 
6274  auto snapshot_chainstate =
6275  WITH_LOCK(::cs_main, return std::make_unique<Chainstate>(
6276  /* mempool */ nullptr, m_blockman, *this,
6277  base_blockhash));
6278 
6279  {
6280  LOCK(::cs_main);
6281  snapshot_chainstate->InitCoinsDB(
6282  static_cast<size_t>(current_coinsdb_cache_size *
6283  SNAPSHOT_CACHE_PERC),
6284  in_memory, false, "chainstate");
6285  snapshot_chainstate->InitCoinsCache(static_cast<size_t>(
6286  current_coinstip_cache_size * SNAPSHOT_CACHE_PERC));
6287  }
6288 
6289  bool snapshot_ok = this->PopulateAndValidateSnapshot(*snapshot_chainstate,
6290  coins_file, metadata);
6291 
6292  // If not in-memory, persist the base blockhash for use during subsequent
6293  // initialization.
6294  if (!in_memory) {
6295  LOCK(::cs_main);
6296  if (!node::WriteSnapshotBaseBlockhash(*snapshot_chainstate)) {
6297  snapshot_ok = false;
6298  }
6299  }
6300  if (!snapshot_ok) {
6301  LOCK(::cs_main);
6302  this->MaybeRebalanceCaches();
6303 
6304  // PopulateAndValidateSnapshot can return (in error) before the leveldb
6305  // datadir has been created, so only attempt removal if we got that far.
6306  if (auto snapshot_datadir = node::FindSnapshotChainstateDir()) {
6307  // We have to destruct leveldb::DB in order to release the db lock,
6308  // otherwise DestroyDB() (in DeleteCoinsDBFromDisk()) will fail. See
6309  // `leveldb::~DBImpl()`. Destructing the chainstate (and so
6310  // resetting the coinsviews object) does this.
6311  snapshot_chainstate.reset();
6312  bool removed =
6313  DeleteCoinsDBFromDisk(*snapshot_datadir, /*is_snapshot=*/true);
6314  if (!removed) {
6315  AbortNode(
6316  strprintf("Failed to remove snapshot chainstate dir (%s). "
6317  "Manually remove it before restarting.\n",
6318  fs::PathToString(*snapshot_datadir)));
6319  }
6320  }
6321  return false;
6322  }
6323 
6324  {
6325  LOCK(::cs_main);
6326  assert(!m_snapshot_chainstate);
6327  m_snapshot_chainstate.swap(snapshot_chainstate);
6328  const bool chaintip_loaded = m_snapshot_chainstate->LoadChainTip();
6329  assert(chaintip_loaded);
6330 
6331  m_active_chainstate = m_snapshot_chainstate.get();
6332 
6333  LogPrintf("[snapshot] successfully activated snapshot %s\n",
6334  base_blockhash.ToString());
6335  LogPrintf("[snapshot] (%.2f MB)\n",
6336  m_snapshot_chainstate->CoinsTip().DynamicMemoryUsage() /
6337  (1000 * 1000));
6338 
6339  this->MaybeRebalanceCaches();
6340  }
6341  return true;
6342 }
6343 
6344 static void FlushSnapshotToDisk(CCoinsViewCache &coins_cache,
6345  bool snapshot_loaded) {
6347  strprintf("%s (%.2f MB)",
6348  snapshot_loaded ? "saving snapshot chainstate"
6349  : "flushing coins cache",
6350  coins_cache.DynamicMemoryUsage() / (1000 * 1000)),
6351  BCLog::LogFlags::ALL);
6352 
6353  coins_cache.Flush();
6354 }
6355 
6356 struct StopHashingException : public std::exception {
6357  const char *what() const throw() override {
6358  return "ComputeUTXOStats interrupted by shutdown.";
6359  }
6360 };
6361 
6363  if (ShutdownRequested()) {
6364  throw StopHashingException();
6365  }
6366 }
6367 
6369  Chainstate &snapshot_chainstate, AutoFile &coins_file,
6370  const SnapshotMetadata &metadata) {
6371  // It's okay to release cs_main before we're done using `coins_cache`
6372  // because we know that nothing else will be referencing the newly created
6373  // snapshot_chainstate yet.
6374  CCoinsViewCache &coins_cache =
6375  *WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsTip());
6376 
6377  BlockHash base_blockhash = metadata.m_base_blockhash;
6378 
6379  CBlockIndex *snapshot_start_block = WITH_LOCK(
6380  ::cs_main, return m_blockman.LookupBlockIndex(base_blockhash));
6381 
6382  if (!snapshot_start_block) {
6383  // Needed for ComputeUTXOStats and ExpectedAssumeutxo to determine the
6384  // height and to avoid a crash when base_blockhash.IsNull()
6385  LogPrintf("[snapshot] Did not find snapshot start blockheader %s\n",
6386  base_blockhash.ToString());
6387  return false;
6388  }
6389 
6390  int base_height = snapshot_start_block->nHeight;
6391  auto maybe_au_data = ExpectedAssumeutxo(base_height, GetParams());
6392 
6393  if (!maybe_au_data) {
6394  LogPrintf("[snapshot] assumeutxo height in snapshot metadata not "
6395  "recognized (%d) - refusing to load snapshot\n",
6396  base_height);
6397  return false;
6398  }
6399 
6400  const AssumeutxoData &au_data = *maybe_au_data;
6401 
6402  COutPoint outpoint;
6403  Coin coin;
6404  const uint64_t coins_count = metadata.m_coins_count;
6405  uint64_t coins_left = metadata.m_coins_count;
6406 
6407  LogPrintf("[snapshot] loading coins from snapshot %s\n",
6408  base_blockhash.ToString());
6409  int64_t coins_processed{0};
6410 
6411  while (coins_left > 0) {
6412  try {
6413  coins_file >> outpoint;
6414  coins_file >> coin;
6415  } catch (const std::ios_base::failure &) {
6416  LogPrintf("[snapshot] bad snapshot format or truncated snapshot "
6417  "after deserializing %d coins\n",
6418  coins_count - coins_left);
6419  return false;
6420  }
6421  if (coin.GetHeight() > uint32_t(base_height) ||
6422  // Avoid integer wrap-around in coinstats.cpp:ApplyHash
6423  outpoint.GetN() >=
6424  std::numeric_limits<decltype(outpoint.GetN())>::max()) {
6425  LogPrintf(
6426  "[snapshot] bad snapshot data after deserializing %d coins\n",
6427  coins_count - coins_left);
6428  return false;
6429  }
6430  coins_cache.EmplaceCoinInternalDANGER(std::move(outpoint),
6431  std::move(coin));
6432 
6433  --coins_left;
6434  ++coins_processed;
6435 
6436  if (coins_processed % 1000000 == 0) {
6437  LogPrintf("[snapshot] %d coins loaded (%.2f%%, %.2f MB)\n",
6438  coins_processed,
6439  static_cast<float>(coins_processed) * 100 /
6440  static_cast<float>(coins_count),
6441  coins_cache.DynamicMemoryUsage() / (1000 * 1000));
6442  }
6443 
6444  // Batch write and flush (if we need to) every so often.
6445  //
6446  // If our average Coin size is roughly 41 bytes, checking every 120,000
6447  // coins means <5MB of memory imprecision.
6448  if (coins_processed % 120000 == 0) {
6449  if (ShutdownRequested()) {
6450  return false;
6451  }
6452 
6453  const auto snapshot_cache_state = WITH_LOCK(
6454  ::cs_main, return snapshot_chainstate.GetCoinsCacheSizeState());
6455 
6456  if (snapshot_cache_state >= CoinsCacheSizeState::CRITICAL) {
6457  // This is a hack - we don't know what the actual best block is,
6458  // but that doesn't matter for the purposes of flushing the
6459  // cache here. We'll set this to its correct value
6460  // (`base_blockhash`) below after the coins are loaded.
6461  coins_cache.SetBestBlock(BlockHash{GetRandHash()});
6462 
6463  // No need to acquire cs_main since this chainstate isn't being
6464  // used yet.
6465  FlushSnapshotToDisk(coins_cache, /*snapshot_loaded=*/false);
6466  }
6467  }
6468  }
6469 
6470  // Important that we set this. This and the coins_cache accesses above are
6471  // sort of a layer violation, but either we reach into the innards of
6472  // CCoinsViewCache here or we have to invert some of the Chainstate to
6473  // embed them in a snapshot-activation-specific CCoinsViewCache bulk load
6474  // method.
6475  coins_cache.SetBestBlock(base_blockhash);
6476 
6477  bool out_of_coins{false};
6478  try {
6479  coins_file >> outpoint;
6480  } catch (const std::ios_base::failure &) {
6481  // We expect an exception since we should be out of coins.
6482  out_of_coins = true;
6483  }
6484  if (!out_of_coins) {
6485  LogPrintf("[snapshot] bad snapshot - coins left over after "
6486  "deserializing %d coins\n",
6487  coins_count);
6488  return false;
6489  }
6490 
6491  LogPrintf("[snapshot] loaded %d (%.2f MB) coins from snapshot %s\n",
6492  coins_count, coins_cache.DynamicMemoryUsage() / (1000 * 1000),
6493  base_blockhash.ToString());
6494 
6495  // No need to acquire cs_main since this chainstate isn't being used yet.
6496  FlushSnapshotToDisk(coins_cache, /*snapshot_loaded=*/true);
6497 
6498  assert(coins_cache.GetBestBlock() == base_blockhash);
6499 
6500  // As above, okay to immediately release cs_main here since no other context
6501  // knows about the snapshot_chainstate.
6502  CCoinsViewDB *snapshot_coinsdb =
6503  WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsDB());
6504 
6505  std::optional<CCoinsStats> maybe_stats;
6506 
6507  try {
6508  maybe_stats = ComputeUTXOStats(CoinStatsHashType::HASH_SERIALIZED,
6509  snapshot_coinsdb, m_blockman,
6511  } catch (StopHashingException const &) {
6512  return false;
6513  }
6514  if (!maybe_stats.has_value()) {
6515  LogPrintf("[snapshot] failed to generate coins stats\n");
6516  return false;
6517  }
6518 
6519  // Assert that the deserialized chainstate contents match the expected
6520  // assumeutxo value.
6521  if (AssumeutxoHash{maybe_stats->hashSerialized} !=
6522  au_data.hash_serialized) {
6523  LogPrintf("[snapshot] bad snapshot content hash: expected %s, got %s\n",
6524  au_data.hash_serialized.ToString(),
6525  maybe_stats->hashSerialized.ToString());
6526  return false;
6527  }
6528 
6529  snapshot_chainstate.m_chain.SetTip(*snapshot_start_block);
6530 
6531  // The remainder of this function requires modifying data protected by
6532  // cs_main.
6533  LOCK(::cs_main);
6534 
6535  // Fake various pieces of CBlockIndex state:
6536  CBlockIndex *index = nullptr;
6537 
6538  // Don't make any modifications to the genesis block.
6539  // This is especially important because we don't want to erroneously
6540  // apply ASSUMED_VALID_FLAG to genesis, which would happen if we didn't
6541  // skip it here (since it apparently isn't BlockValidity::SCRIPTS).
6542  constexpr int AFTER_GENESIS_START{1};
6543 
6544  for (int i = AFTER_GENESIS_START; i <= snapshot_chainstate.m_chain.Height();
6545  ++i) {
6546  index = snapshot_chainstate.m_chain[i];
6547 
6548  // Fake nTx so that LoadBlockIndex() loads assumed-valid CBlockIndex
6549  // entries (among other things)
6550  if (!index->nTx) {
6551  index->nTx = 1;
6552  }
6553  // Fake nChainTx so that GuessVerificationProgress reports accurately
6554  index->nChainTx = index->pprev->nChainTx + index->nTx;
6555 
6556  // Mark unvalidated block index entries beneath the snapshot base block
6557  // as assumed-valid.
6558  if (!index->IsValid(BlockValidity::SCRIPTS)) {
6559  // This flag will be removed once the block is fully validated by a
6560  // background chainstate.
6561  index->nStatus = index->nStatus.withAssumedValid();
6562  }
6563 
6564  m_blockman.m_dirty_blockindex.insert(index);
6565  // Changes to the block index will be flushed to disk after this call
6566  // returns in `ActivateSnapshot()`, when `MaybeRebalanceCaches()` is
6567  // called, since we've added a snapshot chainstate and therefore will
6568  // have to downsize the IBD chainstate, which will result in a call to
6569  // `FlushStateToDisk(ALWAYS)`.
6570  }
6571 
6572  assert(index);
6573  index->nChainTx = au_data.nChainTx;
6574  snapshot_chainstate.setBlockIndexCandidates.insert(snapshot_start_block);
6575 
6576  LogPrintf("[snapshot] validated snapshot (%.2f MB)\n",
6577  coins_cache.DynamicMemoryUsage() / (1000 * 1000));
6578  return true;
6579 }
6580 
6581 // Currently, this function holds cs_main for its duration, which could be for
6582 // multiple minutes due to the ComputeUTXOStats call. This hold is necessary
6583 // because we need to avoid advancing the background validation chainstate
6584 // farther than the snapshot base block - and this function is also invoked
6585 // from within ConnectTip, i.e. from within ActivateBestChain, so cs_main is
6586 // held anyway.
6587 //
6588 // Eventually (TODO), we could somehow separate this function's runtime from
6589 // maintenance of the active chain, but that will either require
6590 //
6591 // (i) setting `m_disabled` immediately and ensuring all chainstate accesses go
6592 // through IsUsable() checks, or
6593 //
6594 // (ii) giving each chainstate its own lock instead of using cs_main for
6595 // everything.
6596 SnapshotCompletionResult ChainstateManager::MaybeCompleteSnapshotValidation(
6597  std::function<void(bilingual_str)> shutdown_fnc) {
6599  if (m_ibd_chainstate.get() == &this->ActiveChainstate() ||
6600  !this->IsUsable(m_snapshot_chainstate.get()) ||
6601  !this->IsUsable(m_ibd_chainstate.get()) ||
6602  !m_ibd_chainstate->m_chain.Tip()) {
6603  // Nothing to do - this function only applies to the background
6604  // validation chainstate.
6606  }
6607  const int snapshot_tip_height = this->ActiveHeight();
6608  const int snapshot_base_height = *Assert(this->GetSnapshotBaseHeight());
6609  const CBlockIndex &index_new = *Assert(m_ibd_chainstate->m_chain.Tip());
6610 
6611  if (index_new.nHeight < snapshot_base_height) {
6612  // Background IBD not complete yet.
6614  }
6615 
6617  BlockHash snapshot_blockhash = *Assert(SnapshotBlockhash());
6618 
6619  auto handle_invalid_snapshot = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
6620  bilingual_str user_error = strprintf(
6621  _("%s failed to validate the -assumeutxo snapshot state. "
6622  "This indicates a hardware problem, or a bug in the software, or "
6623  "a bad software modification that allowed an invalid snapshot to "
6624  "be loaded. As a result of this, the node will shut down and "
6625  "stop using any state that was built on the snapshot, resetting "
6626  "the chain height from %d to %d. On the next restart, the node "
6627  "will resume syncing from %d without using any snapshot data. "
6628  "Please report this incident to %s, including how you obtained "
6629  "the snapshot. The invalid snapshot chainstate will be left on "
6630  "disk in case it is helpful in diagnosing the issue that caused "
6631  "this error."),
6632  PACKAGE_NAME, snapshot_tip_height, snapshot_base_height,
6633  snapshot_base_height, PACKAGE_BUGREPORT);
6634 
6635  LogPrintf("[snapshot] !!! %s\n", user_error.original);
6636  LogPrintf("[snapshot] deleting snapshot, reverting to validated chain, "
6637  "and stopping node\n");
6638 
6639  m_active_chainstate = m_ibd_chainstate.get();
6640  m_snapshot_chainstate->m_disabled = true;
6641  assert(!this->IsUsable(m_snapshot_chainstate.get()));
6642  assert(this->IsUsable(m_ibd_chainstate.get()));
6643 
6644  auto rename_result = m_snapshot_chainstate->InvalidateCoinsDBOnDisk();
6645  if (!rename_result) {
6646  user_error = strprintf(Untranslated("%s\n%s"), user_error,
6647  util::ErrorString(rename_result));
6648  }
6649 
6650  shutdown_fnc(user_error);
6651  };
6652 
6653  if (index_new.GetBlockHash() != snapshot_blockhash) {
6654  LogPrintf(
6655  "[snapshot] supposed base block %s does not match the "
6656  "snapshot base block %s (height %d). Snapshot is not valid.\n",
6657  index_new.ToString(), snapshot_blockhash.ToString(),
6658  snapshot_base_height);
6659  handle_invalid_snapshot();
6661  }
6662 
6663  assert(index_new.nHeight == snapshot_base_height);
6664 
6665  int curr_height = m_ibd_chainstate->m_chain.Height();
6666 
6667  assert(snapshot_base_height == curr_height);
6668  assert(snapshot_base_height == index_new.nHeight);
6669  assert(this->IsUsable(m_snapshot_chainstate.get()));
6670  assert(this->GetAll().size() == 2);
6671 
6672  CCoinsViewDB &ibd_coins_db = m_ibd_chainstate->CoinsDB();
6673  m_ibd_chainstate->ForceFlushStateToDisk();
6674 
6675  auto maybe_au_data = ExpectedAssumeutxo(curr_height, GetParams());
6676  if (!maybe_au_data) {
6677  LogPrintf("[snapshot] assumeutxo data not found for height "
6678  "(%d) - refusing to validate snapshot\n",
6679  curr_height);
6680  handle_invalid_snapshot();
6682  }
6683 
6684  const AssumeutxoData &au_data = *maybe_au_data;
6685  std::optional<CCoinsStats> maybe_ibd_stats;
6686  LogPrintf(
6687  "[snapshot] computing UTXO stats for background chainstate to validate "
6688  "snapshot - this could take a few minutes\n");
6689  try {
6690  maybe_ibd_stats =
6691  ComputeUTXOStats(CoinStatsHashType::HASH_SERIALIZED, &ibd_coins_db,
6693  } catch (StopHashingException const &) {
6695  }
6696 
6697  if (!maybe_ibd_stats) {
6698  LogPrintf(
6699  "[snapshot] failed to generate stats for validation coins db\n");
6700  // While this isn't a problem with the snapshot per se, this condition
6701  // prevents us from validating the snapshot, so we should shut down and
6702  // let the user handle the issue manually.
6703  handle_invalid_snapshot();
6705  }
6706  const auto &ibd_stats = *maybe_ibd_stats;
6707 
6708  // Compare the background validation chainstate's UTXO set hash against the
6709  // hard-coded assumeutxo hash we expect.
6710  //
6711  // TODO: For belt-and-suspenders, we could cache the UTXO set
6712  // hash for the snapshot when it's loaded in its chainstate's leveldb. We
6713  // could then reference that here for an additional check.
6714  if (AssumeutxoHash{ibd_stats.hashSerialized} != au_data.hash_serialized) {
6715  LogPrintf("[snapshot] hash mismatch: actual=%s, expected=%s\n",
6716  ibd_stats.hashSerialized.ToString(),
6717  au_data.hash_serialized.ToString());
6718  handle_invalid_snapshot();
6720  }
6721 
6722  LogPrintf("[snapshot] snapshot beginning at %s has been fully validated\n",
6723  snapshot_blockhash.ToString());
6724 
6725  m_ibd_chainstate->m_disabled = true;
6726  this->MaybeRebalanceCaches();
6727 
6729 }
6730 
6731 Chainstate &ChainstateManager::ActiveChainstate() const {
6732  LOCK(::cs_main);
6733  assert(m_active_chainstate);
6734  return *m_active_chainstate;
6735 }
6736 
6738  LOCK(::cs_main);
6739  return m_snapshot_chainstate &&
6740  m_active_chainstate == m_snapshot_chainstate.get();
6741 }
6742 void ChainstateManager::MaybeRebalanceCaches() {
6744  bool ibd_usable = this->IsUsable(m_ibd_chainstate.get());
6745  bool snapshot_usable = this->IsUsable(m_snapshot_chainstate.get());
6746  assert(ibd_usable || snapshot_usable);
6747 
6748  if (ibd_usable && !snapshot_usable) {
6749  LogPrintf("[snapshot] allocating all cache to the IBD chainstate\n");
6750  // Allocate everything to the IBD chainstate.
6751  m_ibd_chainstate->ResizeCoinsCaches(m_total_coinstip_cache,
6753  } else if (snapshot_usable && !ibd_usable) {
6754  // If background validation has completed and snapshot is our active
6755  // chain...
6756  LogPrintf(
6757  "[snapshot] allocating all cache to the snapshot chainstate\n");
6758  // Allocate everything to the snapshot chainstate.
6759  m_snapshot_chainstate->ResizeCoinsCaches(m_total_coinstip_cache,
6761  } else if (ibd_usable && snapshot_usable) {
6762  // If both chainstates exist, determine who needs more cache based on
6763  // IBD status.
6764  //
6765  // Note: shrink caches first so that we don't inadvertently overwhelm
6766  // available memory.
6767  if (m_snapshot_chainstate->IsInitialBlockDownload()) {
6768  m_ibd_chainstate->ResizeCoinsCaches(m_total_coinstip_cache * 0.05,
6769  m_total_coinsdb_cache * 0.05);
6770  m_snapshot_chainstate->ResizeCoinsCaches(
6772  } else {
6773  m_snapshot_chainstate->ResizeCoinsCaches(
6775  m_ibd_chainstate->ResizeCoinsCaches(m_total_coinstip_cache * 0.95,
6776  m_total_coinsdb_cache * 0.95);
6777  }
6778  }
6779 }
6780 
6781 void ChainstateManager::ResetChainstates() {
6782  m_ibd_chainstate.reset();
6783  m_snapshot_chainstate.reset();
6784  m_active_chainstate = nullptr;
6785 }
6786 
6793  if (!opts.check_block_index.has_value()) {
6794  opts.check_block_index =
6795  opts.config.GetChainParams().DefaultConsistencyChecks();
6796  }
6797 
6798  if (!opts.minimum_chain_work.has_value()) {
6799  opts.minimum_chain_work = UintToArith256(
6800  opts.config.GetChainParams().GetConsensus().nMinimumChainWork);
6801  }
6802  if (!opts.assumed_valid_block.has_value()) {
6803  opts.assumed_valid_block =
6804  opts.config.GetChainParams().GetConsensus().defaultAssumeValid;
6805  }
6806  Assert(opts.adjusted_time_callback);
6807  return std::move(opts);
6808 }
6809 
6811  Options options, node::BlockManager::Options blockman_options)
6812  : m_options{Flatten(std::move(options))}, m_blockman{std::move(
6813  blockman_options)} {}
6814 
6815 bool ChainstateManager::DetectSnapshotChainstate(CTxMemPool *mempool) {
6816  assert(!m_snapshot_chainstate);
6817  std::optional<fs::path> path = node::FindSnapshotChainstateDir();
6818  if (!path) {
6819  return false;
6820  }
6821  std::optional<BlockHash> base_blockhash =
6823  if (!base_blockhash) {
6824  return false;
6825  }
6826  LogPrintf("[snapshot] detected active snapshot chainstate (%s) - loading\n",
6827  fs::PathToString(*path));
6828 
6829  this->ActivateExistingSnapshot(mempool, *base_blockhash);
6830  return true;
6831 }
6832 
6833 Chainstate &
6834 ChainstateManager::ActivateExistingSnapshot(CTxMemPool *mempool,
6835  BlockHash base_blockhash) {
6836  assert(!m_snapshot_chainstate);
6837  m_snapshot_chainstate = std::make_unique<Chainstate>(mempool, m_blockman,
6838  *this, base_blockhash);
6839  LogPrintf("[snapshot] switching active chainstate to %s\n",
6840  m_snapshot_chainstate->ToString());
6841  m_active_chainstate = m_snapshot_chainstate.get();
6842  return *m_snapshot_chainstate;
6843 }
6844 
6845 util::Result<void> Chainstate::InvalidateCoinsDBOnDisk() {
6847  // Should never be called on a non-snapshot chainstate.
6849  auto storage_path_maybe = this->CoinsDB().StoragePath();
6850  // Should never be called with a non-existent storage path.
6851  assert(storage_path_maybe);
6852  fs::path snapshot_datadir = *storage_path_maybe;
6853 
6854  // Coins views no longer usable.
6855  m_coins_views.reset();
6856 
6857  auto invalid_path = snapshot_datadir + "_INVALID";
6858  std::string dbpath = fs::PathToString(snapshot_datadir);
6859  std::string target = fs::PathToString(invalid_path);
6860  LogPrintf("[snapshot] renaming snapshot datadir %s to %s\n", dbpath,
6861  target);
6862 
6863  // The invalid snapshot datadir is simply moved and not deleted because we
6864  // may want to do forensics later during issue investigation. The user is
6865  // instructed accordingly in MaybeCompleteSnapshotValidation().
6866  try {
6867  fs::rename(snapshot_datadir, invalid_path);
6868  } catch (const fs::filesystem_error &e) {
6869  auto src_str = fs::PathToString(snapshot_datadir);
6870  auto dest_str = fs::PathToString(invalid_path);
6871 
6872  LogPrintf("%s: error renaming file '%s' -> '%s': %s\n", __func__,
6873  src_str, dest_str, e.what());
6874  return util::Error{strprintf(_("Rename of '%s' -> '%s' failed. "
6875  "You should resolve this by manually "
6876  "moving or deleting the invalid "
6877  "snapshot directory %s, otherwise you "
6878  "will encounter the same error again "
6879  "on the next startup."),
6880  src_str, dest_str, src_str)};
6881  }
6882  return {};
6883 }
6884 
6885 const CBlockIndex *ChainstateManager::GetSnapshotBaseBlock() const {
6886  const auto blockhash_op = this->SnapshotBlockhash();
6887  if (!blockhash_op) {
6888  return nullptr;
6889  }
6890  return Assert(m_blockman.LookupBlockIndex(*blockhash_op));
6891 }
6892 
6893 std::optional<int> ChainstateManager::GetSnapshotBaseHeight() const {
6894  const CBlockIndex *base = this->GetSnapshotBaseBlock();
6895  return base ? std::make_optional(base->nHeight) : std::nullopt;
6896 }
6897 
6898 bool ChainstateManager::ValidatedSnapshotCleanup() {
6900  auto get_storage_path = [](auto &chainstate) EXCLUSIVE_LOCKS_REQUIRED(
6901  ::cs_main) -> std::optional<fs::path> {
6902  if (!(chainstate && chainstate->HasCoinsViews())) {
6903  return {};
6904  }
6905  return chainstate->CoinsDB().StoragePath();
6906  };
6907  std::optional<fs::path> ibd_chainstate_path_maybe =
6908  get_storage_path(m_ibd_chainstate);
6909  std::optional<fs::path> snapshot_chainstate_path_maybe =
6910  get_storage_path(m_snapshot_chainstate);
6911 
6912  if (!this->IsSnapshotValidated()) {
6913  // No need to clean up.
6914  return false;
6915  }
6916  // If either path doesn't exist, that means at least one of the chainstates
6917  // is in-memory, in which case we can't do on-disk cleanup. You'd better be
6918  // in a unittest!
6919  if (!ibd_chainstate_path_maybe || !snapshot_chainstate_path_maybe) {
6920  LogPrintf("[snapshot] snapshot chainstate cleanup cannot happen with "
6921  "in-memory chainstates. You are testing, right?\n");
6922  return false;
6923  }
6924 
6925  const auto &snapshot_chainstate_path = *snapshot_chainstate_path_maybe;
6926  const auto &ibd_chainstate_path = *ibd_chainstate_path_maybe;
6927 
6928  // Since we're going to be moving around the underlying leveldb filesystem
6929  // content for each chainstate, make sure that the chainstates (and their
6930  // constituent CoinsViews members) have been destructed first.
6931  //
6932  // The caller of this method will be responsible for reinitializing
6933  // chainstates if they want to continue operation.
6934  this->ResetChainstates();
6935 
6936  // No chainstates should be considered usable.
6937  assert(this->GetAll().size() == 0);
6938 
6939  LogPrintf("[snapshot] deleting background chainstate directory (now "
6940  "unnecessary) (%s)\n",
6941  fs::PathToString(ibd_chainstate_path));
6942 
6943  fs::path tmp_old{ibd_chainstate_path + "_todelete"};
6944 
6945  auto rename_failed_abort = [](fs::path p_old, fs::path p_new,
6946  const fs::filesystem_error &err) {
6947  LogPrintf("Error renaming file (%s): %s\n", fs::PathToString(p_old),
6948  err.what());
6950  "Rename of '%s' -> '%s' failed. "
6951  "Cannot clean up the background chainstate leveldb directory.",
6952  fs::PathToString(p_old), fs::PathToString(p_new)));
6953  };
6954 
6955  try {
6956  fs::rename(ibd_chainstate_path, tmp_old);
6957  } catch (const fs::filesystem_error &e) {
6958  rename_failed_abort(ibd_chainstate_path, tmp_old, e);
6959  throw;
6960  }
6961 
6962  LogPrintf("[snapshot] moving snapshot chainstate (%s) to "
6963  "default chainstate directory (%s)\n",
6964  fs::PathToString(snapshot_chainstate_path),
6965  fs::PathToString(ibd_chainstate_path));
6966 
6967  try {
6968  fs::rename(snapshot_chainstate_path, ibd_chainstate_path);
6969  } catch (const fs::filesystem_error &e) {
6970  rename_failed_abort(snapshot_chainstate_path, ibd_chainstate_path, e);
6971  throw;
6972  }
6973 
6974  if (!DeleteCoinsDBFromDisk(tmp_old, /*is_snapshot=*/false)) {
6975  // No need to AbortNode because once the unneeded bg chainstate data is
6976  // moved, it will not interfere with subsequent initialization.
6977  LogPrintf("Deletion of %s failed. Please remove it manually, as the "
6978  "directory is now unnecessary.\n",
6979  fs::PathToString(tmp_old));
6980  } else {
6981  LogPrintf("[snapshot] deleted background chainstate directory (%s)\n",
6982  fs::PathToString(ibd_chainstate_path));
6983  }
6984  return true;
6985 }
bool IsDAAEnabled(const Consensus::Params &params, int nHeight)
Definition: activation.cpp:24
bool IsUAHFenabled(const Consensus::Params &params, int nHeight)
Definition: activation.cpp:11
static bool IsPhononEnabled(const Consensus::Params &params, int32_t nHeight)
Definition: activation.cpp:65
static bool IsGravitonEnabled(const Consensus::Params &params, int32_t nHeight)
Definition: activation.cpp:51
bool IsMagneticAnomalyEnabled(const Consensus::Params &params, int32_t nHeight)
Check if Nov 15, 2018 HF has activated using block height.
Definition: activation.cpp:37
bool MoneyRange(const Amount nValue)
Definition: amount.h:166
static constexpr Amount SATOSHI
Definition: amount.h:143
static constexpr Amount COIN
Definition: amount.h:144
ArgsManager gArgs
Definition: args.cpp:38
arith_uint256 UintToArith256(const uint256 &a)
int flags
Definition: bitcoin-tx.cpp:543
@ CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
@ TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
@ SCRIPTS
Scripts & signatures ok.
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:74
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:112
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params &params)
Return the time it would take to redo the work difference between from and to, assuming the current h...
Definition: chain.cpp:89
bool AreOnTheSameFork(const CBlockIndex *pa, const CBlockIndex *pb)
Check if two block index are on the same fork.
Definition: chain.cpp:136
#define Assert(val)
Identity function.
Definition: check.h:84
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: args.cpp:289
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:215
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:526
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:556
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:528
std::string ToString() const
Definition: hash_type.h:28
uint64_t getExcessiveBlockSize() const
Definition: validation.h:153
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
Definition: validation.h:138
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
Definition: validation.h:145
BlockValidationOptions(const Config &config)
Definition: validation.cpp:117
bool shouldValidatePoW() const
Definition: validation.h:151
bool shouldValidateMerkleRoot() const
Definition: validation.h:152
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
BlockHash GetHash() const
Definition: block.cpp:11
NodeSeconds Time() const
Definition: block.h:53
uint32_t nBits
Definition: block.h:30
BlockHash hashPrevBlock
Definition: block.h:27
int64_t GetBlockTime() const
Definition: block.h:57
int32_t nVersion
Definition: block.h:26
uint256 hashMerkleRoot
Definition: block.h:28
Definition: block.h:60
std::string ToString() const
Definition: block.cpp:15
std::vector< CTransactionRef > vtx
Definition: block.h:63
bool fChecked
Definition: block.h:66
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
bool IsValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: blockindex.h:211
std::string ToString() const
Definition: blockindex.cpp:28
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
bool IsAssumedValid() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: blockindex.h:219
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: blockindex.h:51
const BlockHash * phashBlock
pointer to the hash of the block, if any.
Definition: blockindex.h:29
bool HaveTxsDownloaded() const
Check whether this block's and all previous blocks' transactions have been downloaded (and stored to ...
Definition: blockindex.h:174
int64_t GetChainTxCount() const
Get the number of transaction in the chain so far.
Definition: blockindex.h:154
uint32_t nTime
Definition: blockindex.h:92
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: blockindex.h:98
int64_t GetReceivedTimeDiff() const
Definition: blockindex.h:186
int64_t GetBlockTime() const
Definition: blockindex.h:180
int64_t GetMedianTimePast() const
Definition: blockindex.h:192
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: blockindex.h:123
bool UpdateChainStats()
Update chain tx stats.
Definition: blockindex.cpp:34
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: blockindex.h:35
unsigned int nTx
Number of transactions in this block.
Definition: blockindex.h:60
bool RaiseValidity(enum BlockValidity nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
Definition: blockindex.h:226
NodeSeconds Time() const
Definition: blockindex.h:176
int32_t nVersion
block header
Definition: blockindex.h:90
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: blockindex.cpp:78
BlockHash GetBlockHash() const
Definition: blockindex.h:146
unsigned int nSize
Size of this block.
Definition: blockindex.h:65
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
Definition: blockindex.h:77
Undo information for a CBlock.
Definition: undo.h:73
std::vector< CTxUndo > vtxundo
Definition: undo.h:76
Non-refcounted RAII wrapper around a FILE* that implements a ring buffer to deserialize from.
Definition: streams.h:671
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:143
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
Definition: chain.h:174
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:150
void SetTip(CBlockIndex &block)
Set/initialize a chain with a given tip.
Definition: chain.cpp:8
int Height() const
Return the maximal height in the chain.
Definition: chain.h:186
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:49
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:166
CBlockLocator GetLocator() const
Return a CBlockLocator that refers to the tip of this chain.
Definition: chain.cpp:45
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:80
const ChainTxData & TxData() const
Definition: chainparams.h:140
const CCheckpointData & Checkpoints() const
Definition: chainparams.h:134
const MapAssumeutxo & Assumeutxo() const
Get allowed assumeutxo configuration.
Definition: chainparams.h:138
const CMessageHeader::MessageMagic & DiskMagic() const
Definition: chainparams.h:93
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:92
uint64_t PruneAfterHeight() const
Definition: chainparams.h:114
const CBlock & GenesisBlock() const
Definition: chainparams.h:105
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
Definition: checkqueue.h:198
void Add(std::vector< T > &&vChecks)
Definition: checkqueue.h:224
Queue for verifications that have to be performed.
Definition: checkqueue.h:28
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:47
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:221
void AddCoin(const COutPoint &outpoint, Coin coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:104
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:214
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:172
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:330
void SetBestBlock(const BlockHash &hashBlock)
Definition: coins.cpp:221
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:342
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:95
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:209
bool Flush()
Push the modifications applied to this cache to its base and wipe local state.
Definition: coins.cpp:301
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:67
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:148
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:204
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:196
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:65
std::optional< fs::path > StoragePath()
Definition: txdb.h:92
void ResizeCache(size_t new_cache_size) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Dynamically alter the underlying leveldb cache size.
Definition: txdb.cpp:82
Abstract view on the open txout dataset.
Definition: coins.h:163
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:13
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:591
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
void BlockConnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
void UpdatedBlockTip(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)
void BlockDisconnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
void BlockChecked(const CBlock &, const BlockValidationState &)
void BlockFinalized(const CBlockIndex *)
void TransactionAddedToMempool(const CTransactionRef &, std::shared_ptr< const std::vector< Coin >>, uint64_t mempool_sequence)
void NewPoWValidBlock(const CBlockIndex *, const std::shared_ptr< const CBlock > &)
void ChainStateFlushed(const CBlockLocator &)
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:36
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:20
uint32_t GetN() const
Definition: transaction.h:36
const TxId & GetTxId() const
Definition: transaction.h:35
void insert(Span< const uint8_t > vKey)
Definition: bloom.cpp:215
bool contains(Span< const uint8_t > vKey) const
Definition: bloom.cpp:249
Closure representing one script verification.
Definition: validation.h:526
bool operator()()
ScriptError GetScriptError() const
Definition: validation.h:557
ScriptExecutionMetrics GetScriptExecutionMetrics() const
Definition: validation.h:559
uint32_t nFlags
Definition: validation.h:531
TxSigCheckLimiter * pTxLimitSigChecks
Definition: validation.h:536
ScriptExecutionMetrics metrics
Definition: validation.h:534
CTxOut m_tx_out
Definition: validation.h:528
bool cacheStore
Definition: validation.h:532
ScriptError error
Definition: validation.h:533
PrecomputedTransactionData txdata
Definition: validation.h:535
const CTransaction * ptxTo
Definition: validation.h:529
unsigned int nIn
Definition: validation.h:530
CheckInputsLimiter * pBlockLimitSigChecks
Definition: validation.h:537
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:431
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:192
const std::vector< CTxOut > vout
Definition: transaction.h:207
unsigned int GetTotalSize() const
Get the total transaction size in bytes.
Definition: transaction.cpp:92
bool IsCoinBase() const
Definition: transaction.h:252
const std::vector< CTxIn > vin
Definition: transaction.h:206
const TxId GetId() const
Definition: transaction.h:240
An input of a transaction.
Definition: transaction.h:59
COutPoint prevout
Definition: transaction.h:61
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: mempool_entry.h:65
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:209
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:296
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:139
const int64_t m_max_size_bytes
Definition: txmempool.h:333
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:643
void clear()
Definition: txmempool.cpp:340
void SetLoadTried(bool load_tried)
Set whether or not we've made an attempt to load the mempool (regardless of whether the attempt was s...
Definition: txmempool.cpp:813
CScript scriptPubKey
Definition: transaction.h:131
Amount nValue
Definition: transaction.h:130
Restore the UTXO in a Coin at a given COutPoint.
Definition: undo.h:62
std::vector< Coin > vprevout
Definition: undo.h:65
VerifyDBResult VerifyDB(Chainstate &chainstate, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::Notifications & m_notifications
Definition: validation.h:618
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:695
std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for itself and all ancestors...
Definition: validation.h:827
bool IsBlockAvalancheFinalized(const CBlockIndex *pindex) const EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
Checks if a block is finalized by avalanche voting.
const std::optional< BlockHash > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
Definition: validation.h:812
CTxMemPool * GetMempool()
Definition: validation.h:843
void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mutex m_chainstate_mutex
The ChainState Mutex.
Definition: validation.h:701
void UnloadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void UpdateFlags(CBlockIndex *pindex, CBlockIndex *&pindexReset, F f, C fChild, AC fAncestorWasChanged) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:804
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
Definition: validation.h:857
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of a block on the utxo cache, ignoring that it may already have been applied.
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition: validation.h:863
bool ActivateBestChainStep(BlockValidationState &state, CBlockIndex *pindexMostWork, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, ConnectTrace &connectTrace, const avalanche::Processor *const avalanche=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Try to make some progress towards making pindexMostWork the active block.
bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update the chain tip based on database information, i.e.
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition: validation.h:860
int32_t nBlockReverseSequenceId
Decreasing counter (used by subsequent preciousblock calls).
Definition: validation.h:710
void UnparkBlockImpl(CBlockIndex *pindex, bool fClearChildren) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Chainstate(CTxMemPool *mempool, node::BlockManager &blockman, ChainstateManager &chainman, std::optional< BlockHash > from_snapshot_blockhash=std::nullopt)
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:837
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Mutex cs_avalancheFinalizedBlockIndex
Definition: validation.h:742
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(std::chrono::microsecond m_last_write)
Check warning conditions and do some notifications on new chain tip set.
Definition: validation.h:1157
void UnparkBlockAndChildren(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block and its descendants.
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:724
bool reliesOnAssumedValid()
Return true if this chainstate relies on blocks that are assumed-valid.
Definition: validation.h:816
void LoadMempool(const fs::path &load_path, fsbridge::FopenFn mockable_fopen_function=fsbridge::fopen)
Load the persisted mempool from disk.
arith_uint256 nLastPreciousChainwork
chainwork for the last block that preciousblock has been applied to.
Definition: validation.h:712
std::chrono::microseconds m_last_flush
Definition: validation.h:1158
bool DisconnectTip(BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain's tip.
bool UnwindBlock(BlockValidationState &state, CBlockIndex *pindex, bool invalidate) EXCLUSIVE_LOCKS_REQUIRED(m_chainstate_mutex
bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Mark a block as invalid.
bool ConnectTip(BlockValidationState &state, BlockPolicyValidationState &blockPolicyState, CBlockIndex *pindexNew, const std::shared_ptr< const CBlock > &pblock, ConnectTrace &connectTrace, DisconnectedBlockTransactions &disconnectpool, const avalanche::Processor *const avalanche=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Connect a new block to m_chain.
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:773
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:728
CRollingBloomFilter m_filterParkingPoliciesApplied
Filter to prevent parking a block due to block policies more than once.
Definition: validation.h:759
bool ReplayBlocks()
Replay blocks that aren't fully applied to the database.
bool AvalancheFinalizeBlock(CBlockIndex *pindex, avalanche::Processor &avalanche) EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
Mark a block as finalized by avalanche.
void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew, const FlatFilePos &pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove invalidity status from a block and its descendants.
void CheckBlockIndex()
Make various assertions about the state of the block index.
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view) EXCLUSIVE_LOCKS_REQUIRED(boo ConnectBlock)(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, BlockValidationOptions options, Amount *blockFees=nullptr, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of this block (with given index) on the UTXO set represented by coins.
Definition: validation.h:973
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:830
CBlockIndex const * m_best_fork_tip
Definition: validation.h:762
void PruneAndFlush()
Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned.
bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
Update the on-disk chain state.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:768
void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe, std::string leveldb_name="chainstate")
Initialize the CoinsViews UTXO set database management data structures.
CBlockIndex const * m_best_fork_base
Definition: validation.h:763
void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main
std::atomic< bool > m_cached_finished_ibd
Whether this chainstate is undergoing initial block download.
Definition: validation.h:720
void UnparkBlock(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block.
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex, avalanche::Processor *const avalanche=nullptr) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Mark a block as precious and reorganize.
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr, avalanche::Processor *const avalanche=nullptr, bool skip_checkblockindex=false) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Find the best known block, and make it the tip of the block chain.
void ClearAvalancheFinalizedBlock() EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
Clear avalanche finalization.
const CBlockIndex * FindForkInGlobalIndex(const CBlockLocator &locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block of this chain and a locator.
Definition: validation.cpp:122
std::atomic< int32_t > nBlockSequenceId
Every received block is assigned a unique and increasing identifier, so we know which one to give pri...
Definition: validation.h:708
CBlockIndex * FindMostWorkChain(std::vector< const CBlockIndex * > &blocksToReconcile, bool fAutoUnpark) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Return the tip of the chain with the most work in it, that isn't known to be invalid (it's however fa...
bool UpdateFlagsForBlock(CBlockIndex *pindexBase, CBlockIndex *pindex, F f) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool AcceptBlock(const std::shared_ptr< const CBlock > &pblock, BlockValidationState &state, bool fRequested, const FlatFilePos *dbp, bool *fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Store a block on disk.
bool ParkBlock(BlockValidationState &state, CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Park a block.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1218
int64_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
Definition: validation.h:1381
const CChainParams & GetParams() const
Definition: validation.h:1312
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:1321
MempoolAcceptResult ProcessTransaction(const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the memory pool.
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:1385
bool AcceptBlockHeader(const CBlockHeader &block, BlockValidationState &state, CBlockIndex **ppindex, bool min_pow_checked, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
If a block header hasn't already been seen, call CheckBlockHeader on it, ensure that it doesn't desce...
bool ShouldCheckBlockIndex() const
Definition: validation.h:1318
const Config & GetConfig() const
Definition: validation.h:1310
const BlockHash & AssumedValidBlock() const
Definition: validation.h:1324
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block, avalanche::Processor *const avalanche=nullptr) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
std::optional< BlockHash > SnapshotBlockhash() const
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:1450
bool PopulateAndValidateSnapshot(Chainstate &snapshot_chainstate, AutoFile &coins_file, const node::SnapshotMetadata &metadata)
Internal helper for ActivateSnapshot().
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1431
bool ActivateSnapshot(AutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
Construct and activate a Chainstate on the basis of UTXO snapshot data.
bool IsSnapshotActive() const
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
const Options m_options
Definition: validation.h:1346
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
ChainstateManager(Options options, node::BlockManager::Options blockman_options)
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1395
std::set< CBlockIndex * > m_failed_blocks
In order to efficiently track invalidity of headers, we keep the set of blocks which we tried to conn...
Definition: validation.h:1371
kernel::Notifications & GetNotifications() const
Definition: validation.h:1327
const Consensus::Params & GetConsensus() const
Definition: validation.h:1315
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1350
Simple class for regulating resource usage during CheckInputScripts (and CScriptCheck),...
Definition: validation.h:382
bool consume_and_check(int consumed)
Definition: validation.h:389
A UTXO entry.
Definition: coins.h:28
uint32_t GetHeight() const
Definition: coins.h:45
bool IsCoinBase() const
Definition: coins.h:46
bool IsSpent() const
Definition: coins.h:47
CTxOut & GetTxOut()
Definition: coins.h:49
CoinsViews(DBParams db_params, CoinsViewOptions options)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
Definition: config.h:19
virtual const CChainParams & GetChainParams() const =0
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
std::vector< PerBlockConnectTrace > blocksConnected
std::vector< PerBlockConnectTrace > & GetBlocksConnected()
void BlockConnected(CBlockIndex *pindex, std::shared_ptr< const CBlock > pblock)
void updateMempoolForReorg(Chainstate &active_chainstate, bool fAddToMempool, CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Make mempool consistent after a reorg, by re-adding or recursively erasing disconnected block transac...
void addForBlock(const std::vector< CTransactionRef > &vtx, CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
void importMempool(CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
Different type to mark Mutex at global scope.
Definition: sync.h:144
static RCUPtr acquire(T *&ptrIn)
Acquire ownership of some pointer.
Definition: rcu.h:103
The script cache is a map using a key/value element, that caches the success of executing a specific ...
Definition: scriptcache.h:25
static TxSigCheckLimiter getDisabled()
Definition: validation.h:410
bool IsValid() const
Definition: validation.h:117
std::string GetRejectReason() const
Definition: validation.h:121
std::string GetDebugMessage() const
Definition: validation.h:122
bool Error(const std::string &reject_reason)
Definition: validation.h:110
bool Invalid(Result result, const std::string &reject_reason="", const std::string &debug_message="")
Definition: validation.h:99
bool IsError() const
Definition: validation.h:119
Result GetResult() const
Definition: validation.h:120
std::string ToString() const
Definition: validation.h:123
bool IsInvalid() const
Definition: validation.h:118
256-bit unsigned big integer.
std::string ToString() const
Definition: uint256.h:80
bool IsNull() const
Definition: uint256.h:32
std::string GetHex() const
Definition: uint256.cpp:16
double getdouble() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
A base class defining functions for notifying about certain kernel events.
virtual void headerTip(SynchronizationState state, int64_t height, int64_t timestamp, bool presync)
virtual void warning(const std::string &warning)
virtual void progress(const bilingual_str &title, int progress_percent, bool resume_possible)
virtual void blockTip(SynchronizationState state, CBlockIndex &index)
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:74
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
RecursiveMutex cs_LastBlockFile
Definition: blockstorage.h:142
void FindFilesToPrune(std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, int prune_height, bool is_ibd)
Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a us...
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
Calculate the block/rev files to delete based on height specified by user with RPC command pruneblock...
const CBlockIndex *GetFirstStoredBlock(const CBlockIndex &start_block) EXCLUSIVE_LOCKS_REQUIRED(bool m_have_pruned
Find the first block that is not pruned.
Definition: blockstorage.h:264
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool WriteUndoDataForBlock(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex &block) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePos SaveBlockToDisk(const CBlock &block, int nHeight, CChain &active_chain, const FlatFilePos *dbp)
Store block on disk.
Definition: blockstorage.h:231
bool LoadingBlocks() const
Definition: blockstorage.h:244
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex &index) const
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune) const
Actually unlink the specified files.
std::set< CBlockIndex * > m_dirty_blockindex
Dirty block index entries.
Definition: blockstorage.h:155
bool m_check_for_pruning
Global flag to indicate we should check to see if there are block/undo files that should be deleted.
Definition: blockstorage.h:150
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:235
std::vector< CBlockIndex * > GetAllBlockIndices() EXCLUSIVE_LOCKS_REQUIRED(std::multimap< CBlockIndex *, CBlockIndex * > m_blocks_unlinked
All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
Definition: blockstorage.h:182
void FlushBlockFile(bool fFinalize=false, bool finalize_undo=false)
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:21
uint64_t m_coins_count
The number of coins in the UTXO set contained in this snapshot.
Definition: utxo_snapshot.h:29
BlockHash m_base_blockhash
The hash of the block that reflects the tip of the chain for the UTXO set contained in this snapshot.
Definition: utxo_snapshot.h:25
256-bit opaque blob.
Definition: uint256.h:129
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
const Coin & AccessByTxid(const CCoinsViewCache &view, const TxId &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:397
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
Utility function to add all of a transaction's outputs to a cache.
Definition: coins.cpp:156
@ BLOCK_CHECKPOINT
the block failed to meet one of our checkpoints
@ BLOCK_HEADER_LOW_WORK
the block header may be on a too-little-work chain
@ BLOCK_INVALID_HEADER
invalid proof of work or time too old
@ BLOCK_CACHED_INVALID
this block was cached as being invalid and we didn't store the reason why
@ BLOCK_CONSENSUS
invalid by consensus rules (excluding any below reasons)
@ BLOCK_MISSING_PREV
We don't have the previous block the checked one is built on.
@ BLOCK_INVALID_PREV
A block this one builds on is invalid.
@ BLOCK_MUTATED
the block's data didn't match the data committed to by the PoW
@ BLOCK_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
@ TX_CHILD_BEFORE_PARENT
This tx outputs are already spent in the mempool.
@ TX_MEMPOOL_POLICY
violated mempool's fee/size/descendant/etc limits
@ TX_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
@ TX_DUPLICATE
Tx already in mempool or in the chain.
@ TX_INPUTS_NOT_STANDARD
inputs failed policy rules
@ TX_CONFLICT
Tx conflicts with another mempool tx, i.e.
@ TX_NOT_STANDARD
otherwise didn't meet our local policy rules
@ TX_NO_MEMPOOL
this node does not have a mempool so can't validate the transaction
@ TX_CONSENSUS
invalid by consensus rules
@ TX_RECONSIDERABLE
fails some policy, but might be acceptable if submitted in a (different) package
static constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE
Flags for nSequence and nLockTime locks.
Definition: consensus.h:38
static const uint64_t MAX_TX_SIZE
The maximum allowed size for a transaction, in bytes.
Definition: consensus.h:14
uint64_t GetMaxBlockSigChecksCount(uint64_t maxBlockSize)
Compute the maximum number of sigchecks that can be contained in a block given the MAXIMUM block size...
Definition: consensus.h:47
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::BuriedDeployment dep)
Determine if a deployment is active for the next block.
bool DeploymentActiveAt(const CBlockIndex &index, const Consensus::Params &params, Consensus::BuriedDeployment dep)
Determine if a deployment is active for this block.
DisconnectResult
volatile double sum
Definition: examples.cpp:10
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: fs_helpers.cpp:111
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, uint32_t flags, const BaseSignatureChecker &checker, ScriptExecutionMetrics &metricsOut, ScriptError *serror)
Execute an unlocking and locking script together.
std::map< int, const AssumeutxoData > MapAssumeutxo
Definition: chainparams.h:59
static void LoadExternalBlockFile(benchmark::Bench &bench)
The LoadExternalBlockFile() function is used during -reindex and -loadblock.
bool error(const char *fmt, const Args &...args)
Definition: logging.h:226
#define LogPrint(category,...)
Definition: logging.h:211
#define LogPrintf(...)
Definition: logging.h:207
unsigned int nHeight
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Compute the Merkle root of the transactions in a block.
Definition: merkle.cpp:69
@ AVALANCHE
Definition: logging.h:62
@ REINDEX
Definition: logging.h:51
@ VALIDATION
Definition: logging.h:61
@ PRUNE
Definition: logging.h:54
@ MEMPOOL
Definition: logging.h:42
@ BENCH
Definition: logging.h:44
bool CheckBlock(const CCheckpointData &data, int nHeight, const BlockHash &hash)
Returns true if block passes checkpoint checks.
Definition: checkpoints.cpp:11
@ DEPLOYMENT_DERSIG
Definition: params.h:23
@ DEPLOYMENT_P2SH
Definition: params.h:20
@ DEPLOYMENT_CSV
Definition: params.h:24
@ DEPLOYMENT_HEIGHTINCB
Definition: params.h:21
@ DEPLOYMENT_CLTV
Definition: params.h:22
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, Amount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts).
Definition: tx_verify.cpp:168
static bool exists(const path &p)
Definition: fs.h:102
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:142
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:142
std::function< FILE *(const fs::path &, const char *)> FopenFn
Definition: fs.h:198
Definition: common.cpp:29
static bool ComputeUTXOStats(CCoinsView *view, CCoinsStats &stats, T hash_obj, const std::function< void()> &interruption_point)
Calculate statistics about the unspent transaction output set.
Definition: coinstats.cpp:92
CoinStatsHashType
Definition: coinstats.h:23
bool LoadMempool(CTxMemPool &pool, const fs::path &load_path, Chainstate &active_chainstate, FopenFn mockable_fopen_function)
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
Definition: blockstorage.h:46
const fs::path SNAPSHOT_BLOCKHASH_FILENAME
The file in the snapshot chainstate dir which stores the base blockhash.
Definition: utxo_snapshot.h:46
bool WriteSnapshotBaseBlockhash(Chainstate &snapshot_chainstate)
std::optional< fs::path > FindSnapshotChainstateDir()
Return a path to the snapshot-based chainstate dir, if one exists.
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:60
std::optional< BlockHash > ReadSnapshotBaseBlockhash(const fs::path &chaindir)
static constexpr unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Definition: blockstorage.h:44
std::atomic_bool fReindex
bool WriteSnapshotBaseBlockhash(Chainstate &snapshot_chainstate) EXCLUSIVE_LOCKS_REQUIRED(std::optional< BlockHash > constexpr ReadSnapshotBaseBlockhash(const fs::path &chaindir) EXCLUSIVE_LOCKS_REQUIRED(std::string_view SNAPSHOT_CHAINSTATE_SUFFIX
Write out the blockhash of the snapshot base block that was used to construct this chainstate.
Definition: utxo_snapshot.h:61
bool Func(const std::string &str, Span< const char > &sp)
Parse a function call.
Definition: spanparsing.cpp:23
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:257
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:78
std::shared_ptr< Chain::Notifications > m_notifications
Definition: interfaces.cpp:446
bool IsChildWithParents(const Package &package)
Context-free check that a package is exactly one child and its parents; not all parents need to be pr...
Definition: packages.cpp:86
bool CheckPackage(const Package &txns, PackageValidationState &state)
Context-free package policy checks:
Definition: packages.cpp:14
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:40
@ PCKG_POLICY
The package itself is invalid (e.g. too many transactions).
@ PCKG_MEMPOOL_ERROR
Mempool logic error.
@ PCKG_TX
At least one tx is invalid.
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs, uint32_t flags)
Check transaction inputs to mitigate two potential denial-of-service attacks:
Definition: policy.cpp:145
bool IsStandardTx(const CTransaction &tx, const std::optional< unsigned > &max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate &dust_relay_fee, std::string &reason)
Check for standard transaction types.
Definition: policy.cpp:66
static constexpr uint32_t STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:91
static constexpr uint32_t STANDARD_LOCKTIME_VERIFY_FLAGS
Used as the flags parameter to sequence and nLocktime checks in non-consensus code.
Definition: policy.h:108
static constexpr uint32_t STANDARD_NOT_MANDATORY_VERIFY_FLAGS
For convenience, standard but not mandatory verify flags.
Definition: policy.h:101
bool CheckProofOfWork(const BlockHash &hash, uint32_t nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:91
uint32_t GetNextWorkRequired(const CBlockIndex *pindexPrev, const CBlockHeader *pblock, const CChainParams &chainParams)
Definition: pow.cpp:21
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
uint256 GetRandHash() noexcept
Definition: random.cpp:659
const char * prefix
Definition: rest.cpp:817
reverse_range< T > reverse_iterate(T &x)
std::string ScriptErrorString(const ScriptError serror)
ScriptError
Definition: script_error.h:11
@ SIGCHECKS_LIMIT_EXCEEDED
@ SCRIPT_VERIFY_P2SH
Definition: script_flags.h:16
@ SCRIPT_VERIFY_SIGPUSHONLY
Definition: script_flags.h:35
@ SCRIPT_VERIFY_LOW_S
Definition: script_flags.h:31
@ SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
Definition: script_flags.h:68
@ SCRIPT_ENABLE_REPLAY_PROTECTION
Definition: script_flags.h:89
@ SCRIPT_ENABLE_SCHNORR_MULTISIG
Definition: script_flags.h:97
@ SCRIPT_VERIFY_STRICTENC
Definition: script_flags.h:22
@ SCRIPT_VERIFY_NULLFAIL
Definition: script_flags.h:81
@ SCRIPT_VERIFY_DERSIG
Definition: script_flags.h:26
@ SCRIPT_ENFORCE_SIGCHECKS
Definition: script_flags.h:106
@ SCRIPT_VERIFY_CLEANSTACK
Definition: script_flags.h:63
@ SCRIPT_VERIFY_NONE
Definition: script_flags.h:12
@ SCRIPT_VERIFY_MINIMALDATA
Definition: script_flags.h:43
@ SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
Definition: script_flags.h:73
@ SCRIPT_ENABLE_SIGHASH_FORKID
Definition: script_flags.h:85
void AddKeyInScriptCache(ScriptCacheKey key, int nSigChecks)
Add an entry in the cache.
bool IsKeyInScriptCache(ScriptCacheKey key, bool erase, int &nSigChecksOut)
Check if a given key is in the cache, and if so, return its values.
CAddrDb db
Definition: main.cpp:35
@ SER_DISK
Definition: serialize.h:153
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1258
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:85
void StartShutdown()
Request shutdown of the application.
Definition: shutdown.cpp:55
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:86
Definition: amount.h:19
static constexpr Amount zero() noexcept
Definition: amount.h:32
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:46
const AssumeutxoHash hash_serialized
The expected hash of the deserialized UTXO set.
Definition: chainparams.h:48
const unsigned int nChainTx
Used to populate the nChainTx value, which is used during BlockManager::LoadBlockIndex().
Definition: chainparams.h:56
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
bool isValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: blockstatus.h:102
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:105
std::vector< BlockHash > vHave
Definition: block.h:106
Holds various statistics on transactions within a chain.
Definition: chainparams.h:67
double dTxRate
Definition: chainparams.h:70
int64_t nTime
Definition: chainparams.h:68
int64_t nTxCount
Definition: chainparams.h:69
User-controlled performance and debug options.
Definition: txdb.h:56
Parameters that influence chain consensus.
Definition: params.h:34
BlockHash BIP34Hash
Definition: params.h:41
int BIP34Height
Block height and hash at which BIP34 becomes active.
Definition: params.h:40
int nSubsidyHalvingInterval
Definition: params.h:36
BlockHash hashGenesisBlock
Definition: params.h:35
int64_t nPowTargetSpacing
Definition: params.h:78
int augustoActivationTime
Unix time used for MTP activation of 15 Nov 2024 12:00:00 UTC upgrade.
Definition: params.h:65
Application-specific storage settings.
Definition: dbwrapper.h:32
fs::path path
Location in the filesystem where leveldb data will be stored.
Definition: dbwrapper.h:34
int nFile
Definition: flatfile.h:15
unsigned int nPos
Definition: flatfile.h:16
bool IsNull() const
Definition: flatfile.h:40
int64_t time
Definition: mempool_entry.h:27
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:206
const ResultType m_result_type
Result type.
Definition: validation.h:217
@ VALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:245
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Definition: validation.h:250
static MempoolAcceptResult Success(int64_t vsize, Amount fees, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Constructor for success case.
Definition: validation.h:258
static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition: validation.h:268
std::chrono::time_point< NodeClock > time_point
Definition: time.h:19
Validation result for package mempool acceptance.
Definition: validation.h:309
std::shared_ptr< const CBlock > pblock
CBlockIndex * pindex
Precompute sighash midstate to avoid quadratic hashing.
Definition: transaction.h:325
const char * what() const override
A TxId is the identifier of a transaction.
Definition: txid.h:14
Bilingual messages:
Definition: translation.h:17
std::string original
Definition: translation.h:18
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
const std::function< NodeClock::time_point()> adjusted_time_callback
std::optional< bool > check_block_index
std::chrono::seconds max_tip_age
If the tip is older than this, the node is considered to be in initial block download.
#define AssertLockNotHeld(cs)
Definition: sync.h:163
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:55
#define NO_THREAD_SAFETY_ANALYSIS
Definition: threadsafety.h:58
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:105
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:101
int64_t GetTime()
Definition: time.cpp:109
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:113
#define LOG_TIME_MILLIS_WITH_CATEGORY(end_msg, log_category)
Definition: timer.h:97
#define LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE(end_msg, log_category)
Definition: timer.h:100
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
#define TRACE6(context, event, a, b, c, d, e, f)
Definition: trace.h:45
#define TRACE5(context, event, a, b, c, d, e)
Definition: trace.h:44
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
bool CheckRegularTransaction(const CTransaction &tx, TxValidationState &state)
Context-independent validity checks for coinbase and non-coinbase transactions.
Definition: tx_check.cpp:75
bool CheckCoinbase(const CTransaction &tx, TxValidationState &state)
Definition: tx_check.cpp:56
std::pair< int, int64_t > CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector< int > &prevHeights, const CBlockIndex &block)
Calculates the block height and previous block's median time past at which the transaction will be co...
Definition: tx_verify.cpp:78
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
Definition: tx_verify.cpp:150
bool SequenceLocks(const CTransaction &tx, int flags, std::vector< int > &prevHeights, const CBlockIndex &block)
Check if transaction is final per BIP 68 sequence numbers and can be included in a block.
Definition: tx_verify.cpp:161
bool ContextualCheckTransaction(const Consensus::Params &params, const CTransaction &tx, TxValidationState &state, int nHeight, int64_t nMedianTimePast)
Context dependent validity checks for non coinbase transactions.
Definition: tx_verify.cpp:41
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coins to signify they are only in the memory pool(since 0....
Definition: txmempool.h:45
uint256 uint256S(const char *str)
uint256 from const char *.
Definition: uint256.h:143
#define expect(bit)
static bool DeleteCoinsDBFromDisk(const fs::path &db_path, bool is_snapshot) EXCLUSIVE_LOCKS_REQUIRED(
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
static int64_t nTimeConnectTotal
GlobalMutex g_best_block_mutex
Definition: validation.cpp:113
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
std::condition_variable g_best_block_cv
Definition: validation.cpp:114
arith_uint256 CalculateHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the work on a given set of headers.
DisconnectResult ApplyBlockUndo(CBlockUndo &&blockUndo, const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view)
Undo a block from the block and the undoblock data.
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept, unsigned int heightOverride)
Try to add a transaction to the mempool.
#define MICRO
Definition: validation.cpp:90
static int64_t nBlocksTotal
static int64_t nTimePostConnect
static bool CheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, const Consensus::Params &params, BlockValidationOptions validationOptions)
Return true if the provided block header is valid.
static SynchronizationState GetSynchronizationState(bool init)
static void SnapshotUTXOHashBreakpoint()
static int64_t nTimeFlush
static bool ContextualCheckBlock(const CBlock &block, BlockValidationState &state, const ChainstateManager &chainman, const CBlockIndex *pindexPrev)
NOTE: This function is not currently invoked by ConnectBlock(), so we should consider upgrade issues ...
bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points)
Check if transaction will be BIP68 final in the next block to be created on top of tip.
Definition: validation.cpp:204
static uint32_t GetNextBlockScriptFlags(const CBlockIndex *pindex, const ChainstateManager &chainman)
const CBlockIndex * g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:115
bool HasValidProofOfWork(const std::vector< CBlockHeader > &headers, const Consensus::Params &consensusParams)
Check with the proof of work on each blockheader matches the value in nBits.
static constexpr std::chrono::hours DATABASE_FLUSH_INTERVAL
Time to wait between flushing chainstate to disk.
Definition: validation.cpp:96
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept)
Validate (and maybe submit) a package to the mempool.
static constexpr int PRUNE_LOCK_BUFFER
The number of blocks to keep below the deepest prune lock.
Definition: validation.cpp:111
static int64_t nTimeVerify
const AssumeutxoData * ExpectedAssumeutxo(const int height, const CChainParams &chainparams)
Return the expected assumeutxo value for a given height, if one exists.
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
static void LimitValidationInterfaceQueue() LOCKS_EXCLUDED(cs_main)
return CheckInputScripts(tx, state, view, flags, true, true, txdata, nSigChecksOut)
static bool CheckInputsFromMempoolAndCache(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const CTxMemPool &pool, const uint32_t flags, PrecomputedTransactionData &txdata, int &nSigChecksOut, CCoinsViewCache &coins_tip) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Checks to avoid mempool polluting consensus critical paths since cached signature and script validity...
void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Mark all the coins corresponding to a given transaction inputs as spent.
static int64_t nTimeTotal
static int64_t nTimeConnect
static bool NotifyHeaderTip(Chainstate &chainstate) LOCKS_EXCLUDED(cs_main)
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &params, BlockValidationOptions validationOptions)
Functions for validating blocks and updating the block tree.
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state)
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:97
static ChainstateManager::Options && Flatten(ChainstateManager::Options &&opts)
Apply default chain params to nullopt members.
DisconnectResult UndoCoinSpend(Coin &&undo, CCoinsViewCache &view, const COutPoint &out)
Restore the UTXO in a Coin at a given COutPoint.
static int64_t nTimeIndex
bool TestBlockValidity(BlockValidationState &state, const CChainParams &params, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, BlockValidationOptions validationOptions)
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
static void FlushSnapshotToDisk(CCoinsViewCache &coins_cache, bool snapshot_loaded)
std::optional< LockPoints > CalculateLockPointsAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx)
Calculate LockPoints required to check if transaction will be BIP68 final in the next block to be cre...
Definition: validation.cpp:180
AssertLockHeld(pool.cs)
bool AbortNode(BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage)
void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
static bool ContextualCheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, BlockManager &blockman, ChainstateManager &chainman, const CBlockIndex *pindexPrev, NodeClock::time_point now, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(
Context-dependent validity checks.
static int64_t nTimeForks
static int64_t nTimeCheck
#define MILLI
Definition: validation.cpp:91
static void UpdateTipLog(const CCoinsViewCache &coins_tip, const CBlockIndex *tip, const CChainParams &params, const std::string &func_name, const std::string &prefix) EXCLUSIVE_LOCKS_REQUIRED(
static constexpr std::chrono::hours DATABASE_WRITE_INTERVAL
Time to wait between writing blocks/block index to disk.
Definition: validation.cpp:94
static int64_t nTimeChainState
static CCheckQueue< CScriptCheck > scriptcheckqueue(128)
assert(!tx.IsCoinBase())
static int64_t nTimeReadFromDisk
static bool IsReplayProtectionEnabled(const Consensus::Params &params, int64_t nMedianTimePast)
Definition: validation.cpp:223
#define MIN_TRANSACTION_SIZE
Definition: validation.h:78
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition: validation.h:94
SnapshotCompletionResult
Definition: validation.h:1170
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:113
VerifyDBResult
Definition: validation.h:604
CoinsCacheSizeState
Definition: validation.h:673
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
FlushStateMode
Definition: validation.h:634
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:89
CMainSignals & GetMainSignals()
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11
void SetfLargeWorkInvalidChainFound(bool flag)
Definition: warnings.cpp:36
void SetfLargeWorkForkFound(bool flag)
Definition: warnings.cpp:26
bool GetfLargeWorkForkFound()
Definition: warnings.cpp:31