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