Bitcoin Core  23.99.0
P2P Digital Currency
validation.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <validation.h>
7 
8 #include <arith_uint256.h>
9 #include <chain.h>
10 #include <chainparams.h>
11 #include <checkqueue.h>
12 #include <consensus/amount.h>
13 #include <consensus/consensus.h>
14 #include <consensus/merkle.h>
15 #include <consensus/tx_check.h>
16 #include <consensus/tx_verify.h>
17 #include <consensus/validation.h>
18 #include <cuckoocache.h>
19 #include <flatfile.h>
20 #include <hash.h>
21 #include <kernel/coinstats.h>
22 #include <logging.h>
23 #include <logging/timer.h>
24 #include <node/blockstorage.h>
25 #include <node/interface_ui.h>
26 #include <node/utxo_snapshot.h>
27 #include <policy/policy.h>
28 #include <policy/rbf.h>
29 #include <policy/settings.h>
30 #include <pow.h>
31 #include <primitives/block.h>
32 #include <primitives/transaction.h>
33 #include <random.h>
34 #include <reverse_iterator.h>
35 #include <script/script.h>
36 #include <script/sigcache.h>
37 #include <shutdown.h>
38 #include <signet.h>
39 #include <tinyformat.h>
40 #include <txdb.h>
41 #include <txmempool.h>
42 #include <uint256.h>
43 #include <undo.h>
44 #include <util/check.h> // For NDEBUG compile time check
45 #include <util/hasher.h>
46 #include <util/moneystr.h>
47 #include <util/rbf.h>
48 #include <util/strencodings.h>
49 #include <util/system.h>
50 #include <util/trace.h>
51 #include <util/translation.h>
52 #include <validationinterface.h>
53 #include <warnings.h>
54 
55 #include <algorithm>
56 #include <deque>
57 #include <numeric>
58 #include <optional>
59 #include <string>
60 
64 
66 using node::BlockManager;
67 using node::BlockMap;
70 using node::fImporting;
71 using node::fPruneMode;
72 using node::fReindex;
73 using node::nPruneTarget;
80 
81 #define MICRO 0.000001
82 #define MILLI 0.001
83 
85 static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000;
87 static constexpr std::chrono::hours DATABASE_WRITE_INTERVAL{1};
89 static constexpr std::chrono::hours DATABASE_FLUSH_INTERVAL{24};
91 static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE{3};
92 const std::vector<std::string> CHECKLEVEL_DOC {
93  "level 0 reads the blocks from disk",
94  "level 1 verifies block validity",
95  "level 2 verifies undo data",
96  "level 3 checks disconnection of tip blocks",
97  "level 4 tries to reconnect the blocks",
98  "each level includes the checks of the previous levels",
99 };
105 static constexpr int PRUNE_LOCK_BUFFER{10};
106 
118 
120 std::condition_variable g_best_block_cv;
123 bool fRequireStandard = true;
124 bool fCheckBlockIndex = false;
127 
130 
132 {
134 
135  // Find the latest block common to locator and chain - we expect that
136  // locator.vHave is sorted descending by height.
137  for (const uint256& hash : locator.vHave) {
138  const CBlockIndex* pindex{m_blockman.LookupBlockIndex(hash)};
139  if (pindex) {
140  if (m_chain.Contains(pindex)) {
141  return pindex;
142  }
143  if (pindex->GetAncestor(m_chain.Height()) == m_chain.Tip()) {
144  return m_chain.Tip();
145  }
146  }
147  }
148  return m_chain.Genesis();
149 }
150 
151 bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
152  const CCoinsViewCache& inputs, unsigned int flags, bool cacheSigStore,
153  bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
154  std::vector<CScriptCheck>* pvChecks = nullptr)
156 
157 bool CheckFinalTxAtTip(const CBlockIndex* active_chain_tip, const CTransaction& tx)
158 {
160  assert(active_chain_tip); // TODO: Make active_chain_tip a reference
161 
162  // CheckFinalTxAtTip() uses active_chain_tip.Height()+1 to evaluate
163  // nLockTime because when IsFinalTx() is called within
164  // AcceptBlock(), the height of the block *being*
165  // evaluated is what is used. Thus if we want to know if a
166  // transaction can be part of the *next* block, we need to call
167  // IsFinalTx() with one more than active_chain_tip.Height().
168  const int nBlockHeight = active_chain_tip->nHeight + 1;
169 
170  // BIP113 requires that time-locked transactions have nLockTime set to
171  // less than the median time of the previous block they're contained in.
172  // When the next block is created its previous block will be the current
173  // chain tip, so we use that to calculate the median time passed to
174  // IsFinalTx().
175  const int64_t nBlockTime{active_chain_tip->GetMedianTimePast()};
176 
177  return IsFinalTx(tx, nBlockHeight, nBlockTime);
178 }
179 
181  const CCoinsView& coins_view,
182  const CTransaction& tx,
183  LockPoints* lp,
184  bool useExistingLockPoints)
185 {
186  assert(tip != nullptr);
187 
188  CBlockIndex index;
189  index.pprev = tip;
190  // CheckSequenceLocksAtTip() uses active_chainstate.m_chain.Height()+1 to evaluate
191  // height based locks because when SequenceLocks() is called within
192  // ConnectBlock(), the height of the block *being*
193  // evaluated is what is used.
194  // Thus if we want to know if a transaction can be part of the
195  // *next* block, we need to use one more than active_chainstate.m_chain.Height()
196  index.nHeight = tip->nHeight + 1;
197 
198  std::pair<int, int64_t> lockPair;
199  if (useExistingLockPoints) {
200  assert(lp);
201  lockPair.first = lp->height;
202  lockPair.second = lp->time;
203  }
204  else {
205  std::vector<int> prevheights;
206  prevheights.resize(tx.vin.size());
207  for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
208  const CTxIn& txin = tx.vin[txinIndex];
209  Coin coin;
210  if (!coins_view.GetCoin(txin.prevout, coin)) {
211  return error("%s: Missing input", __func__);
212  }
213  if (coin.nHeight == MEMPOOL_HEIGHT) {
214  // Assume all mempool transaction confirm in the next block
215  prevheights[txinIndex] = tip->nHeight + 1;
216  } else {
217  prevheights[txinIndex] = coin.nHeight;
218  }
219  }
220  lockPair = CalculateSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, prevheights, index);
221  if (lp) {
222  lp->height = lockPair.first;
223  lp->time = lockPair.second;
224  // Also store the hash of the block with the highest height of
225  // all the blocks which have sequence locked prevouts.
226  // This hash needs to still be on the chain
227  // for these LockPoint calculations to be valid
228  // Note: It is impossible to correctly calculate a maxInputBlock
229  // if any of the sequence locked inputs depend on unconfirmed txs,
230  // except in the special case where the relative lock time/height
231  // is 0, which is equivalent to no sequence lock. Since we assume
232  // input height of tip+1 for mempool txs and test the resulting
233  // lockPair from CalculateSequenceLocks against tip+1. We know
234  // EvaluateSequenceLocks will fail if there was a non-zero sequence
235  // lock on a mempool input, so we can use the return value of
236  // CheckSequenceLocksAtTip to indicate the LockPoints validity
237  int maxInputHeight = 0;
238  for (const int height : prevheights) {
239  // Can ignore mempool inputs since we'll fail if they had non-zero locks
240  if (height != tip->nHeight+1) {
241  maxInputHeight = std::max(maxInputHeight, height);
242  }
243  }
244  // tip->GetAncestor(maxInputHeight) should never return a nullptr
245  // because maxInputHeight is always less than the tip height.
246  // It would, however, be a bad bug to continue execution, since a
247  // LockPoints object with the maxInputBlock member set to nullptr
248  // signifies no relative lock time.
249  lp->maxInputBlock = Assert(tip->GetAncestor(maxInputHeight));
250  }
251  }
252  return EvaluateSequenceLocks(index, lockPair);
253 }
254 
255 // Returns the script flags which should be checked for a given block
256 static unsigned int GetBlockScriptFlags(const CBlockIndex& block_index, const ChainstateManager& chainman);
257 
258 static void LimitMempoolSize(CTxMemPool& pool, CCoinsViewCache& coins_cache, size_t limit, std::chrono::seconds age)
260 {
262  AssertLockHeld(pool.cs);
263  int expired = pool.Expire(GetTime<std::chrono::seconds>() - age);
264  if (expired != 0) {
265  LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
266  }
267 
268  std::vector<COutPoint> vNoSpendsRemaining;
269  pool.TrimToSize(limit, &vNoSpendsRemaining);
270  for (const COutPoint& removed : vNoSpendsRemaining)
271  coins_cache.Uncache(removed);
272 }
273 
275 {
277  if (active_chainstate.IsInitialBlockDownload())
278  return false;
279  if (active_chainstate.m_chain.Tip()->GetBlockTime() < count_seconds(GetTime<std::chrono::seconds>() - MAX_FEE_ESTIMATION_TIP_AGE))
280  return false;
281  if (active_chainstate.m_chain.Height() < active_chainstate.m_chainman.m_best_header->nHeight - 1) {
282  return false;
283  }
284  return true;
285 }
286 
288  DisconnectedBlockTransactions& disconnectpool,
289  bool fAddToMempool)
290 {
291  if (!m_mempool) return;
292 
295  std::vector<uint256> vHashUpdate;
296  // disconnectpool's insertion_order index sorts the entries from
297  // oldest to newest, but the oldest entry will be the last tx from the
298  // latest mined block that was disconnected.
299  // Iterate disconnectpool in reverse, so that we add transactions
300  // back to the mempool starting with the earliest transaction that had
301  // been previously seen in a block.
302  auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
303  while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
304  // ignore validation errors in resurrected transactions
305  if (!fAddToMempool || (*it)->IsCoinBase() ||
306  AcceptToMemoryPool(*this, *it, GetTime(),
307  /*bypass_limits=*/true, /*test_accept=*/false).m_result_type !=
309  // If the transaction doesn't make it in to the mempool, remove any
310  // transactions that depend on it (which would now be orphans).
312  } else if (m_mempool->exists(GenTxid::Txid((*it)->GetHash()))) {
313  vHashUpdate.push_back((*it)->GetHash());
314  }
315  ++it;
316  }
317  disconnectpool.queuedTx.clear();
318  // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
319  // no in-mempool children, which is generally not true when adding
320  // previously-confirmed transactions back to the mempool.
321  // UpdateTransactionsFromBlock finds descendants of any transactions in
322  // the disconnectpool that were added back and cleans up the mempool state.
323  const uint64_t ancestor_count_limit = gArgs.GetIntArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
324  const uint64_t ancestor_size_limit = gArgs.GetIntArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000;
325  m_mempool->UpdateTransactionsFromBlock(vHashUpdate, ancestor_size_limit, ancestor_count_limit);
326 
327  // Predicate to use for filtering transactions in removeForReorg.
328  // Checks whether the transaction is still final and, if it spends a coinbase output, mature.
329  // Also updates valid entries' cached LockPoints if needed.
330  // If false, the tx is still valid and its lockpoints are updated.
331  // If true, the tx would be invalid in the next block; remove this entry and all of its descendants.
332  const auto filter_final_and_mature = [this](CTxMemPool::txiter it)
336  const CTransaction& tx = it->GetTx();
337 
338  // The transaction must be final.
339  if (!CheckFinalTxAtTip(m_chain.Tip(), tx)) return true;
340  LockPoints lp = it->GetLockPoints();
341  const bool validLP{TestLockPointValidity(m_chain, lp)};
342  CCoinsViewMemPool view_mempool(&CoinsTip(), *m_mempool);
343  // CheckSequenceLocksAtTip checks if the transaction will be final in the next block to be
344  // created on top of the new chain. We use useExistingLockPoints=false so that, instead of
345  // using the information in lp (which might now refer to a block that no longer exists in
346  // the chain), it will update lp to contain LockPoints relevant to the new chain.
347  if (!CheckSequenceLocksAtTip(m_chain.Tip(), view_mempool, tx, &lp, validLP)) {
348  // If CheckSequenceLocksAtTip fails, remove the tx and don't depend on the LockPoints.
349  return true;
350  } else if (!validLP) {
351  // If CheckSequenceLocksAtTip succeeded, it also updated the LockPoints.
352  // Now update the mempool entry lockpoints as well.
353  m_mempool->mapTx.modify(it, [&lp](CTxMemPoolEntry& e) { e.UpdateLockPoints(lp); });
354  }
355 
356  // If the transaction spends any coinbase outputs, it must be mature.
357  if (it->GetSpendsCoinbase()) {
358  for (const CTxIn& txin : tx.vin) {
359  auto it2 = m_mempool->mapTx.find(txin.prevout.hash);
360  if (it2 != m_mempool->mapTx.end())
361  continue;
362  const Coin& coin{CoinsTip().AccessCoin(txin.prevout)};
363  assert(!coin.IsSpent());
364  const auto mempool_spend_height{m_chain.Tip()->nHeight + 1};
365  if (coin.IsCoinBase() && mempool_spend_height - coin.nHeight < COINBASE_MATURITY) {
366  return true;
367  }
368  }
369  }
370  // Transaction is still valid and cached LockPoints are updated.
371  return false;
372  };
373 
374  // We also need to remove any now-immature transactions
375  m_mempool->removeForReorg(m_chain, filter_final_and_mature);
376  // Re-limit mempool size, in case we added any transactions
378  *m_mempool,
379  this->CoinsTip(),
380  gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000,
381  std::chrono::hours{gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
382 }
383 
390  const CCoinsViewCache& view, const CTxMemPool& pool,
391  unsigned int flags, PrecomputedTransactionData& txdata, CCoinsViewCache& coins_tip)
393 {
395  AssertLockHeld(pool.cs);
396 
397  assert(!tx.IsCoinBase());
398  for (const CTxIn& txin : tx.vin) {
399  const Coin& coin = view.AccessCoin(txin.prevout);
400 
401  // This coin was checked in PreChecks and MemPoolAccept
402  // has been holding cs_main since then.
403  Assume(!coin.IsSpent());
404  if (coin.IsSpent()) return false;
405 
406  // If the Coin is available, there are 2 possibilities:
407  // it is available in our current ChainstateActive UTXO set,
408  // or it's a UTXO provided by a transaction in our mempool.
409  // Ensure the scriptPubKeys in Coins from CoinsView are correct.
410  const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
411  if (txFrom) {
412  assert(txFrom->GetHash() == txin.prevout.hash);
413  assert(txFrom->vout.size() > txin.prevout.n);
414  assert(txFrom->vout[txin.prevout.n] == coin.out);
415  } else {
416  const Coin& coinFromUTXOSet = coins_tip.AccessCoin(txin.prevout);
417  assert(!coinFromUTXOSet.IsSpent());
418  assert(coinFromUTXOSet.out == coin.out);
419  }
420  }
421 
422  // Call CheckInputScripts() to cache signature and script validity against current tip consensus rules.
423  return CheckInputScripts(tx, state, view, flags, /* cacheSigStore= */ true, /* cacheFullScriptStore= */ true, txdata);
424 }
425 
426 namespace {
427 
428 class MemPoolAccept
429 {
430 public:
431  explicit MemPoolAccept(CTxMemPool& mempool, CChainState& active_chainstate) : m_pool(mempool), m_view(&m_dummy), m_viewmempool(&active_chainstate.CoinsTip(), m_pool), m_active_chainstate(active_chainstate),
432  m_limit_ancestors(gArgs.GetIntArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT)),
433  m_limit_ancestor_size(gArgs.GetIntArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000),
434  m_limit_descendants(gArgs.GetIntArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT)),
435  m_limit_descendant_size(gArgs.GetIntArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000) {
436  }
437 
438  // We put the arguments we're handed into a struct, so we can pass them
439  // around easier.
440  struct ATMPArgs {
441  const CChainParams& m_chainparams;
442  const int64_t m_accept_time;
443  const bool m_bypass_limits;
444  /*
445  * Return any outpoints which were not previously present in the coins
446  * cache, but were added as a result of validating the tx for mempool
447  * acceptance. This allows the caller to optionally remove the cache
448  * additions if the associated transaction ends up being rejected by
449  * the mempool.
450  */
451  std::vector<COutPoint>& m_coins_to_uncache;
452  const bool m_test_accept;
456  const bool m_allow_bip125_replacement;
461  const bool m_package_submission;
465  const bool m_package_feerates;
466 
468  static ATMPArgs SingleAccept(const CChainParams& chainparams, int64_t accept_time,
469  bool bypass_limits, std::vector<COutPoint>& coins_to_uncache,
470  bool test_accept) {
471  return ATMPArgs{/* m_chainparams */ chainparams,
472  /* m_accept_time */ accept_time,
473  /* m_bypass_limits */ bypass_limits,
474  /* m_coins_to_uncache */ coins_to_uncache,
475  /* m_test_accept */ test_accept,
476  /* m_allow_bip125_replacement */ true,
477  /* m_package_submission */ false,
478  /* m_package_feerates */ false,
479  };
480  }
481 
483  static ATMPArgs PackageTestAccept(const CChainParams& chainparams, int64_t accept_time,
484  std::vector<COutPoint>& coins_to_uncache) {
485  return ATMPArgs{/* m_chainparams */ chainparams,
486  /* m_accept_time */ accept_time,
487  /* m_bypass_limits */ false,
488  /* m_coins_to_uncache */ coins_to_uncache,
489  /* m_test_accept */ true,
490  /* m_allow_bip125_replacement */ false,
491  /* m_package_submission */ false, // not submitting to mempool
492  /* m_package_feerates */ false,
493  };
494  }
495 
497  static ATMPArgs PackageChildWithParents(const CChainParams& chainparams, int64_t accept_time,
498  std::vector<COutPoint>& coins_to_uncache) {
499  return ATMPArgs{/* m_chainparams */ chainparams,
500  /* m_accept_time */ accept_time,
501  /* m_bypass_limits */ false,
502  /* m_coins_to_uncache */ coins_to_uncache,
503  /* m_test_accept */ false,
504  /* m_allow_bip125_replacement */ false,
505  /* m_package_submission */ true,
506  /* m_package_feerates */ true,
507  };
508  }
509 
511  static ATMPArgs SingleInPackageAccept(const ATMPArgs& package_args) {
512  return ATMPArgs{/* m_chainparams */ package_args.m_chainparams,
513  /* m_accept_time */ package_args.m_accept_time,
514  /* m_bypass_limits */ false,
515  /* m_coins_to_uncache */ package_args.m_coins_to_uncache,
516  /* m_test_accept */ package_args.m_test_accept,
517  /* m_allow_bip125_replacement */ true,
518  /* m_package_submission */ false,
519  /* m_package_feerates */ false, // only 1 transaction
520  };
521  }
522 
523  private:
524  // Private ctor to avoid exposing details to clients and allowing the possibility of
525  // mixing up the order of the arguments. Use static functions above instead.
526  ATMPArgs(const CChainParams& chainparams,
527  int64_t accept_time,
528  bool bypass_limits,
529  std::vector<COutPoint>& coins_to_uncache,
530  bool test_accept,
531  bool allow_bip125_replacement,
532  bool package_submission,
533  bool package_feerates)
534  : m_chainparams{chainparams},
535  m_accept_time{accept_time},
536  m_bypass_limits{bypass_limits},
537  m_coins_to_uncache{coins_to_uncache},
538  m_test_accept{test_accept},
539  m_allow_bip125_replacement{allow_bip125_replacement},
540  m_package_submission{package_submission},
541  m_package_feerates{package_feerates}
542  {
543  }
544  };
545 
546  // Single transaction acceptance
547  MempoolAcceptResult AcceptSingleTransaction(const CTransactionRef& ptx, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
548 
554  PackageMempoolAcceptResult AcceptMultipleTransactions(const std::vector<CTransactionRef>& txns, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
555 
560  PackageMempoolAcceptResult AcceptPackage(const Package& package, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
561 
562 private:
563  // All the intermediate state that gets passed between the various levels
564  // of checking a given transaction.
565  struct Workspace {
566  explicit Workspace(const CTransactionRef& ptx) : m_ptx(ptx), m_hash(ptx->GetHash()) {}
568  std::set<uint256> m_conflicts;
570  CTxMemPool::setEntries m_iters_conflicting;
573  CTxMemPool::setEntries m_all_conflicting;
575  CTxMemPool::setEntries m_ancestors;
578  std::unique_ptr<CTxMemPoolEntry> m_entry;
582  std::list<CTransactionRef> m_replaced_transactions;
583 
586  int64_t m_vsize;
588  CAmount m_base_fees;
590  CAmount m_modified_fees;
592  CAmount m_conflicting_fees{0};
594  size_t m_conflicting_size{0};
595 
596  const CTransactionRef& m_ptx;
598  const uint256& m_hash;
599  TxValidationState m_state;
602  PrecomputedTransactionData m_precomputed_txdata;
603  };
604 
605  // Run the policy checks on a given transaction, excluding any script checks.
606  // Looks up inputs, calculates feerate, considers replacement, evaluates
607  // package limits, etc. As this function can be invoked for "free" by a peer,
608  // only tests that are fast should be done here (to avoid CPU DoS).
609  bool PreChecks(ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
610 
611  // Run checks for mempool replace-by-fee.
612  bool ReplacementChecks(Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
613 
614  // Enforce package mempool ancestor/descendant limits (distinct from individual
615  // ancestor/descendant limits done in PreChecks).
616  bool PackageMempoolChecks(const std::vector<CTransactionRef>& txns,
617  PackageValidationState& package_state) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
618 
619  // Run the script checks using our policy flags. As this can be slow, we should
620  // only invoke this on transactions that have otherwise passed policy checks.
621  bool PolicyScriptChecks(const ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
622 
623  // Re-run the script checks, using consensus flags, and try to cache the
624  // result in the scriptcache. This should be done after
625  // PolicyScriptChecks(). This requires that all inputs either be in our
626  // utxo set or in the mempool.
627  bool ConsensusScriptChecks(const ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
628 
629  // Try to add the transaction to the mempool, removing any conflicts first.
630  // Returns true if the transaction is in the mempool after any size
631  // limiting is performed, false otherwise.
632  bool Finalize(const ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
633 
634  // Submit all transactions to the mempool and call ConsensusScriptChecks to add to the script
635  // cache - should only be called after successful validation of all transactions in the package.
636  // The package may end up partially-submitted after size limiting; returns true if all
637  // transactions are successfully added to the mempool, false otherwise.
638  bool SubmitPackage(const ATMPArgs& args, std::vector<Workspace>& workspaces, PackageValidationState& package_state,
639  std::map<const uint256, const MempoolAcceptResult>& results)
640  EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
641 
642  // Compare a package's feerate against minimum allowed.
643  bool CheckFeeRate(size_t package_size, CAmount package_fee, TxValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_pool.cs)
644  {
646  AssertLockHeld(m_pool.cs);
647  CAmount mempoolRejectFee = m_pool.GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(package_size);
648  if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) {
649  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool min fee not met", strprintf("%d < %d", package_fee, mempoolRejectFee));
650  }
651 
652  if (package_fee < ::minRelayTxFee.GetFee(package_size)) {
653  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "min relay fee not met", strprintf("%d < %d", package_fee, ::minRelayTxFee.GetFee(package_size)));
654  }
655  return true;
656  }
657 
658 private:
659  CTxMemPool& m_pool;
660  CCoinsViewCache m_view;
661  CCoinsViewMemPool m_viewmempool;
662  CCoinsView m_dummy;
663 
664  CChainState& m_active_chainstate;
665 
666  // The package limits in effect at the time of invocation.
667  const size_t m_limit_ancestors;
668  const size_t m_limit_ancestor_size;
669  // These may be modified while evaluating a transaction (eg to account for
670  // in-mempool conflicts; see below).
671  size_t m_limit_descendants;
672  size_t m_limit_descendant_size;
673 
675  bool m_rbf{false};
676 };
677 
678 bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
679 {
681  AssertLockHeld(m_pool.cs);
682  const CTransactionRef& ptx = ws.m_ptx;
683  const CTransaction& tx = *ws.m_ptx;
684  const uint256& hash = ws.m_hash;
685 
686  // Copy/alias what we need out of args
687  const int64_t nAcceptTime = args.m_accept_time;
688  const bool bypass_limits = args.m_bypass_limits;
689  std::vector<COutPoint>& coins_to_uncache = args.m_coins_to_uncache;
690 
691  // Alias what we need out of ws
692  TxValidationState& state = ws.m_state;
693  std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
694 
695  if (!CheckTransaction(tx, state)) {
696  return false; // state filled in by CheckTransaction
697  }
698 
699  // Coinbase is only valid in a block, not as a loose transaction
700  if (tx.IsCoinBase())
701  return state.Invalid(TxValidationResult::TX_CONSENSUS, "coinbase");
702 
703  // Rather not work on nonstandard transactions (unless -testnet/-regtest)
704  std::string reason;
705  if (fRequireStandard && !IsStandardTx(tx, reason))
706  return state.Invalid(TxValidationResult::TX_NOT_STANDARD, reason);
707 
708  // Do not work on transactions that are too small.
709  // A transaction with 1 segwit input and 1 P2WPHK output has non-witness size of 82 bytes.
710  // Transactions smaller than this are not relayed to mitigate CVE-2017-12842 by not relaying
711  // 64-byte transactions.
713  return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "tx-size-small");
714 
715  // Only accept nLockTime-using transactions that can be mined in the next
716  // block; we don't want our mempool filled up with transactions that can't
717  // be mined yet.
718  if (!CheckFinalTxAtTip(m_active_chainstate.m_chain.Tip(), tx)) {
719  return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-final");
720  }
721 
722  if (m_pool.exists(GenTxid::Wtxid(tx.GetWitnessHash()))) {
723  // Exact transaction already exists in the mempool.
724  return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-in-mempool");
725  } else if (m_pool.exists(GenTxid::Txid(tx.GetHash()))) {
726  // Transaction with the same non-witness data but different witness (same txid, different
727  // wtxid) already exists in the mempool.
728  return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-same-nonwitness-data-in-mempool");
729  }
730 
731  // Check for conflicts with in-memory transactions
732  for (const CTxIn &txin : tx.vin)
733  {
734  const CTransaction* ptxConflicting = m_pool.GetConflictTx(txin.prevout);
735  if (ptxConflicting) {
736  if (!args.m_allow_bip125_replacement) {
737  // Transaction conflicts with a mempool tx, but we're not allowing replacements.
738  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "bip125-replacement-disallowed");
739  }
740  if (!ws.m_conflicts.count(ptxConflicting->GetHash()))
741  {
742  // Transactions that don't explicitly signal replaceability are
743  // *not* replaceable with the current logic, even if one of their
744  // unconfirmed ancestors signals replaceability. This diverges
745  // from BIP125's inherited signaling description (see CVE-2021-31876).
746  // Applications relying on first-seen mempool behavior should
747  // check all unconfirmed ancestors; otherwise an opt-in ancestor
748  // might be replaced, causing removal of this descendant.
749  if (!SignalsOptInRBF(*ptxConflicting)) {
750  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "txn-mempool-conflict");
751  }
752 
753  ws.m_conflicts.insert(ptxConflicting->GetHash());
754  }
755  }
756  }
757 
758  LockPoints lp;
759  m_view.SetBackend(m_viewmempool);
760 
761  const CCoinsViewCache& coins_cache = m_active_chainstate.CoinsTip();
762  // do all inputs exist?
763  for (const CTxIn& txin : tx.vin) {
764  if (!coins_cache.HaveCoinInCache(txin.prevout)) {
765  coins_to_uncache.push_back(txin.prevout);
766  }
767 
768  // Note: this call may add txin.prevout to the coins cache
769  // (coins_cache.cacheCoins) by way of FetchCoin(). It should be removed
770  // later (via coins_to_uncache) if this tx turns out to be invalid.
771  if (!m_view.HaveCoin(txin.prevout)) {
772  // Are inputs missing because we already have the tx?
773  for (size_t out = 0; out < tx.vout.size(); out++) {
774  // Optimistically just do efficient check of cache for outputs
775  if (coins_cache.HaveCoinInCache(COutPoint(hash, out))) {
776  return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-known");
777  }
778  }
779  // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
780  return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent");
781  }
782  }
783 
784  // This is const, but calls into the back end CoinsViews. The CCoinsViewDB at the bottom of the
785  // hierarchy brings the best block into scope. See CCoinsViewDB::GetBestBlock().
786  m_view.GetBestBlock();
787 
788  // we have all inputs cached now, so switch back to dummy (to protect
789  // against bugs where we pull more inputs from disk that miss being added
790  // to coins_to_uncache)
791  m_view.SetBackend(m_dummy);
792 
793  assert(m_active_chainstate.m_blockman.LookupBlockIndex(m_view.GetBestBlock()) == m_active_chainstate.m_chain.Tip());
794 
795  // Only accept BIP68 sequence locked transactions that can be mined in the next
796  // block; we don't want our mempool filled up with transactions that can't
797  // be mined yet.
798  // Pass in m_view which has all of the relevant inputs cached. Note that, since m_view's
799  // backend was removed, it no longer pulls coins from the mempool.
800  if (!CheckSequenceLocksAtTip(m_active_chainstate.m_chain.Tip(), m_view, tx, &lp)) {
801  return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-BIP68-final");
802  }
803 
804  // The mempool holds txs for the next block, so pass height+1 to CheckTxInputs
805  if (!Consensus::CheckTxInputs(tx, state, m_view, m_active_chainstate.m_chain.Height() + 1, ws.m_base_fees)) {
806  return false; // state filled in by CheckTxInputs
807  }
808 
809  if (fRequireStandard && !AreInputsStandard(tx, m_view)) {
810  return state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs");
811  }
812 
813  // Check for non-standard witnesses.
814  if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, m_view))
815  return state.Invalid(TxValidationResult::TX_WITNESS_MUTATED, "bad-witness-nonstandard");
816 
817  int64_t nSigOpsCost = GetTransactionSigOpCost(tx, m_view, STANDARD_SCRIPT_VERIFY_FLAGS);
818 
819  // ws.m_modified_fees includes any fee deltas from PrioritiseTransaction
820  ws.m_modified_fees = ws.m_base_fees;
821  m_pool.ApplyDelta(hash, ws.m_modified_fees);
822 
823  // Keep track of transactions that spend a coinbase, which we re-scan
824  // during reorgs to ensure COINBASE_MATURITY is still met.
825  bool fSpendsCoinbase = false;
826  for (const CTxIn &txin : tx.vin) {
827  const Coin &coin = m_view.AccessCoin(txin.prevout);
828  if (coin.IsCoinBase()) {
829  fSpendsCoinbase = true;
830  break;
831  }
832  }
833 
834  entry.reset(new CTxMemPoolEntry(ptx, ws.m_base_fees, nAcceptTime, m_active_chainstate.m_chain.Height(),
835  fSpendsCoinbase, nSigOpsCost, lp));
836  ws.m_vsize = entry->GetTxSize();
837 
838  if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
839  return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "bad-txns-too-many-sigops",
840  strprintf("%d", nSigOpsCost));
841 
842  // No individual transactions are allowed below minRelayTxFee and mempool min fee except from
843  // disconnected blocks and transactions in a package. Package transactions will be checked using
844  // package feerate later.
845  if (!bypass_limits && !args.m_package_feerates && !CheckFeeRate(ws.m_vsize, ws.m_modified_fees, state)) return false;
846 
847  ws.m_iters_conflicting = m_pool.GetIterSet(ws.m_conflicts);
848  // Calculate in-mempool ancestors, up to a limit.
849  if (ws.m_conflicts.size() == 1) {
850  // In general, when we receive an RBF transaction with mempool conflicts, we want to know whether we
851  // would meet the chain limits after the conflicts have been removed. However, there isn't a practical
852  // way to do this short of calculating the ancestor and descendant sets with an overlay cache of
853  // changed mempool entries. Due to both implementation and runtime complexity concerns, this isn't
854  // very realistic, thus we only ensure a limited set of transactions are RBF'able despite mempool
855  // conflicts here. Importantly, we need to ensure that some transactions which were accepted using
856  // the below carve-out are able to be RBF'ed, without impacting the security the carve-out provides
857  // for off-chain contract systems (see link in the comment below).
858  //
859  // Specifically, the subset of RBF transactions which we allow despite chain limits are those which
860  // conflict directly with exactly one other transaction (but may evict children of said transaction),
861  // and which are not adding any new mempool dependencies. Note that the "no new mempool dependencies"
862  // check is accomplished later, so we don't bother doing anything about it here, but if BIP 125 is
863  // amended, we may need to move that check to here instead of removing it wholesale.
864  //
865  // Such transactions are clearly not merging any existing packages, so we are only concerned with
866  // ensuring that (a) no package is growing past the package size (not count) limits and (b) we are
867  // not allowing something to effectively use the (below) carve-out spot when it shouldn't be allowed
868  // to.
869  //
870  // To check these we first check if we meet the RBF criteria, above, and increment the descendant
871  // limits by the direct conflict and its descendants (as these are recalculated in
872  // CalculateMempoolAncestors by assuming the new transaction being added is a new descendant, with no
873  // removals, of each parent's existing dependent set). The ancestor count limits are unmodified (as
874  // the ancestor limits should be the same for both our new transaction and any conflicts).
875  // We don't bother incrementing m_limit_descendants by the full removal count as that limit never comes
876  // into force here (as we're only adding a single transaction).
877  assert(ws.m_iters_conflicting.size() == 1);
878  CTxMemPool::txiter conflict = *ws.m_iters_conflicting.begin();
879 
880  m_limit_descendants += 1;
881  m_limit_descendant_size += conflict->GetSizeWithDescendants();
882  }
883 
884  std::string errString;
885  if (!m_pool.CalculateMemPoolAncestors(*entry, ws.m_ancestors, m_limit_ancestors, m_limit_ancestor_size, m_limit_descendants, m_limit_descendant_size, errString)) {
886  ws.m_ancestors.clear();
887  // If CalculateMemPoolAncestors fails second time, we want the original error string.
888  std::string dummy_err_string;
889  // Contracting/payment channels CPFP carve-out:
890  // If the new transaction is relatively small (up to 40k weight)
891  // and has at most one ancestor (ie ancestor limit of 2, including
892  // the new transaction), allow it if its parent has exactly the
893  // descendant limit descendants.
894  //
895  // This allows protocols which rely on distrusting counterparties
896  // being able to broadcast descendants of an unconfirmed transaction
897  // to be secure by simply only having two immediately-spendable
898  // outputs - one for each counterparty. For more info on the uses for
899  // this, see https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html
900  if (ws.m_vsize > EXTRA_DESCENDANT_TX_SIZE_LIMIT ||
901  !m_pool.CalculateMemPoolAncestors(*entry, ws.m_ancestors, 2, m_limit_ancestor_size, m_limit_descendants + 1, m_limit_descendant_size + EXTRA_DESCENDANT_TX_SIZE_LIMIT, dummy_err_string)) {
902  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too-long-mempool-chain", errString);
903  }
904  }
905 
906  // A transaction that spends outputs that would be replaced by it is invalid. Now
907  // that we have the set of all ancestors we can detect this
908  // pathological case by making sure ws.m_conflicts and ws.m_ancestors don't
909  // intersect.
910  if (const auto err_string{EntriesAndTxidsDisjoint(ws.m_ancestors, ws.m_conflicts, hash)}) {
911  // We classify this as a consensus error because a transaction depending on something it
912  // conflicts with would be inconsistent.
913  return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-spends-conflicting-tx", *err_string);
914  }
915 
916  m_rbf = !ws.m_conflicts.empty();
917  return true;
918 }
919 
920 bool MemPoolAccept::ReplacementChecks(Workspace& ws)
921 {
923  AssertLockHeld(m_pool.cs);
924 
925  const CTransaction& tx = *ws.m_ptx;
926  const uint256& hash = ws.m_hash;
927  TxValidationState& state = ws.m_state;
928 
929  CFeeRate newFeeRate(ws.m_modified_fees, ws.m_vsize);
930  // The replacement transaction must have a higher feerate than its direct conflicts.
931  // - The motivation for this check is to ensure that the replacement transaction is preferable for
932  // block-inclusion, compared to what would be removed from the mempool.
933  // - This logic predates ancestor feerate-based transaction selection, which is why it doesn't
934  // consider feerates of descendants.
935  // - Note: Ancestor feerate-based transaction selection has made this comparison insufficient to
936  // guarantee that this is incentive-compatible for miners, because it is possible for a
937  // descendant transaction of a direct conflict to pay a higher feerate than the transaction that
938  // might replace them, under these rules.
939  if (const auto err_string{PaysMoreThanConflicts(ws.m_iters_conflicting, newFeeRate, hash)}) {
940  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee", *err_string);
941  }
942 
943  // Calculate all conflicting entries and enforce BIP125 Rule #5.
944  if (const auto err_string{GetEntriesForConflicts(tx, m_pool, ws.m_iters_conflicting, ws.m_all_conflicting)}) {
946  "too many potential replacements", *err_string);
947  }
948  // Enforce BIP125 Rule #2.
949  if (const auto err_string{HasNoNewUnconfirmed(tx, m_pool, ws.m_iters_conflicting)}) {
951  "replacement-adds-unconfirmed", *err_string);
952  }
953  // Check if it's economically rational to mine this transaction rather than the ones it
954  // replaces and pays for its own relay fees. Enforce BIP125 Rules #3 and #4.
955  for (CTxMemPool::txiter it : ws.m_all_conflicting) {
956  ws.m_conflicting_fees += it->GetModifiedFee();
957  ws.m_conflicting_size += it->GetTxSize();
958  }
959  if (const auto err_string{PaysForRBF(ws.m_conflicting_fees, ws.m_modified_fees, ws.m_vsize,
960  ::incrementalRelayFee, hash)}) {
961  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee", *err_string);
962  }
963  return true;
964 }
965 
966 bool MemPoolAccept::PackageMempoolChecks(const std::vector<CTransactionRef>& txns,
967  PackageValidationState& package_state)
968 {
970  AssertLockHeld(m_pool.cs);
971 
972  // CheckPackageLimits expects the package transactions to not already be in the mempool.
973  assert(std::all_of(txns.cbegin(), txns.cend(), [this](const auto& tx)
974  { return !m_pool.exists(GenTxid::Txid(tx->GetHash()));}));
975 
976  std::string err_string;
977  if (!m_pool.CheckPackageLimits(txns, m_limit_ancestors, m_limit_ancestor_size, m_limit_descendants,
978  m_limit_descendant_size, err_string)) {
979  // This is a package-wide error, separate from an individual transaction error.
980  return package_state.Invalid(PackageValidationResult::PCKG_POLICY, "package-mempool-limits", err_string);
981  }
982  return true;
983 }
984 
985 bool MemPoolAccept::PolicyScriptChecks(const ATMPArgs& args, Workspace& ws)
986 {
988  AssertLockHeld(m_pool.cs);
989  const CTransaction& tx = *ws.m_ptx;
990  TxValidationState& state = ws.m_state;
991 
992  constexpr unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
993 
994  // Check input scripts and signatures.
995  // This is done last to help prevent CPU exhaustion denial-of-service attacks.
996  if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, false, ws.m_precomputed_txdata)) {
997  // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
998  // need to turn both off, and compare against just turning off CLEANSTACK
999  // to see if the failure is specifically due to witness validation.
1000  TxValidationState state_dummy; // Want reported failures to be from first CheckInputScripts
1001  if (!tx.HasWitness() && CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, ws.m_precomputed_txdata) &&
1002  !CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, ws.m_precomputed_txdata)) {
1003  // Only the witness is missing, so the transaction itself may be fine.
1005  state.GetRejectReason(), state.GetDebugMessage());
1006  }
1007  return false; // state filled in by CheckInputScripts
1008  }
1009 
1010  return true;
1011 }
1012 
1013 bool MemPoolAccept::ConsensusScriptChecks(const ATMPArgs& args, Workspace& ws)
1014 {
1016  AssertLockHeld(m_pool.cs);
1017  const CTransaction& tx = *ws.m_ptx;
1018  const uint256& hash = ws.m_hash;
1019  TxValidationState& state = ws.m_state;
1020 
1021  // Check again against the current block tip's script verification
1022  // flags to cache our script execution flags. This is, of course,
1023  // useless if the next block has different script flags from the
1024  // previous one, but because the cache tracks script flags for us it
1025  // will auto-invalidate and we'll just have a few blocks of extra
1026  // misses on soft-fork activation.
1027  //
1028  // This is also useful in case of bugs in the standard flags that cause
1029  // transactions to pass as valid when they're actually invalid. For
1030  // instance the STRICTENC flag was incorrectly allowing certain
1031  // CHECKSIG NOT scripts to pass, even though they were invalid.
1032  //
1033  // There is a similar check in CreateNewBlock() to prevent creating
1034  // invalid blocks (using TestBlockValidity), however allowing such
1035  // transactions into the mempool can be exploited as a DoS attack.
1036  unsigned int currentBlockScriptVerifyFlags{GetBlockScriptFlags(*m_active_chainstate.m_chain.Tip(), m_active_chainstate.m_chainman)};
1037  if (!CheckInputsFromMempoolAndCache(tx, state, m_view, m_pool, currentBlockScriptVerifyFlags,
1038  ws.m_precomputed_txdata, m_active_chainstate.CoinsTip())) {
1039  LogPrintf("BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not STANDARD flags %s, %s\n", hash.ToString(), state.ToString());
1040  return Assume(false);
1041  }
1042 
1043  return true;
1044 }
1045 
1046 bool MemPoolAccept::Finalize(const ATMPArgs& args, Workspace& ws)
1047 {
1049  AssertLockHeld(m_pool.cs);
1050  const CTransaction& tx = *ws.m_ptx;
1051  const uint256& hash = ws.m_hash;
1052  TxValidationState& state = ws.m_state;
1053  const bool bypass_limits = args.m_bypass_limits;
1054 
1055  std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
1056 
1057  // Remove conflicting transactions from the mempool
1058  for (CTxMemPool::txiter it : ws.m_all_conflicting)
1059  {
1060  LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s additional fees, %d delta bytes\n",
1061  it->GetTx().GetHash().ToString(),
1062  hash.ToString(),
1063  FormatMoney(ws.m_modified_fees - ws.m_conflicting_fees),
1064  (int)entry->GetTxSize() - (int)ws.m_conflicting_size);
1065  ws.m_replaced_transactions.push_back(it->GetSharedTx());
1066  }
1067  m_pool.RemoveStaged(ws.m_all_conflicting, false, MemPoolRemovalReason::REPLACED);
1068 
1069  // This transaction should only count for fee estimation if:
1070  // - it's not being re-added during a reorg which bypasses typical mempool fee limits
1071  // - the node is not behind
1072  // - the transaction is not dependent on any other transactions in the mempool
1073  // - it's not part of a package. Since package relay is not currently supported, this
1074  // transaction has not necessarily been accepted to miners' mempools.
1075  bool validForFeeEstimation = !bypass_limits && !args.m_package_submission && IsCurrentForFeeEstimation(m_active_chainstate) && m_pool.HasNoInputsOf(tx);
1076 
1077  // Store transaction in memory
1078  m_pool.addUnchecked(*entry, ws.m_ancestors, validForFeeEstimation);
1079 
1080  // trim mempool and check if tx was trimmed
1081  // If we are validating a package, don't trim here because we could evict a previous transaction
1082  // in the package. LimitMempoolSize() should be called at the very end to make sure the mempool
1083  // is still within limits and package submission happens atomically.
1084  if (!args.m_package_submission && !bypass_limits) {
1085  LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip(), gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, std::chrono::hours{gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
1086  if (!m_pool.exists(GenTxid::Txid(hash)))
1087  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
1088  }
1089  return true;
1090 }
1091 
1092 bool MemPoolAccept::SubmitPackage(const ATMPArgs& args, std::vector<Workspace>& workspaces,
1093  PackageValidationState& package_state,
1094  std::map<const uint256, const MempoolAcceptResult>& results)
1095 {
1097  AssertLockHeld(m_pool.cs);
1098  // Sanity check: none of the transactions should be in the mempool, and none of the transactions
1099  // should have a same-txid-different-witness equivalent in the mempool.
1100  assert(std::all_of(workspaces.cbegin(), workspaces.cend(), [this](const auto& ws){
1101  return !m_pool.exists(GenTxid::Txid(ws.m_ptx->GetHash())); }));
1102 
1103  bool all_submitted = true;
1104  // ConsensusScriptChecks adds to the script cache and is therefore consensus-critical;
1105  // CheckInputsFromMempoolAndCache asserts that transactions only spend coins available from the
1106  // mempool or UTXO set. Submit each transaction to the mempool immediately after calling
1107  // ConsensusScriptChecks to make the outputs available for subsequent transactions.
1108  for (Workspace& ws : workspaces) {
1109  if (!ConsensusScriptChecks(args, ws)) {
1110  results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1111  // Since PolicyScriptChecks() passed, this should never fail.
1112  Assume(false);
1113  all_submitted = false;
1115  strprintf("BUG! PolicyScriptChecks succeeded but ConsensusScriptChecks failed: %s",
1116  ws.m_ptx->GetHash().ToString()));
1117  }
1118 
1119  // Re-calculate mempool ancestors to call addUnchecked(). They may have changed since the
1120  // last calculation done in PreChecks, since package ancestors have already been submitted.
1121  std::string unused_err_string;
1122  if(!m_pool.CalculateMemPoolAncestors(*ws.m_entry, ws.m_ancestors, m_limit_ancestors,
1123  m_limit_ancestor_size, m_limit_descendants,
1124  m_limit_descendant_size, unused_err_string)) {
1125  results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1126  // Since PreChecks() and PackageMempoolChecks() both enforce limits, this should never fail.
1127  Assume(false);
1128  all_submitted = false;
1130  strprintf("BUG! Mempool ancestors or descendants were underestimated: %s",
1131  ws.m_ptx->GetHash().ToString()));
1132  }
1133  // If we call LimitMempoolSize() for each individual Finalize(), the mempool will not take
1134  // the transaction's descendant feerate into account because it hasn't seen them yet. Also,
1135  // we risk evicting a transaction that a subsequent package transaction depends on. Instead,
1136  // allow the mempool to temporarily bypass limits, the maximum package size) while
1137  // submitting transactions individually and then trim at the very end.
1138  if (!Finalize(args, ws)) {
1139  results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1140  // Since LimitMempoolSize() won't be called, this should never fail.
1141  Assume(false);
1142  all_submitted = false;
1144  strprintf("BUG! Adding to mempool failed: %s", ws.m_ptx->GetHash().ToString()));
1145  }
1146  }
1147 
1148  // It may or may not be the case that all the transactions made it into the mempool. Regardless,
1149  // make sure we haven't exceeded max mempool size.
1150  LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip(),
1151  gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000,
1152  std::chrono::hours{gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
1153 
1154  // Find the wtxids of the transactions that made it into the mempool. Allow partial submission,
1155  // but don't report success unless they all made it into the mempool.
1156  for (Workspace& ws : workspaces) {
1157  if (m_pool.exists(GenTxid::Wtxid(ws.m_ptx->GetWitnessHash()))) {
1158  results.emplace(ws.m_ptx->GetWitnessHash(),
1159  MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions), ws.m_vsize, ws.m_base_fees));
1160  GetMainSignals().TransactionAddedToMempool(ws.m_ptx, m_pool.GetAndIncrementSequence());
1161  } else {
1162  all_submitted = false;
1163  ws.m_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
1164  results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1165  }
1166  }
1167  return all_submitted;
1168 }
1169 
1170 MempoolAcceptResult MemPoolAccept::AcceptSingleTransaction(const CTransactionRef& ptx, ATMPArgs& args)
1171 {
1173  LOCK(m_pool.cs); // mempool "read lock" (held through GetMainSignals().TransactionAddedToMempool())
1174 
1175  Workspace ws(ptx);
1176 
1177  if (!PreChecks(args, ws)) return MempoolAcceptResult::Failure(ws.m_state);
1178 
1179  if (m_rbf && !ReplacementChecks(ws)) return MempoolAcceptResult::Failure(ws.m_state);
1180 
1181  // Perform the inexpensive checks first and avoid hashing and signature verification unless
1182  // those checks pass, to mitigate CPU exhaustion denial-of-service attacks.
1183  if (!PolicyScriptChecks(args, ws)) return MempoolAcceptResult::Failure(ws.m_state);
1184 
1185  if (!ConsensusScriptChecks(args, ws)) return MempoolAcceptResult::Failure(ws.m_state);
1186 
1187  // Tx was accepted, but not added
1188  if (args.m_test_accept) {
1189  return MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions), ws.m_vsize, ws.m_base_fees);
1190  }
1191 
1192  if (!Finalize(args, ws)) return MempoolAcceptResult::Failure(ws.m_state);
1193 
1194  GetMainSignals().TransactionAddedToMempool(ptx, m_pool.GetAndIncrementSequence());
1195 
1196  return MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions), ws.m_vsize, ws.m_base_fees);
1197 }
1198 
1199 PackageMempoolAcceptResult MemPoolAccept::AcceptMultipleTransactions(const std::vector<CTransactionRef>& txns, ATMPArgs& args)
1200 {
1202 
1203  // These context-free package limits can be done before taking the mempool lock.
1204  PackageValidationState package_state;
1205  if (!CheckPackage(txns, package_state)) return PackageMempoolAcceptResult(package_state, {});
1206 
1207  std::vector<Workspace> workspaces{};
1208  workspaces.reserve(txns.size());
1209  std::transform(txns.cbegin(), txns.cend(), std::back_inserter(workspaces),
1210  [](const auto& tx) { return Workspace(tx); });
1211  std::map<const uint256, const MempoolAcceptResult> results;
1212 
1213  LOCK(m_pool.cs);
1214 
1215  // Do all PreChecks first and fail fast to avoid running expensive script checks when unnecessary.
1216  for (Workspace& ws : workspaces) {
1217  if (!PreChecks(args, ws)) {
1218  package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1219  // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
1220  results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1221  return PackageMempoolAcceptResult(package_state, std::move(results));
1222  }
1223  // Make the coins created by this transaction available for subsequent transactions in the
1224  // package to spend. Since we already checked conflicts in the package and we don't allow
1225  // replacements, we don't need to track the coins spent. Note that this logic will need to be
1226  // updated if package replace-by-fee is allowed in the future.
1227  assert(!args.m_allow_bip125_replacement);
1228  m_viewmempool.PackageAddTransaction(ws.m_ptx);
1229  }
1230 
1231  // Transactions must meet two minimum feerates: the mempool minimum fee and min relay fee.
1232  // For transactions consisting of exactly one child and its parents, it suffices to use the
1233  // package feerate (total modified fees / total virtual size) to check this requirement.
1234  const auto m_total_vsize = std::accumulate(workspaces.cbegin(), workspaces.cend(), int64_t{0},
1235  [](int64_t sum, auto& ws) { return sum + ws.m_vsize; });
1236  const auto m_total_modified_fees = std::accumulate(workspaces.cbegin(), workspaces.cend(), CAmount{0},
1237  [](CAmount sum, auto& ws) { return sum + ws.m_modified_fees; });
1238  const CFeeRate package_feerate(m_total_modified_fees, m_total_vsize);
1239  TxValidationState placeholder_state;
1240  if (args.m_package_feerates &&
1241  !CheckFeeRate(m_total_vsize, m_total_modified_fees, placeholder_state)) {
1242  package_state.Invalid(PackageValidationResult::PCKG_POLICY, "package-fee-too-low");
1243  return PackageMempoolAcceptResult(package_state, package_feerate, {});
1244  }
1245 
1246  // Apply package mempool ancestor/descendant limits. Skip if there is only one transaction,
1247  // because it's unnecessary. Also, CPFP carve out can increase the limit for individual
1248  // transactions, but this exemption is not extended to packages in CheckPackageLimits().
1249  std::string err_string;
1250  if (txns.size() > 1 && !PackageMempoolChecks(txns, package_state)) {
1251  return PackageMempoolAcceptResult(package_state, package_feerate, std::move(results));
1252  }
1253 
1254  for (Workspace& ws : workspaces) {
1255  if (!PolicyScriptChecks(args, ws)) {
1256  // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
1257  package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1258  results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1259  return PackageMempoolAcceptResult(package_state, package_feerate, std::move(results));
1260  }
1261  if (args.m_test_accept) {
1262  // When test_accept=true, transactions that pass PolicyScriptChecks are valid because there are
1263  // no further mempool checks (passing PolicyScriptChecks implies passing ConsensusScriptChecks).
1264  results.emplace(ws.m_ptx->GetWitnessHash(),
1265  MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions),
1266  ws.m_vsize, ws.m_base_fees));
1267  }
1268  }
1269 
1270  if (args.m_test_accept) return PackageMempoolAcceptResult(package_state, package_feerate, std::move(results));
1271 
1272  if (!SubmitPackage(args, workspaces, package_state, results)) {
1273  // PackageValidationState filled in by SubmitPackage().
1274  return PackageMempoolAcceptResult(package_state, package_feerate, std::move(results));
1275  }
1276 
1277  return PackageMempoolAcceptResult(package_state, package_feerate, std::move(results));
1278 }
1279 
1280 PackageMempoolAcceptResult MemPoolAccept::AcceptPackage(const Package& package, ATMPArgs& args)
1281 {
1283  PackageValidationState package_state;
1284 
1285  // Check that the package is well-formed. If it isn't, we won't try to validate any of the
1286  // transactions and thus won't return any MempoolAcceptResults, just a package-wide error.
1287 
1288  // Context-free package checks.
1289  if (!CheckPackage(package, package_state)) return PackageMempoolAcceptResult(package_state, {});
1290 
1291  // All transactions in the package must be a parent of the last transaction. This is just an
1292  // opportunity for us to fail fast on a context-free check without taking the mempool lock.
1293  if (!IsChildWithParents(package)) {
1294  package_state.Invalid(PackageValidationResult::PCKG_POLICY, "package-not-child-with-parents");
1295  return PackageMempoolAcceptResult(package_state, {});
1296  }
1297 
1298  // IsChildWithParents() guarantees the package is > 1 transactions.
1299  assert(package.size() > 1);
1300  // The package must be 1 child with all of its unconfirmed parents. The package is expected to
1301  // be sorted, so the last transaction is the child.
1302  const auto& child = package.back();
1303  std::unordered_set<uint256, SaltedTxidHasher> unconfirmed_parent_txids;
1304  std::transform(package.cbegin(), package.cend() - 1,
1305  std::inserter(unconfirmed_parent_txids, unconfirmed_parent_txids.end()),
1306  [](const auto& tx) { return tx->GetHash(); });
1307 
1308  // All child inputs must refer to a preceding package transaction or a confirmed UTXO. The only
1309  // way to verify this is to look up the child's inputs in our current coins view (not including
1310  // mempool), and enforce that all parents not present in the package be available at chain tip.
1311  // Since this check can bring new coins into the coins cache, keep track of these coins and
1312  // uncache them if we don't end up submitting this package to the mempool.
1313  const CCoinsViewCache& coins_tip_cache = m_active_chainstate.CoinsTip();
1314  for (const auto& input : child->vin) {
1315  if (!coins_tip_cache.HaveCoinInCache(input.prevout)) {
1316  args.m_coins_to_uncache.push_back(input.prevout);
1317  }
1318  }
1319  // Using the MemPoolAccept m_view cache allows us to look up these same coins faster later.
1320  // This should be connecting directly to CoinsTip, not to m_viewmempool, because we specifically
1321  // require inputs to be confirmed if they aren't in the package.
1322  m_view.SetBackend(m_active_chainstate.CoinsTip());
1323  const auto package_or_confirmed = [this, &unconfirmed_parent_txids](const auto& input) {
1324  return unconfirmed_parent_txids.count(input.prevout.hash) > 0 || m_view.HaveCoin(input.prevout);
1325  };
1326  if (!std::all_of(child->vin.cbegin(), child->vin.cend(), package_or_confirmed)) {
1327  package_state.Invalid(PackageValidationResult::PCKG_POLICY, "package-not-child-with-unconfirmed-parents");
1328  return PackageMempoolAcceptResult(package_state, {});
1329  }
1330  // Protect against bugs where we pull more inputs from disk that miss being added to
1331  // coins_to_uncache. The backend will be connected again when needed in PreChecks.
1332  m_view.SetBackend(m_dummy);
1333 
1334  LOCK(m_pool.cs);
1335  std::map<const uint256, const MempoolAcceptResult> results;
1336  // Node operators are free to set their mempool policies however they please, nodes may receive
1337  // transactions in different orders, and malicious counterparties may try to take advantage of
1338  // policy differences to pin or delay propagation of transactions. As such, it's possible for
1339  // some package transaction(s) to already be in the mempool, and we don't want to reject the
1340  // entire package in that case (as that could be a censorship vector). De-duplicate the
1341  // transactions that are already in the mempool, and only call AcceptMultipleTransactions() with
1342  // the new transactions. This ensures we don't double-count transaction counts and sizes when
1343  // checking ancestor/descendant limits, or double-count transaction fees for fee-related policy.
1344  ATMPArgs single_args = ATMPArgs::SingleInPackageAccept(args);
1345  bool quit_early{false};
1346  std::vector<CTransactionRef> txns_new;
1347  for (const auto& tx : package) {
1348  const auto& wtxid = tx->GetWitnessHash();
1349  const auto& txid = tx->GetHash();
1350  // There are 3 possibilities: already in mempool, same-txid-diff-wtxid already in mempool,
1351  // or not in mempool. An already confirmed tx is treated as one not in mempool, because all
1352  // we know is that the inputs aren't available.
1353  if (m_pool.exists(GenTxid::Wtxid(wtxid))) {
1354  // Exact transaction already exists in the mempool.
1355  auto iter = m_pool.GetIter(txid);
1356  assert(iter != std::nullopt);
1357  results.emplace(wtxid, MempoolAcceptResult::MempoolTx(iter.value()->GetTxSize(), iter.value()->GetFee()));
1358  } else if (m_pool.exists(GenTxid::Txid(txid))) {
1359  // Transaction with the same non-witness data but different witness (same txid,
1360  // different wtxid) already exists in the mempool.
1361  //
1362  // We don't allow replacement transactions right now, so just swap the package
1363  // transaction for the mempool one. Note that we are ignoring the validity of the
1364  // package transaction passed in.
1365  // TODO: allow witness replacement in packages.
1366  auto iter = m_pool.GetIter(txid);
1367  assert(iter != std::nullopt);
1368  // Provide the wtxid of the mempool tx so that the caller can look it up in the mempool.
1369  results.emplace(wtxid, MempoolAcceptResult::MempoolTxDifferentWitness(iter.value()->GetTx().GetWitnessHash()));
1370  } else {
1371  // Transaction does not already exist in the mempool.
1372  // Try submitting the transaction on its own.
1373  const auto single_res = AcceptSingleTransaction(tx, single_args);
1374  if (single_res.m_result_type == MempoolAcceptResult::ResultType::VALID) {
1375  // The transaction succeeded on its own and is now in the mempool. Don't include it
1376  // in package validation, because its fees should only be "used" once.
1377  assert(m_pool.exists(GenTxid::Wtxid(wtxid)));
1378  results.emplace(wtxid, single_res);
1379  } else if (single_res.m_state.GetResult() != TxValidationResult::TX_MEMPOOL_POLICY &&
1380  single_res.m_state.GetResult() != TxValidationResult::TX_MISSING_INPUTS) {
1381  // Package validation policy only differs from individual policy in its evaluation
1382  // of feerate. For example, if a transaction fails here due to violation of a
1383  // consensus rule, the result will not change when it is submitted as part of a
1384  // package. To minimize the amount of repeated work, unless the transaction fails
1385  // due to feerate or missing inputs (its parent is a previous transaction in the
1386  // package that failed due to feerate), don't run package validation. Note that this
1387  // decision might not make sense if different types of packages are allowed in the
1388  // future. Continue individually validating the rest of the transactions, because
1389  // some of them may still be valid.
1390  quit_early = true;
1391  } else {
1392  txns_new.push_back(tx);
1393  }
1394  }
1395  }
1396 
1397  // Nothing to do if the entire package has already been submitted.
1398  if (quit_early || txns_new.empty()) {
1399  // No package feerate when no package validation was done.
1400  return PackageMempoolAcceptResult(package_state, std::move(results));
1401  }
1402  // Validate the (deduplicated) transactions as a package.
1403  auto submission_result = AcceptMultipleTransactions(txns_new, args);
1404  // Include already-in-mempool transaction results in the final result.
1405  for (const auto& [wtxid, mempoolaccept_res] : results) {
1406  submission_result.m_tx_results.emplace(wtxid, mempoolaccept_res);
1407  }
1408  if (submission_result.m_state.IsValid()) assert(submission_result.m_package_feerate.has_value());
1409  return submission_result;
1410 }
1411 
1412 } // anon namespace
1413 
1415  int64_t accept_time, bool bypass_limits, bool test_accept)
1417 {
1419  const CChainParams& chainparams{active_chainstate.m_params};
1420  assert(active_chainstate.GetMempool() != nullptr);
1421  CTxMemPool& pool{*active_chainstate.GetMempool()};
1422 
1423  std::vector<COutPoint> coins_to_uncache;
1424  auto args = MemPoolAccept::ATMPArgs::SingleAccept(chainparams, accept_time, bypass_limits, coins_to_uncache, test_accept);
1425  const MempoolAcceptResult result = MemPoolAccept(pool, active_chainstate).AcceptSingleTransaction(tx, args);
1427  // Remove coins that were not present in the coins cache before calling
1428  // AcceptSingleTransaction(); this is to prevent memory DoS in case we receive a large
1429  // number of invalid transactions that attempt to overrun the in-memory coins cache
1430  // (`CCoinsViewCache::cacheCoins`).
1431 
1432  for (const COutPoint& hashTx : coins_to_uncache)
1433  active_chainstate.CoinsTip().Uncache(hashTx);
1434  }
1435  // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
1436  BlockValidationState state_dummy;
1437  active_chainstate.FlushStateToDisk(state_dummy, FlushStateMode::PERIODIC);
1438  return result;
1439 }
1440 
1442  const Package& package, bool test_accept)
1443 {
1445  assert(!package.empty());
1446  assert(std::all_of(package.cbegin(), package.cend(), [](const auto& tx){return tx != nullptr;}));
1447 
1448  std::vector<COutPoint> coins_to_uncache;
1449  const CChainParams& chainparams = active_chainstate.m_params;
1450  const auto result = [&]() EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
1452  if (test_accept) {
1453  auto args = MemPoolAccept::ATMPArgs::PackageTestAccept(chainparams, GetTime(), coins_to_uncache);
1454  return MemPoolAccept(pool, active_chainstate).AcceptMultipleTransactions(package, args);
1455  } else {
1456  auto args = MemPoolAccept::ATMPArgs::PackageChildWithParents(chainparams, GetTime(), coins_to_uncache);
1457  return MemPoolAccept(pool, active_chainstate).AcceptPackage(package, args);
1458  }
1459  }();
1460 
1461  // Uncache coins pertaining to transactions that were not submitted to the mempool.
1462  if (test_accept || result.m_state.IsInvalid()) {
1463  for (const COutPoint& hashTx : coins_to_uncache) {
1464  active_chainstate.CoinsTip().Uncache(hashTx);
1465  }
1466  }
1467  // Ensure the coins cache is still within limits.
1468  BlockValidationState state_dummy;
1469  active_chainstate.FlushStateToDisk(state_dummy, FlushStateMode::PERIODIC);
1470  return result;
1471 }
1472 
1473 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1474 {
1475  int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1476  // Force block reward to zero when right shift is undefined.
1477  if (halvings >= 64)
1478  return 0;
1479 
1480  CAmount nSubsidy = 50 * COIN;
1481  // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1482  nSubsidy >>= halvings;
1483  return nSubsidy;
1484 }
1485 
1487  fs::path ldb_name,
1488  size_t cache_size_bytes,
1489  bool in_memory,
1490  bool should_wipe) : m_dbview(
1491  gArgs.GetDataDirNet() / ldb_name, cache_size_bytes, in_memory, should_wipe),
1492  m_catcherview(&m_dbview) {}
1493 
1494 void CoinsViews::InitCache()
1495 {
1497  m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
1498 }
1499 
1501  CTxMemPool* mempool,
1502  BlockManager& blockman,
1503  ChainstateManager& chainman,
1504  std::optional<uint256> from_snapshot_blockhash)
1505  : m_mempool(mempool),
1506  m_blockman(blockman),
1507  m_params(chainman.GetParams()),
1508  m_chainman(chainman),
1509  m_from_snapshot_blockhash(from_snapshot_blockhash) {}
1510 
1512  size_t cache_size_bytes,
1513  bool in_memory,
1514  bool should_wipe,
1515  fs::path leveldb_name)
1516 {
1518  leveldb_name += "_" + m_from_snapshot_blockhash->ToString();
1519  }
1520 
1521  m_coins_views = std::make_unique<CoinsViews>(
1522  leveldb_name, cache_size_bytes, in_memory, should_wipe);
1523 }
1524 
1525 void CChainState::InitCoinsCache(size_t cache_size_bytes)
1526 {
1528  assert(m_coins_views != nullptr);
1529  m_coinstip_cache_size_bytes = cache_size_bytes;
1530  m_coins_views->InitCache();
1531 }
1532 
1533 // Note that though this is marked const, we may end up modifying `m_cached_finished_ibd`, which
1534 // is a performance-related implementation detail. This function must be marked
1535 // `const` so that `CValidationInterface` clients (which are given a `const CChainState*`)
1536 // can call it.
1537 //
1538 bool CChainState::IsInitialBlockDownload() const
1539 {
1540  // Optimization: pre-test latch before taking the lock.
1541  if (m_cached_finished_ibd.load(std::memory_order_relaxed))
1542  return false;
1543 
1544  LOCK(cs_main);
1545  if (m_cached_finished_ibd.load(std::memory_order_relaxed))
1546  return false;
1547  if (fImporting || fReindex)
1548  return true;
1549  if (m_chain.Tip() == nullptr)
1550  return true;
1552  return true;
1553  if (m_chain.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1554  return true;
1555  LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1556  m_cached_finished_ibd.store(true, std::memory_order_relaxed);
1557  return false;
1558 }
1559 
1560 static void AlertNotify(const std::string& strMessage)
1561 {
1562  uiInterface.NotifyAlertChanged();
1563 #if HAVE_SYSTEM
1564  std::string strCmd = gArgs.GetArg("-alertnotify", "");
1565  if (strCmd.empty()) return;
1566 
1567  // Alert text should be plain ascii coming from a trusted source, but to
1568  // be safe we first strip anything not in safeChars, then add single quotes around
1569  // the whole string before passing it to the shell:
1570  std::string singleQuote("'");
1571  std::string safeStatus = SanitizeString(strMessage);
1572  safeStatus = singleQuote+safeStatus+singleQuote;
1573  ReplaceAll(strCmd, "%s", safeStatus);
1574 
1575  std::thread t(runCommand, strCmd);
1576  t.detach(); // thread runs free
1577 #endif
1578 }
1579 
1581 {
1583 
1584  // Before we get past initial download, we cannot reliably alert about forks
1585  // (we assume we don't get stuck on a fork before finishing our initial sync)
1586  if (IsInitialBlockDownload()) {
1587  return;
1588  }
1589 
1590  if (m_chainman.m_best_invalid && m_chainman.m_best_invalid->nChainWork > m_chain.Tip()->nChainWork + (GetBlockProof(*m_chain.Tip()) * 6)) {
1591  LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1593  } else {
1595  }
1596 }
1597 
1598 // Called both upon regular invalid block discovery *and* InvalidateBlock
1600 {
1602  if (!m_chainman.m_best_invalid || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork) {
1603  m_chainman.m_best_invalid = pindexNew;
1604  }
1605  if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindexNew->nHeight) == pindexNew) {
1607  }
1608 
1609  LogPrintf("%s: invalid block=%s height=%d log2_work=%f date=%s\n", __func__,
1610  pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1611  log(pindexNew->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(pindexNew->GetBlockTime()));
1612  CBlockIndex *tip = m_chain.Tip();
1613  assert (tip);
1614  LogPrintf("%s: current best=%s height=%d log2_work=%f date=%s\n", __func__,
1615  tip->GetBlockHash().ToString(), m_chain.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1618 }
1619 
1620 // Same as InvalidChainFound, above, except not called directly from InvalidateBlock,
1621 // which does its own setBlockIndexCandidates management.
1623 {
1626  pindex->nStatus |= BLOCK_FAILED_VALID;
1627  m_chainman.m_failed_blocks.insert(pindex);
1628  m_blockman.m_dirty_blockindex.insert(pindex);
1629  setBlockIndexCandidates.erase(pindex);
1630  InvalidChainFound(pindex);
1631  }
1632 }
1633 
1634 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1635 {
1636  // mark inputs spent
1637  if (!tx.IsCoinBase()) {
1638  txundo.vprevout.reserve(tx.vin.size());
1639  for (const CTxIn &txin : tx.vin) {
1640  txundo.vprevout.emplace_back();
1641  bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1642  assert(is_spent);
1643  }
1644  }
1645  // add outputs
1646  AddCoins(inputs, tx, nHeight);
1647 }
1648 
1650  const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1651  const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1653 }
1654 
1657 
1659  // Setup the salted hasher
1661  // We want the nonce to be 64 bytes long to force the hasher to process
1662  // this chunk, which makes later hash computations more efficient. We
1663  // just write our 32-byte entropy twice to fill the 64 bytes.
1666  // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1667  // setup_bytes creates the minimum possible cache (2 elements).
1668  size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetIntArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
1669  size_t nElems = g_scriptExecutionCache.setup_bytes(nMaxCacheSize);
1670  LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1671  (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1672 }
1673 
1694  const CCoinsViewCache& inputs, unsigned int flags, bool cacheSigStore,
1695  bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
1696  std::vector<CScriptCheck>* pvChecks)
1697 {
1698  if (tx.IsCoinBase()) return true;
1699 
1700  if (pvChecks) {
1701  pvChecks->reserve(tx.vin.size());
1702  }
1703 
1704  // First check if script executions have been cached with the same
1705  // flags. Note that this assumes that the inputs provided are
1706  // correct (ie that the transaction hash which is in tx's prevouts
1707  // properly commits to the scriptPubKey in the inputs view of that
1708  // transaction).
1709  uint256 hashCacheEntry;
1711  hasher.Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1712  AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1713  if (g_scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1714  return true;
1715  }
1716 
1717  if (!txdata.m_spent_outputs_ready) {
1718  std::vector<CTxOut> spent_outputs;
1719  spent_outputs.reserve(tx.vin.size());
1720 
1721  for (const auto& txin : tx.vin) {
1722  const COutPoint& prevout = txin.prevout;
1723  const Coin& coin = inputs.AccessCoin(prevout);
1724  assert(!coin.IsSpent());
1725  spent_outputs.emplace_back(coin.out);
1726  }
1727  txdata.Init(tx, std::move(spent_outputs));
1728  }
1729  assert(txdata.m_spent_outputs.size() == tx.vin.size());
1730 
1731  for (unsigned int i = 0; i < tx.vin.size(); i++) {
1732 
1733  // We very carefully only pass in things to CScriptCheck which
1734  // are clearly committed to by tx' witness hash. This provides
1735  // a sanity check that our caching is not introducing consensus
1736  // failures through additional data in, eg, the coins being
1737  // spent being checked as a part of CScriptCheck.
1738 
1739  // Verify signature
1740  CScriptCheck check(txdata.m_spent_outputs[i], tx, i, flags, cacheSigStore, &txdata);
1741  if (pvChecks) {
1742  pvChecks->push_back(CScriptCheck());
1743  check.swap(pvChecks->back());
1744  } else if (!check()) {
1746  // Check whether the failure was caused by a
1747  // non-mandatory script verification check, such as
1748  // non-standard DER encodings or non-null dummy
1749  // arguments; if so, ensure we return NOT_STANDARD
1750  // instead of CONSENSUS to avoid downstream users
1751  // splitting the network between upgraded and
1752  // non-upgraded nodes by banning CONSENSUS-failing
1753  // data providers.
1754  CScriptCheck check2(txdata.m_spent_outputs[i], tx, i,
1755  flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1756  if (check2())
1757  return state.Invalid(TxValidationResult::TX_NOT_STANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1758  }
1759  // MANDATORY flag failures correspond to
1760  // TxValidationResult::TX_CONSENSUS. Because CONSENSUS
1761  // failures are the most serious case of validation
1762  // failures, we may need to consider using
1763  // RECENT_CONSENSUS_CHANGE for any script failure that
1764  // could be due to non-upgraded nodes which we may want to
1765  // support, to avoid splitting the network (but this
1766  // depends on the details of how net_processing handles
1767  // such errors).
1768  return state.Invalid(TxValidationResult::TX_CONSENSUS, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1769  }
1770  }
1771 
1772  if (cacheFullScriptStore && !pvChecks) {
1773  // We executed all of the provided scripts, and were told to
1774  // cache the result. Do so now.
1775  g_scriptExecutionCache.insert(hashCacheEntry);
1776  }
1777 
1778  return true;
1779 }
1780 
1781 bool AbortNode(BlockValidationState& state, const std::string& strMessage, const bilingual_str& userMessage)
1782 {
1783  AbortNode(strMessage, userMessage);
1784  return state.Error(strMessage);
1785 }
1786 
1794 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1795 {
1796  bool fClean = true;
1797 
1798  if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1799 
1800  if (undo.nHeight == 0) {
1801  // Missing undo metadata (height and coinbase). Older versions included this
1802  // information only in undo records for the last spend of a transactions'
1803  // outputs. This implies that it must be present for some other output of the same tx.
1804  const Coin& alternate = AccessByTxid(view, out.hash);
1805  if (!alternate.IsSpent()) {
1806  undo.nHeight = alternate.nHeight;
1807  undo.fCoinBase = alternate.fCoinBase;
1808  } else {
1809  return DISCONNECT_FAILED; // adding output for transaction without known metadata
1810  }
1811  }
1812  // If the coin already exists as an unspent coin in the cache, then the
1813  // possible_overwrite parameter to AddCoin must be set to true. We have
1814  // already checked whether an unspent coin exists above using HaveCoin, so
1815  // we don't need to guess. When fClean is false, an unspent coin already
1816  // existed and it is an overwrite.
1817  view.AddCoin(out, std::move(undo), !fClean);
1818 
1819  return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1820 }
1821 
1824 DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1825 {
1827  bool fClean = true;
1828 
1829  CBlockUndo blockUndo;
1830  if (!UndoReadFromDisk(blockUndo, pindex)) {
1831  error("DisconnectBlock(): failure reading undo data");
1832  return DISCONNECT_FAILED;
1833  }
1834 
1835  if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1836  error("DisconnectBlock(): block and undo data inconsistent");
1837  return DISCONNECT_FAILED;
1838  }
1839 
1840  // undo transactions in reverse order
1841  for (int i = block.vtx.size() - 1; i >= 0; i--) {
1842  const CTransaction &tx = *(block.vtx[i]);
1843  uint256 hash = tx.GetHash();
1844  bool is_coinbase = tx.IsCoinBase();
1845 
1846  // Check that all outputs are available and match the outputs in the block itself
1847  // exactly.
1848  for (size_t o = 0; o < tx.vout.size(); o++) {
1849  if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1850  COutPoint out(hash, o);
1851  Coin coin;
1852  bool is_spent = view.SpendCoin(out, &coin);
1853  if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1854  fClean = false; // transaction output mismatch
1855  }
1856  }
1857  }
1858 
1859  // restore inputs
1860  if (i > 0) { // not coinbases
1861  CTxUndo &txundo = blockUndo.vtxundo[i-1];
1862  if (txundo.vprevout.size() != tx.vin.size()) {
1863  error("DisconnectBlock(): transaction and undo data inconsistent");
1864  return DISCONNECT_FAILED;
1865  }
1866  for (unsigned int j = tx.vin.size(); j > 0;) {
1867  --j;
1868  const COutPoint& out = tx.vin[j].prevout;
1869  int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1870  if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1871  fClean = fClean && res != DISCONNECT_UNCLEAN;
1872  }
1873  // At this point, all of txundo.vprevout should have been moved out.
1874  }
1875  }
1876 
1877  // move best block pointer to prevout block
1878  view.SetBestBlock(pindex->pprev->GetBlockHash());
1879 
1880  return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1881 }
1882 
1884 
1885 void StartScriptCheckWorkerThreads(int threads_num)
1886 {
1887  scriptcheckqueue.StartWorkerThreads(threads_num);
1888 }
1889 
1891 {
1892  scriptcheckqueue.StopWorkerThreads();
1893 }
1894 
1899 {
1900 private:
1902  int m_bit;
1903 
1904 public:
1905  explicit WarningBitsConditionChecker(const ChainstateManager& chainman, int bit) : m_chainman{chainman}, m_bit(bit) {}
1906 
1907  int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1908  int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1909  int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1910  int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1911 
1912  bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1913  {
1914  return pindex->nHeight >= params.MinBIP9WarningHeight &&
1916  ((pindex->nVersion >> m_bit) & 1) != 0 &&
1917  ((m_chainman.m_versionbitscache.ComputeBlockVersion(pindex->pprev, params) >> m_bit) & 1) == 0;
1918  }
1919 };
1920 
1921 static std::array<ThresholdConditionCache, VERSIONBITS_NUM_BITS> warningcache GUARDED_BY(cs_main);
1922 
1923 static unsigned int GetBlockScriptFlags(const CBlockIndex& block_index, const ChainstateManager& chainman)
1924 {
1925  const Consensus::Params& consensusparams = chainman.GetConsensus();
1926 
1927  // BIP16 didn't become active until Apr 1 2012 (on mainnet, and
1928  // retroactively applied to testnet)
1929  // However, only one historical block violated the P2SH rules (on both
1930  // mainnet and testnet).
1931  // Similarly, only one historical block violated the TAPROOT rules on
1932  // mainnet.
1933  // For simplicity, always leave P2SH+WITNESS+TAPROOT on except for the two
1934  // violating blocks.
1936  const auto it{consensusparams.script_flag_exceptions.find(*Assert(block_index.phashBlock))};
1937  if (it != consensusparams.script_flag_exceptions.end()) {
1938  flags = it->second;
1939  }
1940 
1941  // Enforce the DERSIG (BIP66) rule
1942  if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_DERSIG)) {
1944  }
1945 
1946  // Enforce CHECKLOCKTIMEVERIFY (BIP65)
1947  if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_CLTV)) {
1949  }
1950 
1951  // Enforce CHECKSEQUENCEVERIFY (BIP112)
1952  if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_CSV)) {
1954  }
1955 
1956  // Enforce BIP147 NULLDUMMY (activated simultaneously with segwit)
1957  if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_SEGWIT)) {
1959  }
1960 
1961  return flags;
1962 }
1963 
1964 
1965 static int64_t nTimeCheck = 0;
1966 static int64_t nTimeForks = 0;
1967 static int64_t nTimeConnect = 0;
1968 static int64_t nTimeVerify = 0;
1969 static int64_t nTimeUndo = 0;
1970 static int64_t nTimeIndex = 0;
1971 static int64_t nTimeTotal = 0;
1972 static int64_t nBlocksTotal = 0;
1973 
1977 bool CChainState::ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
1978  CCoinsViewCache& view, bool fJustCheck)
1979 {
1981  assert(pindex);
1982 
1983  uint256 block_hash{block.GetHash()};
1984  assert(*pindex->phashBlock == block_hash);
1985 
1986  int64_t nTimeStart = GetTimeMicros();
1987 
1988  // Check it again in case a previous version let a bad block in
1989  // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
1990  // ContextualCheckBlockHeader() here. This means that if we add a new
1991  // consensus rule that is enforced in one of those two functions, then we
1992  // may have let in a block that violates the rule prior to updating the
1993  // software, and we would NOT be enforcing the rule here. Fully solving
1994  // upgrade from one software version to the next after a consensus rule
1995  // change is potentially tricky and issue-specific (see NeedsRedownload()
1996  // for one approach that was used for BIP 141 deployment).
1997  // Also, currently the rule against blocks more than 2 hours in the future
1998  // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
1999  // re-enforce that rule here (at least until we make it impossible for
2000  // m_adjusted_time_callback() to go backward).
2001  if (!CheckBlock(block, state, m_params.GetConsensus(), !fJustCheck, !fJustCheck)) {
2003  // We don't write down blocks to disk if they may have been
2004  // corrupted, so this should be impossible unless we're having hardware
2005  // problems.
2006  return AbortNode(state, "Corrupt block found indicating potential hardware failure; shutting down");
2007  }
2008  return error("%s: Consensus::CheckBlock: %s", __func__, state.ToString());
2009  }
2010 
2011  // verify that the view's current state corresponds to the previous block
2012  uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
2013  assert(hashPrevBlock == view.GetBestBlock());
2014 
2015  nBlocksTotal++;
2016 
2017  // Special case for the genesis block, skipping connection of its transactions
2018  // (its coinbase is unspendable)
2019  if (block_hash == m_params.GetConsensus().hashGenesisBlock) {
2020  if (!fJustCheck)
2021  view.SetBestBlock(pindex->GetBlockHash());
2022  return true;
2023  }
2024 
2025  bool fScriptChecks = true;
2026  if (!hashAssumeValid.IsNull()) {
2027  // We've been configured with the hash of a block which has been externally verified to have a valid history.
2028  // A suitable default value is included with the software and updated from time to time. Because validity
2029  // relative to a piece of software is an objective fact these defaults can be easily reviewed.
2030  // This setting doesn't force the selection of any particular chain but makes validating some faster by
2031  // effectively caching the result of part of the verification.
2032  BlockMap::const_iterator it = m_blockman.m_block_index.find(hashAssumeValid);
2033  if (it != m_blockman.m_block_index.end()) {
2034  if (it->second.GetAncestor(pindex->nHeight) == pindex &&
2035  m_chainman.m_best_header->GetAncestor(pindex->nHeight) == pindex &&
2037  // This block is a member of the assumed verified chain and an ancestor of the best header.
2038  // Script verification is skipped when connecting blocks under the
2039  // assumevalid block. Assuming the assumevalid block is valid this
2040  // is safe because block merkle hashes are still computed and checked,
2041  // Of course, if an assumed valid block is invalid due to false scriptSigs
2042  // this optimization would allow an invalid chain to be accepted.
2043  // The equivalent time check discourages hash power from extorting the network via DOS attack
2044  // into accepting an invalid block through telling users they must manually set assumevalid.
2045  // Requiring a software change or burying the invalid block, regardless of the setting, makes
2046  // it hard to hide the implication of the demand. This also avoids having release candidates
2047  // that are hardly doing any signature verification at all in testing without having to
2048  // artificially set the default assumed verified block further back.
2049  // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
2050  // least as good as the expected chain.
2051  fScriptChecks = (GetBlockProofEquivalentTime(*m_chainman.m_best_header, *pindex, *m_chainman.m_best_header, m_params.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
2052  }
2053  }
2054  }
2055 
2056  int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
2057  LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
2058 
2059  // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2060  // unless those are already completely spent.
2061  // If such overwrites are allowed, coinbases and transactions depending upon those
2062  // can be duplicated to remove the ability to spend the first instance -- even after
2063  // being sent to another address.
2064  // See BIP30, CVE-2012-1909, and http://r6.ca/blog/20120206T005236Z.html for more information.
2065  // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
2066  // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
2067  // two in the chain that violate it. This prevents exploiting the issue against nodes during their
2068  // initial block download.
2069  bool fEnforceBIP30 = !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
2070  (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
2071 
2072  // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
2073  // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
2074  // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
2075  // before the first had been spent. Since those coinbases are sufficiently buried it's no longer possible to create further
2076  // duplicate transactions descending from the known pairs either.
2077  // If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
2078 
2079  // BIP34 requires that a block at height X (block X) has its coinbase
2080  // scriptSig start with a CScriptNum of X (indicated height X). The above
2081  // logic of no longer requiring BIP30 once BIP34 activates is flawed in the
2082  // case that there is a block X before the BIP34 height of 227,931 which has
2083  // an indicated height Y where Y is greater than X. The coinbase for block
2084  // X would also be a valid coinbase for block Y, which could be a BIP30
2085  // violation. An exhaustive search of all mainnet coinbases before the
2086  // BIP34 height which have an indicated height greater than the block height
2087  // reveals many occurrences. The 3 lowest indicated heights found are
2088  // 209,921, 490,897, and 1,983,702 and thus coinbases for blocks at these 3
2089  // heights would be the first opportunity for BIP30 to be violated.
2090 
2091  // The search reveals a great many blocks which have an indicated height
2092  // greater than 1,983,702, so we simply remove the optimization to skip
2093  // BIP30 checking for blocks at height 1,983,702 or higher. Before we reach
2094  // that block in another 25 years or so, we should take advantage of a
2095  // future consensus change to do a new and improved version of BIP34 that
2096  // will actually prevent ever creating any duplicate coinbases in the
2097  // future.
2098  static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
2099 
2100  // There is no potential to create a duplicate coinbase at block 209,921
2101  // because this is still before the BIP34 height and so explicit BIP30
2102  // checking is still active.
2103 
2104  // The final case is block 176,684 which has an indicated height of
2105  // 490,897. Unfortunately, this issue was not discovered until about 2 weeks
2106  // before block 490,897 so there was not much opportunity to address this
2107  // case other than to carefully analyze it and determine it would not be a
2108  // problem. Block 490,897 was, in fact, mined with a different coinbase than
2109  // block 176,684, but it is important to note that even if it hadn't been or
2110  // is remined on an alternate fork with a duplicate coinbase, we would still
2111  // not run into a BIP30 violation. This is because the coinbase for 176,684
2112  // is spent in block 185,956 in transaction
2113  // d4f7fbbf92f4a3014a230b2dc70b8058d02eb36ac06b4a0736d9d60eaa9e8781. This
2114  // spending transaction can't be duplicated because it also spends coinbase
2115  // 0328dd85c331237f18e781d692c92de57649529bd5edf1d01036daea32ffde29. This
2116  // coinbase has an indicated height of over 4.2 billion, and wouldn't be
2117  // duplicatable until that height, and it's currently impossible to create a
2118  // chain that long. Nevertheless we may wish to consider a future soft fork
2119  // which retroactively prevents block 490,897 from creating a duplicate
2120  // coinbase. The two historical BIP30 violations often provide a confusing
2121  // edge case when manipulating the UTXO and it would be simpler not to have
2122  // another edge case to deal with.
2123 
2124  // testnet3 has no blocks before the BIP34 height with indicated heights
2125  // post BIP34 before approximately height 486,000,000. After block
2126  // 1,983,702 testnet3 starts doing unnecessary BIP30 checking again.
2127  assert(pindex->pprev);
2128  CBlockIndex* pindexBIP34height = pindex->pprev->GetAncestor(m_params.GetConsensus().BIP34Height);
2129  //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
2130  fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == m_params.GetConsensus().BIP34Hash));
2131 
2132  // TODO: Remove BIP30 checking from block height 1,983,702 on, once we have a
2133  // consensus change that ensures coinbases at those heights cannot
2134  // duplicate earlier coinbases.
2135  if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
2136  for (const auto& tx : block.vtx) {
2137  for (size_t o = 0; o < tx->vout.size(); o++) {
2138  if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
2139  LogPrintf("ERROR: ConnectBlock(): tried to overwrite transaction\n");
2140  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-BIP30");
2141  }
2142  }
2143  }
2144  }
2145 
2146  // Enforce BIP68 (sequence locks)
2147  int nLockTimeFlags = 0;
2149  nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
2150  }
2151 
2152  // Get the script flags for this block
2153  unsigned int flags{GetBlockScriptFlags(*pindex, m_chainman)};
2154 
2155  int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
2156  LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
2157 
2158  CBlockUndo blockundo;
2159 
2160  // Precomputed transaction data pointers must not be invalidated
2161  // until after `control` has run the script checks (potentially
2162  // in multiple threads). Preallocate the vector size so a new allocation
2163  // doesn't invalidate pointers into the vector, and keep txsdata in scope
2164  // for as long as `control`.
2165  CCheckQueueControl<CScriptCheck> control(fScriptChecks && g_parallel_script_checks ? &scriptcheckqueue : nullptr);
2166  std::vector<PrecomputedTransactionData> txsdata(block.vtx.size());
2167 
2168  std::vector<int> prevheights;
2169  CAmount nFees = 0;
2170  int nInputs = 0;
2171  int64_t nSigOpsCost = 0;
2172  blockundo.vtxundo.reserve(block.vtx.size() - 1);
2173  for (unsigned int i = 0; i < block.vtx.size(); i++)
2174  {
2175  const CTransaction &tx = *(block.vtx[i]);
2176 
2177  nInputs += tx.vin.size();
2178 
2179  if (!tx.IsCoinBase())
2180  {
2181  CAmount txfee = 0;
2182  TxValidationState tx_state;
2183  if (!Consensus::CheckTxInputs(tx, tx_state, view, pindex->nHeight, txfee)) {
2184  // Any transaction validation failure in ConnectBlock is a block consensus failure
2186  tx_state.GetRejectReason(), tx_state.GetDebugMessage());
2187  return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), state.ToString());
2188  }
2189  nFees += txfee;
2190  if (!MoneyRange(nFees)) {
2191  LogPrintf("ERROR: %s: accumulated fee in the block out of range.\n", __func__);
2192  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-accumulated-fee-outofrange");
2193  }
2194 
2195  // Check that transaction is BIP68 final
2196  // BIP68 lock checks (as opposed to nLockTime checks) must
2197  // be in ConnectBlock because they require the UTXO set
2198  prevheights.resize(tx.vin.size());
2199  for (size_t j = 0; j < tx.vin.size(); j++) {
2200  prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
2201  }
2202 
2203  if (!SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
2204  LogPrintf("ERROR: %s: contains a non-BIP68-final transaction\n", __func__);
2205  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal");
2206  }
2207  }
2208 
2209  // GetTransactionSigOpCost counts 3 types of sigops:
2210  // * legacy (always)
2211  // * p2sh (when P2SH enabled in flags and excludes coinbase)
2212  // * witness (when witness enabled in flags and excludes coinbase)
2213  nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
2214  if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST) {
2215  LogPrintf("ERROR: ConnectBlock(): too many sigops\n");
2216  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops");
2217  }
2218 
2219  if (!tx.IsCoinBase())
2220  {
2221  std::vector<CScriptCheck> vChecks;
2222  bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
2223  TxValidationState tx_state;
2224  if (fScriptChecks && !CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], g_parallel_script_checks ? &vChecks : nullptr)) {
2225  // Any transaction validation failure in ConnectBlock is a block consensus failure
2227  tx_state.GetRejectReason(), tx_state.GetDebugMessage());
2228  return error("ConnectBlock(): CheckInputScripts on %s failed with %s",
2229  tx.GetHash().ToString(), state.ToString());
2230  }
2231  control.Add(vChecks);
2232  }
2233 
2234  CTxUndo undoDummy;
2235  if (i > 0) {
2236  blockundo.vtxundo.push_back(CTxUndo());
2237  }
2238  UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2239  }
2240  int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
2241  LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(), MILLI * (nTime3 - nTime2), MILLI * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : MILLI * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * MICRO, nTimeConnect * MILLI / nBlocksTotal);
2242 
2243  CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, m_params.GetConsensus());
2244  if (block.vtx[0]->GetValueOut() > blockReward) {
2245  LogPrintf("ERROR: ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)\n", block.vtx[0]->GetValueOut(), blockReward);
2246  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-amount");
2247  }
2248 
2249  if (!control.Wait()) {
2250  LogPrintf("ERROR: %s: CheckQueue failed\n", __func__);
2251  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "block-validation-failed");
2252  }
2253  int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
2254  LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1, MILLI * (nTime4 - nTime2), nInputs <= 1 ? 0 : MILLI * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * MICRO, nTimeVerify * MILLI / nBlocksTotal);
2255 
2256  if (fJustCheck)
2257  return true;
2258 
2259  if (!m_blockman.WriteUndoDataForBlock(blockundo, state, pindex, m_params)) {
2260  return false;
2261  }
2262 
2263  int64_t nTime5 = GetTimeMicros(); nTimeUndo += nTime5 - nTime4;
2264  LogPrint(BCLog::BENCH, " - Write undo data: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeUndo * MICRO, nTimeUndo * MILLI / nBlocksTotal);
2265 
2266  if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
2268  m_blockman.m_dirty_blockindex.insert(pindex);
2269  }
2270 
2271  assert(pindex->phashBlock);
2272  // add this block to the view's block chain
2273  view.SetBestBlock(pindex->GetBlockHash());
2274 
2275  int64_t nTime6 = GetTimeMicros(); nTimeIndex += nTime6 - nTime5;
2276  LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
2277 
2278  TRACE6(validation, block_connected,
2279  block_hash.data(),
2280  pindex->nHeight,
2281  block.vtx.size(),
2282  nInputs,
2283  nSigOpsCost,
2284  nTime5 - nTimeStart // in microseconds (µs)
2285  );
2286 
2287  return true;
2288 }
2289 
2290 CoinsCacheSizeState CChainState::GetCoinsCacheSizeState()
2291 {
2293  return this->GetCoinsCacheSizeState(
2295  gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
2296 }
2297 
2298 CoinsCacheSizeState CChainState::GetCoinsCacheSizeState(
2299  size_t max_coins_cache_size_bytes,
2300  size_t max_mempool_size_bytes)
2301 {
2303  const int64_t nMempoolUsage = m_mempool ? m_mempool->DynamicMemoryUsage() : 0;
2304  int64_t cacheSize = CoinsTip().DynamicMemoryUsage();
2305  int64_t nTotalSpace =
2306  max_coins_cache_size_bytes + std::max<int64_t>(int64_t(max_mempool_size_bytes) - nMempoolUsage, 0);
2307 
2309  static constexpr int64_t MAX_BLOCK_COINSDB_USAGE_BYTES = 10 * 1024 * 1024; // 10MB
2310  int64_t large_threshold =
2311  std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE_BYTES);
2312 
2313  if (cacheSize > nTotalSpace) {
2314  LogPrintf("Cache size (%s) exceeds total space (%s)\n", cacheSize, nTotalSpace);
2316  } else if (cacheSize > large_threshold) {
2318  }
2319  return CoinsCacheSizeState::OK;
2320 }
2321 
2323  BlockValidationState &state,
2324  FlushStateMode mode,
2325  int nManualPruneHeight)
2326 {
2327  LOCK(cs_main);
2328  assert(this->CanFlushToDisk());
2329  static std::chrono::microseconds nLastWrite{0};
2330  static std::chrono::microseconds nLastFlush{0};
2331  std::set<int> setFilesToPrune;
2332  bool full_flush_completed = false;
2333 
2334  const size_t coins_count = CoinsTip().GetCacheSize();
2335  const size_t coins_mem_usage = CoinsTip().DynamicMemoryUsage();
2336 
2337  try {
2338  {
2339  bool fFlushForPrune = false;
2340  bool fDoFullFlush = false;
2341 
2342  CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
2344  if (fPruneMode && (m_blockman.m_check_for_pruning || nManualPruneHeight > 0) && !fReindex) {
2345  // make sure we don't prune above any of the prune locks bestblocks
2346  // pruning is height-based
2347  int last_prune{m_chain.Height()}; // last height we can prune
2348  std::optional<std::string> limiting_lock; // prune lock that actually was the limiting factor, only used for logging
2349 
2350  for (const auto& prune_lock : m_blockman.m_prune_locks) {
2351  if (prune_lock.second.height_first == std::numeric_limits<int>::max()) continue;
2352  // Remove the buffer and one additional block here to get actual height that is outside of the buffer
2353  const int lock_height{prune_lock.second.height_first - PRUNE_LOCK_BUFFER - 1};
2354  last_prune = std::max(1, std::min(last_prune, lock_height));
2355  if (last_prune == lock_height) {
2356  limiting_lock = prune_lock.first;
2357  }
2358  }
2359 
2360  if (limiting_lock) {
2361  LogPrint(BCLog::PRUNE, "%s limited pruning to height %d\n", limiting_lock.value(), last_prune);
2362  }
2363 
2364  if (nManualPruneHeight > 0) {
2365  LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune (manual)", BCLog::BENCH);
2366 
2367  m_blockman.FindFilesToPruneManual(setFilesToPrune, std::min(last_prune, nManualPruneHeight), m_chain.Height());
2368  } else {
2369  LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune", BCLog::BENCH);
2370 
2371  m_blockman.FindFilesToPrune(setFilesToPrune, m_params.PruneAfterHeight(), m_chain.Height(), last_prune, IsInitialBlockDownload());
2373  }
2374  if (!setFilesToPrune.empty()) {
2375  fFlushForPrune = true;
2376  if (!m_blockman.m_have_pruned) {
2377  m_blockman.m_block_tree_db->WriteFlag("prunedblockfiles", true);
2378  m_blockman.m_have_pruned = true;
2379  }
2380  }
2381  }
2382  const auto nNow = GetTime<std::chrono::microseconds>();
2383  // Avoid writing/flushing immediately after startup.
2384  if (nLastWrite.count() == 0) {
2385  nLastWrite = nNow;
2386  }
2387  if (nLastFlush.count() == 0) {
2388  nLastFlush = nNow;
2389  }
2390  // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
2391  bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
2392  // The cache is over the limit, we have to write now.
2393  bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
2394  // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
2395  bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > nLastWrite + DATABASE_WRITE_INTERVAL;
2396  // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2397  bool fPeriodicFlush = mode == FlushStateMode::PERIODIC && nNow > nLastFlush + DATABASE_FLUSH_INTERVAL;
2398  // Combine all conditions that result in a full cache flush.
2399  fDoFullFlush = (mode == FlushStateMode::ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2400  // Write blocks and block index to disk.
2401  if (fDoFullFlush || fPeriodicWrite) {
2402  // Ensure we can write block index
2404  return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
2405  }
2406  {
2407  LOG_TIME_MILLIS_WITH_CATEGORY("write block and undo data to disk", BCLog::BENCH);
2408 
2409  // First make sure all block and undo data is flushed to disk.
2411  }
2412 
2413  // Then update all block file information (which may refer to block and undo files).
2414  {
2415  LOG_TIME_MILLIS_WITH_CATEGORY("write block index to disk", BCLog::BENCH);
2416 
2417  if (!m_blockman.WriteBlockIndexDB()) {
2418  return AbortNode(state, "Failed to write to block index database");
2419  }
2420  }
2421  // Finally remove any pruned files
2422  if (fFlushForPrune) {
2423  LOG_TIME_MILLIS_WITH_CATEGORY("unlink pruned files", BCLog::BENCH);
2424 
2425  UnlinkPrunedFiles(setFilesToPrune);
2426  }
2427  nLastWrite = nNow;
2428  }
2429  // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2430  if (fDoFullFlush && !CoinsTip().GetBestBlock().IsNull()) {
2431  LOG_TIME_MILLIS_WITH_CATEGORY(strprintf("write coins cache to disk (%d coins, %.2fkB)",
2432  coins_count, coins_mem_usage / 1000), BCLog::BENCH);
2433 
2434  // Typical Coin structures on disk are around 48 bytes in size.
2435  // Pushing a new one to the database can cause it to be written
2436  // twice (once in the log, and once in the tables). This is already
2437  // an overestimation, as most will delete an existing entry or
2438  // overwrite one. Still, use a conservative safety factor of 2.
2439  if (!CheckDiskSpace(gArgs.GetDataDirNet(), 48 * 2 * 2 * CoinsTip().GetCacheSize())) {
2440  return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
2441  }
2442  // Flush the chainstate (which may refer to block index entries).
2443  if (!CoinsTip().Flush())
2444  return AbortNode(state, "Failed to write to coin database");
2445  nLastFlush = nNow;
2446  full_flush_completed = true;
2447  TRACE5(utxocache, flush,
2448  (int64_t)(GetTimeMicros() - nNow.count()), // in microseconds (µs)
2449  (uint32_t)mode,
2450  (uint64_t)coins_count,
2451  (uint64_t)coins_mem_usage,
2452  (bool)fFlushForPrune);
2453  }
2454  }
2455  if (full_flush_completed) {
2456  // Update best block in wallet (so we can detect restored wallets).
2458  }
2459  } catch (const std::runtime_error& e) {
2460  return AbortNode(state, std::string("System error while flushing: ") + e.what());
2461  }
2462  return true;
2463 }
2464 
2466 {
2467  BlockValidationState state;
2468  if (!this->FlushStateToDisk(state, FlushStateMode::ALWAYS)) {
2469  LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
2470  }
2471 }
2472 
2474 {
2475  BlockValidationState state;
2477  if (!this->FlushStateToDisk(state, FlushStateMode::NONE)) {
2478  LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
2479  }
2480 }
2481 
2482 static void DoWarning(const bilingual_str& warning)
2483 {
2484  static bool fWarned = false;
2485  SetMiscWarning(warning);
2486  if (!fWarned) {
2487  AlertNotify(warning.original);
2488  fWarned = true;
2489  }
2490 }
2491 
2493 static void AppendWarning(bilingual_str& res, const bilingual_str& warn)
2494 {
2495  if (!res.empty()) res += Untranslated(", ");
2496  res += warn;
2497 }
2498 
2499 static void UpdateTipLog(
2500  const CCoinsViewCache& coins_tip,
2501  const CBlockIndex* tip,
2502  const CChainParams& params,
2503  const std::string& func_name,
2504  const std::string& prefix,
2505  const std::string& warning_messages) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
2506 {
2507 
2509  LogPrintf("%s%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)%s\n",
2510  prefix, func_name,
2511  tip->GetBlockHash().ToString(), tip->nHeight, tip->nVersion,
2512  log(tip->nChainWork.getdouble()) / log(2.0), (unsigned long)tip->nChainTx,
2513  FormatISO8601DateTime(tip->GetBlockTime()),
2514  GuessVerificationProgress(params.TxData(), tip),
2515  coins_tip.DynamicMemoryUsage() * (1.0 / (1 << 20)),
2516  coins_tip.GetCacheSize(),
2517  !warning_messages.empty() ? strprintf(" warning='%s'", warning_messages) : "");
2518 }
2519 
2520 void CChainState::UpdateTip(const CBlockIndex* pindexNew)
2521 {
2523  const auto& coins_tip = this->CoinsTip();
2524 
2525  // The remainder of the function isn't relevant if we are not acting on
2526  // the active chainstate, so return if need be.
2527  if (this != &m_chainman.ActiveChainstate()) {
2528  // Only log every so often so that we don't bury log messages at the tip.
2529  constexpr int BACKGROUND_LOG_INTERVAL = 2000;
2530  if (pindexNew->nHeight % BACKGROUND_LOG_INTERVAL == 0) {
2531  UpdateTipLog(coins_tip, pindexNew, m_params, __func__, "[background validation] ", "");
2532  }
2533  return;
2534  }
2535 
2536  // New best block
2537  if (m_mempool) {
2539  }
2540 
2541  {
2543  g_best_block = pindexNew->GetBlockHash();
2544  g_best_block_cv.notify_all();
2545  }
2546 
2547  bilingual_str warning_messages;
2548  if (!this->IsInitialBlockDownload()) {
2549  const CBlockIndex* pindex = pindexNew;
2550  for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2552  ThresholdState state = checker.GetStateFor(pindex, m_params.GetConsensus(), warningcache.at(bit));
2553  if (state == ThresholdState::ACTIVE || state == ThresholdState::LOCKED_IN) {
2554  const bilingual_str warning = strprintf(_("Unknown new rules activated (versionbit %i)"), bit);
2555  if (state == ThresholdState::ACTIVE) {
2556  DoWarning(warning);
2557  } else {
2558  AppendWarning(warning_messages, warning);
2559  }
2560  }
2561  }
2562  }
2563  UpdateTipLog(coins_tip, pindexNew, m_params, __func__, "", warning_messages.original);
2564 }
2565 
2577 {
2580 
2581  CBlockIndex *pindexDelete = m_chain.Tip();
2582  assert(pindexDelete);
2583  // Read block from disk.
2584  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2585  CBlock& block = *pblock;
2586  if (!ReadBlockFromDisk(block, pindexDelete, m_params.GetConsensus())) {
2587  return error("DisconnectTip(): Failed to read block");
2588  }
2589  // Apply the block atomically to the chain state.
2590  int64_t nStart = GetTimeMicros();
2591  {
2592  CCoinsViewCache view(&CoinsTip());
2593  assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2594  if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2595  return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2596  bool flushed = view.Flush();
2597  assert(flushed);
2598  }
2599  LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
2600 
2601  {
2602  // Prune locks that began at or after the tip should be moved backward so they get a chance to reorg
2603  const int max_height_first{pindexDelete->nHeight - 1};
2604  for (auto& prune_lock : m_blockman.m_prune_locks) {
2605  if (prune_lock.second.height_first <= max_height_first) continue;
2606 
2607  prune_lock.second.height_first = max_height_first;
2608  LogPrint(BCLog::PRUNE, "%s prune lock moved back to %d\n", prune_lock.first, max_height_first);
2609  }
2610  }
2611 
2612  // Write the chain state to disk, if necessary.
2614  return false;
2615  }
2616 
2617  if (disconnectpool && m_mempool) {
2618  // Save transactions to re-add to mempool at end of reorg
2619  for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2620  disconnectpool->addTransaction(*it);
2621  }
2622  while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2623  // Drop the earliest entry, and remove its children from the mempool.
2624  auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2626  disconnectpool->removeEntry(it);
2627  }
2628  }
2629 
2630  m_chain.SetTip(pindexDelete->pprev);
2631 
2632  UpdateTip(pindexDelete->pprev);
2633  // Let wallets know transactions went from 1-confirmed to
2634  // 0-confirmed or conflicted:
2635  GetMainSignals().BlockDisconnected(pblock, pindexDelete);
2636  return true;
2637 }
2638 
2639 static int64_t nTimeReadFromDiskTotal = 0;
2640 static int64_t nTimeConnectTotal = 0;
2641 static int64_t nTimeFlush = 0;
2642 static int64_t nTimeChainState = 0;
2643 static int64_t nTimePostConnect = 0;
2644 
2646  CBlockIndex* pindex = nullptr;
2647  std::shared_ptr<const CBlock> pblock;
2648  PerBlockConnectTrace() = default;
2649 };
2658 private:
2659  std::vector<PerBlockConnectTrace> blocksConnected;
2660 
2661 public:
2662  explicit ConnectTrace() : blocksConnected(1) {}
2663 
2664  void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2665  assert(!blocksConnected.back().pindex);
2666  assert(pindex);
2667  assert(pblock);
2668  blocksConnected.back().pindex = pindex;
2669  blocksConnected.back().pblock = std::move(pblock);
2670  blocksConnected.emplace_back();
2671  }
2672 
2673  std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2674  // We always keep one extra block at the end of our list because
2675  // blocks are added after all the conflicted transactions have
2676  // been filled in. Thus, the last entry should always be an empty
2677  // one waiting for the transactions from the next block. We pop
2678  // the last entry here to make sure the list we return is sane.
2679  assert(!blocksConnected.back().pindex);
2680  blocksConnected.pop_back();
2681  return blocksConnected;
2682  }
2683 };
2684 
2691 bool CChainState::ConnectTip(BlockValidationState& state, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions& disconnectpool)
2692 {
2695 
2696  assert(pindexNew->pprev == m_chain.Tip());
2697  // Read block from disk.
2698  int64_t nTime1 = GetTimeMicros();
2699  std::shared_ptr<const CBlock> pthisBlock;
2700  if (!pblock) {
2701  std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2702  if (!ReadBlockFromDisk(*pblockNew, pindexNew, m_params.GetConsensus())) {
2703  return AbortNode(state, "Failed to read block");
2704  }
2705  pthisBlock = pblockNew;
2706  } else {
2707  LogPrint(BCLog::BENCH, " - Using cached block\n");
2708  pthisBlock = pblock;
2709  }
2710  const CBlock& blockConnecting = *pthisBlock;
2711  // Apply the block atomically to the chain state.
2712  int64_t nTime2 = GetTimeMicros(); nTimeReadFromDiskTotal += nTime2 - nTime1;
2713  int64_t nTime3;
2714  LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDiskTotal * MICRO, nTimeReadFromDiskTotal * MILLI / nBlocksTotal);
2715  {
2716  CCoinsViewCache view(&CoinsTip());
2717  bool rv = ConnectBlock(blockConnecting, state, pindexNew, view);
2718  GetMainSignals().BlockChecked(blockConnecting, state);
2719  if (!rv) {
2720  if (state.IsInvalid())
2721  InvalidBlockFound(pindexNew, state);
2722  return error("%s: ConnectBlock %s failed, %s", __func__, pindexNew->GetBlockHash().ToString(), state.ToString());
2723  }
2724  nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2725  assert(nBlocksTotal > 0);
2726  LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
2727  bool flushed = view.Flush();
2728  assert(flushed);
2729  }
2730  int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2731  LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
2732  // Write the chain state to disk, if necessary.
2734  return false;
2735  }
2736  int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2737  LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
2738  // Remove conflicting transactions from the mempool.;
2739  if (m_mempool) {
2740  m_mempool->removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2741  disconnectpool.removeForBlock(blockConnecting.vtx);
2742  }
2743  // Update m_chain & related variables.
2744  m_chain.SetTip(pindexNew);
2745  UpdateTip(pindexNew);
2746 
2747  int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2748  LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
2749  LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
2750 
2751  connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2752  return true;
2753 }
2754 
2760 {
2762  do {
2763  CBlockIndex *pindexNew = nullptr;
2764 
2765  // Find the best candidate header.
2766  {
2767  std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2768  if (it == setBlockIndexCandidates.rend())
2769  return nullptr;
2770  pindexNew = *it;
2771  }
2772 
2773  // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2774  // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2775  CBlockIndex *pindexTest = pindexNew;
2776  bool fInvalidAncestor = false;
2777  while (pindexTest && !m_chain.Contains(pindexTest)) {
2778  assert(pindexTest->HaveTxsDownloaded() || pindexTest->nHeight == 0);
2779 
2780  // Pruned nodes may have entries in setBlockIndexCandidates for
2781  // which block files have been deleted. Remove those as candidates
2782  // for the most work chain if we come across them; we can't switch
2783  // to a chain unless we have all the non-active-chain parent blocks.
2784  bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2785  bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2786  if (fFailedChain || fMissingData) {
2787  // Candidate chain is not usable (either invalid or missing data)
2788  if (fFailedChain && (m_chainman.m_best_invalid == nullptr || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork)) {
2789  m_chainman.m_best_invalid = pindexNew;
2790  }
2791  CBlockIndex *pindexFailed = pindexNew;
2792  // Remove the entire chain from the set.
2793  while (pindexTest != pindexFailed) {
2794  if (fFailedChain) {
2795  pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2796  } else if (fMissingData) {
2797  // If we're missing data, then add back to m_blocks_unlinked,
2798  // so that if the block arrives in the future we can try adding
2799  // to setBlockIndexCandidates again.
2801  std::make_pair(pindexFailed->pprev, pindexFailed));
2802  }
2803  setBlockIndexCandidates.erase(pindexFailed);
2804  pindexFailed = pindexFailed->pprev;
2805  }
2806  setBlockIndexCandidates.erase(pindexTest);
2807  fInvalidAncestor = true;
2808  break;
2809  }
2810  pindexTest = pindexTest->pprev;
2811  }
2812  if (!fInvalidAncestor)
2813  return pindexNew;
2814  } while(true);
2815 }
2816 
2819  // Note that we can't delete the current block itself, as we may need to return to it later in case a
2820  // reorganization to a better block fails.
2821  std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2822  while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) {
2823  setBlockIndexCandidates.erase(it++);
2824  }
2825  // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2826  assert(!setBlockIndexCandidates.empty());
2827 }
2828 
2835 bool CChainState::ActivateBestChainStep(BlockValidationState& state, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2836 {
2839 
2840  const CBlockIndex* pindexOldTip = m_chain.Tip();
2841  const CBlockIndex* pindexFork = m_chain.FindFork(pindexMostWork);
2842 
2843  // Disconnect active blocks which are no longer in the best chain.
2844  bool fBlocksDisconnected = false;
2845  DisconnectedBlockTransactions disconnectpool;
2846  while (m_chain.Tip() && m_chain.Tip() != pindexFork) {
2847  if (!DisconnectTip(state, &disconnectpool)) {
2848  // This is likely a fatal error, but keep the mempool consistent,
2849  // just in case. Only remove from the mempool in this case.
2850  MaybeUpdateMempoolForReorg(disconnectpool, false);
2851 
2852  // If we're unable to disconnect a block during normal operation,
2853  // then that is a failure of our local system -- we should abort
2854  // rather than stay on a less work chain.
2855  AbortNode(state, "Failed to disconnect block; see debug.log for details");
2856  return false;
2857  }
2858  fBlocksDisconnected = true;
2859  }
2860 
2861  // Build list of new blocks to connect (in descending height order).
2862  std::vector<CBlockIndex*> vpindexToConnect;
2863  bool fContinue = true;
2864  int nHeight = pindexFork ? pindexFork->nHeight : -1;
2865  while (fContinue && nHeight != pindexMostWork->nHeight) {
2866  // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2867  // a few blocks along the way.
2868  int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2869  vpindexToConnect.clear();
2870  vpindexToConnect.reserve(nTargetHeight - nHeight);
2871  CBlockIndex* pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2872  while (pindexIter && pindexIter->nHeight != nHeight) {
2873  vpindexToConnect.push_back(pindexIter);
2874  pindexIter = pindexIter->pprev;
2875  }
2876  nHeight = nTargetHeight;
2877 
2878  // Connect new blocks.
2879  for (CBlockIndex* pindexConnect : reverse_iterate(vpindexToConnect)) {
2880  if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2881  if (state.IsInvalid()) {
2882  // The block violates a consensus rule.
2884  InvalidChainFound(vpindexToConnect.front());
2885  }
2886  state = BlockValidationState();
2887  fInvalidFound = true;
2888  fContinue = false;
2889  break;
2890  } else {
2891  // A system error occurred (disk space, database error, ...).
2892  // Make the mempool consistent with the current tip, just in case
2893  // any observers try to use it before shutdown.
2894  MaybeUpdateMempoolForReorg(disconnectpool, false);
2895  return false;
2896  }
2897  } else {
2899  if (!pindexOldTip || m_chain.Tip()->nChainWork > pindexOldTip->nChainWork) {
2900  // We're in a better position than we were. Return temporarily to release the lock.
2901  fContinue = false;
2902  break;
2903  }
2904  }
2905  }
2906  }
2907 
2908  if (fBlocksDisconnected) {
2909  // If any blocks were disconnected, disconnectpool may be non empty. Add
2910  // any disconnected transactions back to the mempool.
2911  MaybeUpdateMempoolForReorg(disconnectpool, true);
2912  }
2913  if (m_mempool) m_mempool->check(this->CoinsTip(), this->m_chain.Height() + 1);
2914 
2916 
2917  return true;
2918 }
2919 
2921 {
2925 }
2926 
2928  bool fNotify = false;
2929  bool fInitialBlockDownload = false;
2930  static CBlockIndex* pindexHeaderOld = nullptr;
2931  CBlockIndex* pindexHeader = nullptr;
2932  {
2933  LOCK(cs_main);
2934  pindexHeader = chainstate.m_chainman.m_best_header;
2935 
2936  if (pindexHeader != pindexHeaderOld) {
2937  fNotify = true;
2938  fInitialBlockDownload = chainstate.IsInitialBlockDownload();
2939  pindexHeaderOld = pindexHeader;
2940  }
2941  }
2942  // Send block tip changed notifications without cs_main
2943  if (fNotify) {
2944  uiInterface.NotifyHeaderTip(GetSynchronizationState(fInitialBlockDownload), pindexHeader);
2945  }
2946  return fNotify;
2947 }
2948 
2951 
2952  if (GetMainSignals().CallbacksPending() > 10) {
2954  }
2955 }
2956 
2957 bool CChainState::ActivateBestChain(BlockValidationState& state, std::shared_ptr<const CBlock> pblock)
2958 {
2960 
2961  // Note that while we're often called here from ProcessNewBlock, this is
2962  // far from a guarantee. Things in the P2P/RPC will often end up calling
2963  // us in the middle of ProcessNewBlock - do not assume pblock is set
2964  // sanely for performance or correctness!
2966 
2967  // ABC maintains a fair degree of expensive-to-calculate internal state
2968  // because this function periodically releases cs_main so that it does not lock up other threads for too long
2969  // during large connects - and to allow for e.g. the callback queue to drain
2970  // we use m_chainstate_mutex to enforce mutual exclusion so that only one caller may execute this function at a time
2972 
2973  CBlockIndex *pindexMostWork = nullptr;
2974  CBlockIndex *pindexNewTip = nullptr;
2975  int nStopAtHeight = gArgs.GetIntArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2976  do {
2977  // Block until the validation queue drains. This should largely
2978  // never happen in normal operation, however may happen during
2979  // reindex, causing memory blowup if we run too far ahead.
2980  // Note that if a validationinterface callback ends up calling
2981  // ActivateBestChain this may lead to a deadlock! We should
2982  // probably have a DEBUG_LOCKORDER test for this in the future.
2984 
2985  {
2986  LOCK(cs_main);
2987  // Lock transaction pool for at least as long as it takes for connectTrace to be consumed
2988  LOCK(MempoolMutex());
2989  CBlockIndex* starting_tip = m_chain.Tip();
2990  bool blocks_connected = false;
2991  do {
2992  // We absolutely may not unlock cs_main until we've made forward progress
2993  // (with the exception of shutdown due to hardware issues, low disk space, etc).
2994  ConnectTrace connectTrace; // Destructed before cs_main is unlocked
2995 
2996  if (pindexMostWork == nullptr) {
2997  pindexMostWork = FindMostWorkChain();
2998  }
2999 
3000  // Whether we have anything to do at all.
3001  if (pindexMostWork == nullptr || pindexMostWork == m_chain.Tip()) {
3002  break;
3003  }
3004 
3005  bool fInvalidFound = false;
3006  std::shared_ptr<const CBlock> nullBlockPtr;
3007  if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace)) {
3008  // A system error occurred
3009  return false;
3010  }
3011  blocks_connected = true;
3012 
3013  if (fInvalidFound) {
3014  // Wipe cache, we may need another branch now.
3015  pindexMostWork = nullptr;
3016  }
3017  pindexNewTip = m_chain.Tip();
3018 
3019  for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
3020  assert(trace.pblock && trace.pindex);
3021  GetMainSignals().BlockConnected(trace.pblock, trace.pindex);
3022  }
3023  } while (!m_chain.Tip() || (starting_tip && CBlockIndexWorkComparator()(m_chain.Tip(), starting_tip)));
3024  if (!blocks_connected) return true;
3025 
3026  const CBlockIndex* pindexFork = m_chain.FindFork(starting_tip);
3027  bool fInitialDownload = IsInitialBlockDownload();
3028 
3029  // Notify external listeners about the new tip.
3030  // Enqueue while holding cs_main to ensure that UpdatedBlockTip is called in the order in which blocks are connected
3031  if (pindexFork != pindexNewTip) {
3032  // Notify ValidationInterface subscribers
3033  GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
3034 
3035  // Always notify the UI if a new block tip was connected
3036  uiInterface.NotifyBlockTip(GetSynchronizationState(fInitialDownload), pindexNewTip);
3037  }
3038  }
3039  // When we reach this point, we switched to a new tip (stored in pindexNewTip).
3040 
3041  if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
3042 
3043  // We check shutdown only after giving ActivateBestChainStep a chance to run once so that we
3044  // never shutdown before connecting the genesis block during LoadChainTip(). Previously this
3045  // caused an assert() failure during shutdown in such cases as the UTXO DB flushing checks
3046  // that the best block hash is non-null.
3047  if (ShutdownRequested()) break;
3048  } while (pindexNewTip != pindexMostWork);
3049  CheckBlockIndex();
3050 
3051  // Write changes periodically to disk, after relay.
3053  return false;
3054  }
3055 
3056  return true;
3057 }
3058 
3059 bool CChainState::PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
3060 {
3063  {
3064  LOCK(cs_main);
3065  if (pindex->nChainWork < m_chain.Tip()->nChainWork) {
3066  // Nothing to do, this block is not at the tip.
3067  return true;
3068  }
3070  // The chain has been extended since the last call, reset the counter.
3072  }
3074  setBlockIndexCandidates.erase(pindex);
3076  if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
3077  // We can't keep reducing the counter if somebody really wants to
3078  // call preciousblock 2**31-1 times on the same set of tips...
3080  }
3081  if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->HaveTxsDownloaded()) {
3082  setBlockIndexCandidates.insert(pindex);
3084  }
3085  }
3086 
3087  return ActivateBestChain(state, std::shared_ptr<const CBlock>());
3088 }
3089 
3090 bool CChainState::InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex)
3091 {
3094 
3095  // Genesis block can't be invalidated
3096  assert(pindex);
3097  if (pindex->nHeight == 0) return false;
3098 
3099  CBlockIndex* to_mark_failed = pindex;
3100  bool pindex_was_in_chain = false;
3101  int disconnected = 0;
3102 
3103  // We do not allow ActivateBestChain() to run while InvalidateBlock() is
3104  // running, as that could cause the tip to change while we disconnect
3105  // blocks.
3107 
3108  // We'll be acquiring and releasing cs_main below, to allow the validation
3109  // callbacks to run. However, we should keep the block index in a
3110  // consistent state as we disconnect blocks -- in particular we need to
3111  // add equal-work blocks to setBlockIndexCandidates as we disconnect.
3112  // To avoid walking the block index repeatedly in search of candidates,
3113  // build a map once so that we can look up candidate blocks by chain
3114  // work as we go.
3115  std::multimap<const arith_uint256, CBlockIndex *> candidate_blocks_by_work;
3116 
3117  {
3118  LOCK(cs_main);
3119  for (auto& entry : m_blockman.m_block_index) {
3120  CBlockIndex* candidate = &entry.second;
3121  // We don't need to put anything in our active chain into the
3122  // multimap, because those candidates will be found and considered
3123  // as we disconnect.
3124  // Instead, consider only non-active-chain blocks that have at
3125  // least as much work as where we expect the new tip to end up.
3126  if (!m_chain.Contains(candidate) &&
3127  !CBlockIndexWorkComparator()(candidate, pindex->pprev) &&
3128  candidate->IsValid(BLOCK_VALID_TRANSACTIONS) &&
3129  candidate->HaveTxsDownloaded()) {
3130  candidate_blocks_by_work.insert(std::make_pair(candidate->nChainWork, candidate));
3131  }
3132  }
3133  }
3134 
3135  // Disconnect (descendants of) pindex, and mark them invalid.
3136  while (true) {
3137  if (ShutdownRequested()) break;
3138 
3139  // Make sure the queue of validation callbacks doesn't grow unboundedly.
3141 
3142  LOCK(cs_main);
3143  // Lock for as long as disconnectpool is in scope to make sure MaybeUpdateMempoolForReorg is
3144  // called after DisconnectTip without unlocking in between
3145  LOCK(MempoolMutex());
3146  if (!m_chain.Contains(pindex)) break;
3147  pindex_was_in_chain = true;
3148  CBlockIndex *invalid_walk_tip = m_chain.Tip();
3149 
3150  // ActivateBestChain considers blocks already in m_chain
3151  // unconditionally valid already, so force disconnect away from it.
3152  DisconnectedBlockTransactions disconnectpool;
3153  bool ret = DisconnectTip(state, &disconnectpool);
3154  // DisconnectTip will add transactions to disconnectpool.
3155  // Adjust the mempool to be consistent with the new tip, adding
3156  // transactions back to the mempool if disconnecting was successful,
3157  // and we're not doing a very deep invalidation (in which case
3158  // keeping the mempool up to date is probably futile anyway).
3159  MaybeUpdateMempoolForReorg(disconnectpool, /* fAddToMempool = */ (++disconnected <= 10) && ret);
3160  if (!ret) return false;
3161  assert(invalid_walk_tip->pprev == m_chain.Tip());
3162 
3163  // We immediately mark the disconnected blocks as invalid.
3164  // This prevents a case where pruned nodes may fail to invalidateblock
3165  // and be left unable to start as they have no tip candidates (as there
3166  // are no blocks that meet the "have data and are not invalid per
3167  // nStatus" criteria for inclusion in setBlockIndexCandidates).
3168  invalid_walk_tip->nStatus |= BLOCK_FAILED_VALID;
3169  m_blockman.m_dirty_blockindex.insert(invalid_walk_tip);
3170  setBlockIndexCandidates.erase(invalid_walk_tip);
3171  setBlockIndexCandidates.insert(invalid_walk_tip->pprev);
3172  if (invalid_walk_tip->pprev == to_mark_failed && (to_mark_failed->nStatus & BLOCK_FAILED_VALID)) {
3173  // We only want to mark the last disconnected block as BLOCK_FAILED_VALID; its children
3174  // need to be BLOCK_FAILED_CHILD instead.
3175  to_mark_failed->nStatus = (to_mark_failed->nStatus ^ BLOCK_FAILED_VALID) | BLOCK_FAILED_CHILD;
3176  m_blockman.m_dirty_blockindex.insert(to_mark_failed);
3177  }
3178 
3179  // Add any equal or more work headers to setBlockIndexCandidates
3180  auto candidate_it = candidate_blocks_by_work.lower_bound(invalid_walk_tip->pprev->nChainWork);
3181  while (candidate_it != candidate_blocks_by_work.end()) {
3182  if (!CBlockIndexWorkComparator()(candidate_it->second, invalid_walk_tip->pprev)) {
3183  setBlockIndexCandidates.insert(candidate_it->second);
3184  candidate_it = candidate_blocks_by_work.erase(candidate_it);
3185  } else {
3186  ++candidate_it;
3187  }
3188  }
3189 
3190  // Track the last disconnected block, so we can correct its BLOCK_FAILED_CHILD status in future
3191  // iterations, or, if it's the last one, call InvalidChainFound on it.
3192  to_mark_failed = invalid_walk_tip;
3193  }
3194 
3195  CheckBlockIndex();
3196 
3197  {
3198  LOCK(cs_main);
3199  if (m_chain.Contains(to_mark_failed)) {
3200  // If the to-be-marked invalid block is in the active chain, something is interfering and we can't proceed.
3201  return false;
3202  }
3203 
3204  // Mark pindex (or the last disconnected block) as invalid, even when it never was in the main chain
3205  to_mark_failed->nStatus |= BLOCK_FAILED_VALID;
3206  m_blockman.m_dirty_blockindex.insert(to_mark_failed);
3207  setBlockIndexCandidates.erase(to_mark_failed);
3208  m_chainman.m_failed_blocks.insert(to_mark_failed);
3209 
3210  // If any new blocks somehow arrived while we were disconnecting
3211  // (above), then the pre-calculation of what should go into
3212  // setBlockIndexCandidates may have missed entries. This would
3213  // technically be an inconsistency in the block index, but if we clean
3214  // it up here, this should be an essentially unobservable error.
3215  // Loop back over all block index entries and add any missing entries
3216  // to setBlockIndexCandidates.
3217  for (auto& [_, block_index] : m_blockman.m_block_index) {
3218  if (block_index.IsValid(BLOCK_VALID_TRANSACTIONS) && block_index.HaveTxsDownloaded() && !setBlockIndexCandidates.value_comp()(&block_index, m_chain.Tip())) {
3219  setBlockIndexCandidates.insert(&block_index);
3220  }
3221  }
3222 
3223  InvalidChainFound(to_mark_failed);
3224  }
3225 
3226  // Only notify about a new block tip if the active chain was modified.
3227  if (pindex_was_in_chain) {
3228  uiInterface.NotifyBlockTip(GetSynchronizationState(IsInitialBlockDownload()), to_mark_failed->pprev);
3229  }
3230  return true;
3231 }
3232 
3235 
3236  int nHeight = pindex->nHeight;
3237 
3238  // Remove the invalidity flag from this block and all its descendants.
3239  for (auto& [_, block_index] : m_blockman.m_block_index) {
3240  if (!block_index.IsValid() && block_index.GetAncestor(nHeight) == pindex) {
3241  block_index.nStatus &= ~BLOCK_FAILED_MASK;
3242  m_blockman.m_dirty_blockindex.insert(&block_index);
3243  if (block_index.IsValid(BLOCK_VALID_TRANSACTIONS) && block_index.HaveTxsDownloaded() && setBlockIndexCandidates.value_comp()(m_chain.Tip(), &block_index)) {
3244  setBlockIndexCandidates.insert(&block_index);
3245  }
3246  if (&block_index == m_chainman.m_best_invalid) {
3247  // Reset invalid block marker if it was pointing to one of those.
3248  m_chainman.m_best_invalid = nullptr;
3249  }
3250  m_chainman.m_failed_blocks.erase(&block_index);
3251  }
3252  }
3253 
3254  // Remove the invalidity flag from all ancestors too.
3255  while (pindex != nullptr) {
3256  if (pindex->nStatus & BLOCK_FAILED_MASK) {
3257  pindex->nStatus &= ~BLOCK_FAILED_MASK;
3258  m_blockman.m_dirty_blockindex.insert(pindex);
3259  m_chainman.m_failed_blocks.erase(pindex);
3260  }
3261  pindex = pindex->pprev;
3262  }
3263 }
3264 
3266 void CChainState::ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos)
3267 {
3269  pindexNew->nTx = block.vtx.size();
3270  pindexNew->nChainTx = 0;
3271  pindexNew->nFile = pos.nFile;
3272  pindexNew->nDataPos = pos.nPos;
3273  pindexNew->nUndoPos = 0;
3274  pindexNew->nStatus |= BLOCK_HAVE_DATA;
3276  pindexNew->nStatus |= BLOCK_OPT_WITNESS;
3277  }
3279  m_blockman.m_dirty_blockindex.insert(pindexNew);
3280 
3281  if (pindexNew->pprev == nullptr || pindexNew->pprev->HaveTxsDownloaded()) {
3282  // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3283  std::deque<CBlockIndex*> queue;
3284  queue.push_back(pindexNew);
3285 
3286  // Recursively process any descendant blocks that now may be eligible to be connected.
3287  while (!queue.empty()) {
3288  CBlockIndex *pindex = queue.front();
3289  queue.pop_front();
3290  pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3291  pindex->nSequenceId = nBlockSequenceId++;
3292  if (m_chain.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) {
3293  setBlockIndexCandidates.insert(pindex);
3294  }
3295  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = m_blockman.m_blocks_unlinked.equal_range(pindex);
3296  while (range.first != range.second) {
3297  std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3298  queue.push_back(it->second);
3299  range.first++;
3300  m_blockman.m_blocks_unlinked.erase(it);
3301  }
3302  }
3303  } else {
3304  if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3305  m_blockman.m_blocks_unlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3306  }
3307  }
3308 }
3309 
3310 static bool CheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
3311 {
3312  // Check proof of work matches claimed amount
3313  if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
3314  return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "high-hash", "proof of work failed");
3315 
3316  return true;
3317 }
3318 
3319 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
3320 {
3321  // These are checks that are independent of context.
3322 
3323  if (block.fChecked)
3324  return true;
3325 
3326  // Check that the header is valid (particularly PoW). This is mostly
3327  // redundant with the call in AcceptBlockHeader.
3328  if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
3329  return false;
3330 
3331  // Signet only: check block solution
3332  if (consensusParams.signet_blocks && fCheckPOW && !CheckSignetBlockSolution(block, consensusParams)) {
3333  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-signet-blksig", "signet block signature validation failure");
3334  }
3335 
3336  // Check the merkle root.
3337  if (fCheckMerkleRoot) {
3338  bool mutated;
3339  uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
3340  if (block.hashMerkleRoot != hashMerkleRoot2)
3341  return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txnmrklroot", "hashMerkleRoot mismatch");
3342 
3343  // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3344  // of transactions in a block without affecting the merkle root of a block,
3345  // while still invalidating it.
3346  if (mutated)
3347  return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txns-duplicate", "duplicate transaction");
3348  }
3349 
3350  // All potential-corruption validation must be done before we do any
3351  // transaction validation, as otherwise we may mark the header as invalid
3352  // because we receive the wrong transactions for it.
3353  // Note that witness malleability is checked in ContextualCheckBlock, so no
3354  // checks that use witness data may be performed here.
3355 
3356  // Size limits
3358  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-length", "size limits failed");
3359 
3360  // First transaction must be coinbase, the rest must not be
3361  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
3362  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-missing", "first tx is not coinbase");
3363  for (unsigned int i = 1; i < block.vtx.size(); i++)
3364  if (block.vtx[i]->IsCoinBase())
3365  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple", "more than one coinbase");
3366 
3367  // Check transactions
3368  // Must check for duplicate inputs (see CVE-2018-17144)
3369  for (const auto& tx : block.vtx) {
3370  TxValidationState tx_state;
3371  if (!CheckTransaction(*tx, tx_state)) {
3372  // CheckBlock() does context-free validation checks. The only
3373  // possible failures are consensus failures.
3376  strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), tx_state.GetDebugMessage()));
3377  }
3378  }
3379  unsigned int nSigOps = 0;
3380  for (const auto& tx : block.vtx)
3381  {
3382  nSigOps += GetLegacySigOpCount(*tx);
3383  }
3385  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "out-of-bounds SigOpCount");
3386 
3387  if (fCheckPOW && fCheckMerkleRoot)
3388  block.fChecked = true;
3389 
3390  return true;
3391 }
3392 
3393 void ChainstateManager::UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const
3394 {
3395  int commitpos = GetWitnessCommitmentIndex(block);
3396  static const std::vector<unsigned char> nonce(32, 0x00);
3397  if (commitpos != NO_WITNESS_COMMITMENT && DeploymentActiveAfter(pindexPrev, *this, Consensus::DEPLOYMENT_SEGWIT) && !block.vtx[0]->HasWitness()) {
3398  CMutableTransaction tx(*block.vtx[0]);
3399  tx.vin[0].scriptWitness.stack.resize(1);
3400  tx.vin[0].scriptWitness.stack[0] = nonce;
3401  block.vtx[0] = MakeTransactionRef(std::move(tx));
3402  }
3403 }
3404 
3405 std::vector<unsigned char> ChainstateManager::GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const
3406 {
3407  std::vector<unsigned char> commitment;
3408  int commitpos = GetWitnessCommitmentIndex(block);
3409  std::vector<unsigned char> ret(32, 0x00);
3410  if (commitpos == NO_WITNESS_COMMITMENT) {
3411  uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
3412  CHash256().Write(witnessroot).Write(ret).Finalize(witnessroot);
3413  CTxOut out;
3414  out.nValue = 0;
3416  out.scriptPubKey[0] = OP_RETURN;
3417  out.scriptPubKey[1] = 0x24;
3418  out.scriptPubKey[2] = 0xaa;
3419  out.scriptPubKey[3] = 0x21;
3420  out.scriptPubKey[4] = 0xa9;
3421  out.scriptPubKey[5] = 0xed;
3422  memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
3423  commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
3424  CMutableTransaction tx(*block.vtx[0]);
3425  tx.vout.push_back(out);
3426  block.vtx[0] = MakeTransactionRef(std::move(tx));
3427  }
3428  UpdateUncommittedBlockStructures(block, pindexPrev);
3429  return commitment;
3430 }
3431 
3441 static bool ContextualCheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, BlockManager& blockman, const ChainstateManager& chainman, const CBlockIndex* pindexPrev, int64_t nAdjustedTime) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
3442 {
3444  assert(pindexPrev != nullptr);
3445  const int nHeight = pindexPrev->nHeight + 1;
3446 
3447  // Check proof of work
3448  const Consensus::Params& consensusParams = chainman.GetConsensus();
3449  if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3450  return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits", "incorrect proof of work");
3451 
3452  // Check against checkpoints
3453  if (fCheckpointsEnabled) {
3454  // Don't accept any forks from the main chain prior to last checkpoint.
3455  // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
3456  // BlockIndex().
3457  const CBlockIndex* pcheckpoint = blockman.GetLastCheckpoint(chainman.GetParams().Checkpoints());
3458  if (pcheckpoint && nHeight < pcheckpoint->nHeight) {
3459  LogPrintf("ERROR: %s: forked chain older than last checkpoint (height %d)\n", __func__, nHeight);
3460  return state.Invalid(BlockValidationResult::BLOCK_CHECKPOINT, "bad-fork-prior-to-checkpoint");
3461  }
3462  }
3463 
3464  // Check timestamp against prev
3465  if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3466  return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-too-old", "block's timestamp is too early");
3467 
3468  // Check timestamp
3469  if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
3470  return state.Invalid(BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new", "block timestamp too far in the future");
3471 
3472  // Reject blocks with outdated version
3473  if ((block.nVersion < 2 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_HEIGHTINCB)) ||
3474  (block.nVersion < 3 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_DERSIG)) ||
3475  (block.nVersion < 4 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_CLTV))) {
3476  return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, strprintf("bad-version(0x%08x)", block.nVersion),
3477  strprintf("rejected nVersion=0x%08x block", block.nVersion));
3478  }
3479 
3480  return true;
3481 }
3482 
3489 static bool ContextualCheckBlock(const CBlock& block, BlockValidationState& state, const ChainstateManager& chainman, const CBlockIndex* pindexPrev)
3490 {
3491  const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
3492 
3493  // Enforce BIP113 (Median Time Past).
3494  int nLockTimeFlags = 0;
3495  if (DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_CSV)) {
3496  assert(pindexPrev != nullptr);
3497  nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
3498  }
3499 
3500  int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3501  ? pindexPrev->GetMedianTimePast()
3502  : block.GetBlockTime();
3503 
3504  // Check that all transactions are finalized
3505  for (const auto& tx : block.vtx) {
3506  if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
3507  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal", "non-final transaction");
3508  }
3509  }
3510 
3511  // Enforce rule that the coinbase starts with serialized block height
3512  if (DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_HEIGHTINCB))
3513  {
3514  CScript expect = CScript() << nHeight;
3515  if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
3516  !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
3517  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-height", "block height mismatch in coinbase");
3518  }
3519  }
3520 
3521  // Validation for witness commitments.
3522  // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
3523  // coinbase (where 0x0000....0000 is used instead).
3524  // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness reserved value (unconstrained).
3525  // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
3526  // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
3527  // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness reserved value). In case there are
3528  // multiple, the last one is used.
3529  bool fHaveWitness = false;
3530  if (DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_SEGWIT)) {
3531  int commitpos = GetWitnessCommitmentIndex(block);
3532  if (commitpos != NO_WITNESS_COMMITMENT) {
3533  bool malleated = false;
3534  uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
3535  // The malleation check is ignored; as the transaction tree itself
3536  // already does not permit it, it is impossible to trigger in the
3537  // witness tree.
3538  if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3539  return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-nonce-size", strprintf("%s : invalid witness reserved value size", __func__));
3540  }
3541  CHash256().Write(hashWitness).Write(block.vtx[0]->vin[0].scriptWitness.stack[0]).Finalize(hashWitness);
3542  if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3543  return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-merkle-match", strprintf("%s : witness merkle commitment mismatch", __func__));
3544  }
3545  fHaveWitness = true;
3546  }
3547  }
3548 
3549  // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3550  if (!fHaveWitness) {
3551  for (const auto& tx : block.vtx) {
3552  if (tx->HasWitness()) {
3553  return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "unexpected-witness", strprintf("%s : unexpected witness data found", __func__));
3554  }
3555  }
3556  }
3557 
3558  // After the coinbase witness reserved value and commitment are verified,
3559  // we can check if the block weight passes (before we've checked the
3560  // coinbase witness, it would be possible for the weight to be too
3561  // large by filling up the coinbase witness, which doesn't change
3562  // the block hash, so we couldn't mark the block as permanently
3563  // failed).
3564  if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3565  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-weight", strprintf("%s : weight limit failed", __func__));
3566  }
3567 
3568  return true;
3569 }
3570 
3572 {
3574  // Check for duplicate
3575  uint256 hash = block.GetHash();
3576  BlockMap::iterator miSelf{m_blockman.m_block_index.find(hash)};
3577  if (hash != GetConsensus().hashGenesisBlock) {
3578  if (miSelf != m_blockman.m_block_index.end()) {
3579  // Block header is already known.
3580  CBlockIndex* pindex = &(miSelf->second);
3581  if (ppindex)
3582  *ppindex = pindex;
3583  if (pindex->nStatus & BLOCK_FAILED_MASK) {
3584  LogPrint(BCLog::VALIDATION, "%s: block %s is marked invalid\n", __func__, hash.ToString());
3585  return state.Invalid(BlockValidationResult::BLOCK_CACHED_INVALID, "duplicate");
3586  }
3587  return true;
3588  }
3589 
3590  if (!CheckBlockHeader(block, state, GetConsensus())) {
3591  LogPrint(BCLog::VALIDATION, "%s: Consensus::CheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
3592  return false;
3593  }
3594 
3595  // Get prev block index
3596  CBlockIndex* pindexPrev = nullptr;
3597  BlockMap::iterator mi{m_blockman.m_block_index.find(block.hashPrevBlock)};
3598  if (mi == m_blockman.m_block_index.end()) {
3599  LogPrint(BCLog::VALIDATION, "%s: %s prev block not found\n", __func__, hash.ToString());
3600  return state.Invalid(BlockValidationResult::BLOCK_MISSING_PREV, "prev-blk-not-found");
3601  }
3602  pindexPrev = &((*mi).second);
3603  if (pindexPrev->nStatus & BLOCK_FAILED_MASK) {
3604  LogPrint(BCLog::VALIDATION, "%s: %s prev block invalid\n", __func__, hash.ToString());
3605  return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
3606  }
3607  if (!ContextualCheckBlockHeader(block, state, m_blockman, *this, pindexPrev, m_adjusted_time_callback())) {
3608  LogPrint(BCLog::VALIDATION, "%s: Consensus::ContextualCheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
3609  return false;
3610  }
3611 
3612  /* Determine if this block descends from any block which has been found
3613  * invalid (m_failed_blocks), then mark pindexPrev and any blocks between
3614  * them as failed. For example:
3615  *
3616  * D3
3617  * /
3618  * B2 - C2
3619  * / \
3620  * A D2 - E2 - F2
3621  * \
3622  * B1 - C1 - D1 - E1
3623  *
3624  * In the case that we attempted to reorg from E1 to F2, only to find
3625  * C2 to be invalid, we would mark D2, E2, and F2 as BLOCK_FAILED_CHILD
3626  * but NOT D3 (it was not in any of our candidate sets at the time).
3627  *
3628  * In any case D3 will also be marked as BLOCK_FAILED_CHILD at restart
3629  * in LoadBlockIndex.
3630  */
3631  if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
3632  // The above does not mean "invalid": it checks if the previous block
3633  // hasn't been validated up to BLOCK_VALID_SCRIPTS. This is a performance
3634  // optimization, in the common case of adding a new block to the tip,
3635  // we don't need to iterate over the failed blocks list.
3636  for (const CBlockIndex* failedit : m_failed_blocks) {
3637  if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
3638  assert(failedit->nStatus & BLOCK_FAILED_VALID);
3639  CBlockIndex* invalid_walk = pindexPrev;
3640  while (invalid_walk != failedit) {
3641  invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
3642  m_blockman.m_dirty_blockindex.insert(invalid_walk);
3643  invalid_walk = invalid_walk->pprev;
3644  }
3645  LogPrint(BCLog::VALIDATION, "%s: %s prev block invalid\n", __func__, hash.ToString());
3646  return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
3647  }
3648  }
3649  }
3650  }
3652 
3653  if (ppindex)
3654  *ppindex = pindex;
3655 
3656  return true;
3657 }
3658 
3659 // Exposed wrapper for AcceptBlockHeader
3660 bool ChainstateManager::ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, BlockValidationState& state, const CBlockIndex** ppindex)
3661 {
3663  {
3664  LOCK(cs_main);
3665  for (const CBlockHeader& header : headers) {
3666  CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3667  bool accepted{AcceptBlockHeader(header, state, &pindex)};
3669 
3670  if (!accepted) {
3671  return false;
3672  }
3673  if (ppindex) {
3674  *ppindex = pindex;
3675  }
3676  }
3677  }
3679  if (ActiveChainstate().IsInitialBlockDownload() && ppindex && *ppindex) {
3680  const CBlockIndex& last_accepted{**ppindex};
3681  const int64_t blocks_left{(GetTime() - last_accepted.GetBlockTime()) / GetConsensus().nPowTargetSpacing};
3682  const double progress{100.0 * last_accepted.nHeight / (last_accepted.nHeight + blocks_left)};
3683  LogPrintf("Synchronizing blockheaders, height: %d (~%.2f%%)\n", last_accepted.nHeight, progress);
3684  }
3685  }
3686  return true;
3687 }
3688 
3690 bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock)
3691 {
3692  const CBlock& block = *pblock;
3693 
3694  if (fNewBlock) *fNewBlock = false;
3696 
3697  CBlockIndex *pindexDummy = nullptr;
3698  CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3699 
3700  bool accepted_header{m_chainman.AcceptBlockHeader(block, state, &pindex)};
3701  CheckBlockIndex();
3702 
3703  if (!accepted_header)
3704  return false;
3705 
3706  // Try to process all requested blocks that we don't have, but only
3707  // process an unrequested block if it's new and has enough work to
3708  // advance our tip, and isn't too many blocks ahead.
3709  bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3710  bool fHasMoreOrSameWork = (m_chain.Tip() ? pindex->nChainWork >= m_chain.Tip()->nChainWork : true);
3711  // Blocks that are too out-of-order needlessly limit the effectiveness of
3712  // pruning, because pruning will not delete block files that contain any
3713  // blocks which are too close in height to the tip. Apply this test
3714  // regardless of whether pruning is enabled; it should generally be safe to
3715  // not process unrequested blocks.
3716  bool fTooFarAhead{pindex->nHeight > m_chain.Height() + int(MIN_BLOCKS_TO_KEEP)};
3717 
3718  // TODO: Decouple this function from the block download logic by removing fRequested
3719  // This requires some new chain data structure to efficiently look up if a
3720  // block is in a chain leading to a candidate for best tip, despite not
3721  // being such a candidate itself.
3722  // Note that this would break the getblockfrompeer RPC
3723 
3724  // TODO: deal better with return value and error conditions for duplicate
3725  // and unrequested blocks.
3726  if (fAlreadyHave) return true;
3727  if (!fRequested) { // If we didn't ask for it:
3728  if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3729  if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
3730  if (fTooFarAhead) return true; // Block height is too high
3731 
3732  // Protect against DoS attacks from low-work chains.
3733  // If our tip is behind, a peer could try to send us
3734  // low-work blocks on a fake chain that we would never
3735  // request; don't process these.
3736  if (pindex->nChainWork < nMinimumChainWork) return true;
3737  }
3738 
3739  if (!CheckBlock(block, state, m_params.GetConsensus()) ||
3740  !ContextualCheckBlock(block, state, m_chainman, pindex->pprev)) {
3741  if (state.IsInvalid() && state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
3742  pindex->nStatus |= BLOCK_FAILED_VALID;
3743  m_blockman.m_dirty_blockindex.insert(pindex);
3744  }
3745  return error("%s: %s", __func__, state.ToString());
3746  }
3747 
3748  // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3749  // (but if it does not build on our best tip, let the SendMessages loop relay it)
3750  if (!IsInitialBlockDownload() && m_chain.Tip() == pindex->pprev)
3751  GetMainSignals().NewPoWValidBlock(pindex, pblock);
3752 
3753  // Write block to history file
3754  if (fNewBlock) *fNewBlock = true;
3755  try {
3756  FlatFilePos blockPos{m_blockman.SaveBlockToDisk(block, pindex->nHeight, m_chain, m_params, dbp)};
3757  if (blockPos.IsNull()) {
3758  state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
3759  return false;
3760  }
3761  ReceivedBlockTransactions(block, pindex, blockPos);
3762  } catch (const std::runtime_error& e) {
3763  return AbortNode(state, std::string("System error: ") + e.what());
3764  }
3765 
3767 
3768  CheckBlockIndex();
3769 
3770  return true;
3771 }
3772 
3773 bool ChainstateManager::ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool* new_block)
3774 {
3776 
3777  {
3778  CBlockIndex *pindex = nullptr;
3779  if (new_block) *new_block = false;
3780  BlockValidationState state;
3781 
3782  // CheckBlock() does not support multi-threaded block validation because CBlock::fChecked can cause data race.
3783  // Therefore, the following critical section must include the CheckBlock() call as well.
3784  LOCK(cs_main);
3785 
3786  // Skipping AcceptBlock() for CheckBlock() failures means that we will never mark a block as invalid if
3787  // CheckBlock() fails. This is protective against consensus failure if there are any unknown forms of block
3788  // malleability that cause CheckBlock() to fail; see e.g. CVE-2012-2459 and
3789  // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-February/016697.html. Because CheckBlock() is
3790  // not very expensive, the anti-DoS benefits of caching failure (of a definitely-invalid block) are not substantial.
3791  bool ret = CheckBlock(*block, state, GetConsensus());
3792  if (ret) {
3793  // Store to disk
3794  ret = ActiveChainstate().AcceptBlock(block, state, &pindex, force_processing, nullptr, new_block);
3795  }
3796  if (!ret) {
3797  GetMainSignals().BlockChecked(*block, state);
3798  return error("%s: AcceptBlock FAILED (%s)", __func__, state.ToString());
3799  }
3800  }
3801 
3803 
3804  BlockValidationState state; // Only used to report errors, not invalidity - ignore it
3805  if (!ActiveChainstate().ActivateBestChain(state, block)) {
3806  return error("%s: ActivateBestChain failed (%s)", __func__, state.ToString());
3807  }
3808 
3809  return true;
3810 }
3811 
3813 {
3815  CChainState& active_chainstate = ActiveChainstate();
3816  if (!active_chainstate.GetMempool()) {
3817  TxValidationState state;
3818  state.Invalid(TxValidationResult::TX_NO_MEMPOOL, "no-mempool");
3819  return MempoolAcceptResult::Failure(state);
3820  }
3821  auto result = AcceptToMemoryPool(active_chainstate, tx, GetTime(), /*bypass_limits=*/ false, test_accept);
3822  active_chainstate.GetMempool()->check(active_chainstate.CoinsTip(), active_chainstate.m_chain.Height() + 1);
3823  return result;
3824 }
3825 
3827  const CChainParams& chainparams,
3828  CChainState& chainstate,
3829  const CBlock& block,
3830  CBlockIndex* pindexPrev,
3831  const std::function<int64_t()>& adjusted_time_callback,
3832  bool fCheckPOW,
3833  bool fCheckMerkleRoot)
3834 {
3836  assert(pindexPrev && pindexPrev == chainstate.m_chain.Tip());
3837  CCoinsViewCache viewNew(&chainstate.CoinsTip());
3838  uint256 block_hash(block.GetHash());
3839  CBlockIndex indexDummy(block);
3840  indexDummy.pprev = pindexPrev;
3841  indexDummy.nHeight = pindexPrev->nHeight + 1;
3842  indexDummy.phashBlock = &block_hash;
3843 
3844  // NOTE: CheckBlockHeader is called by CheckBlock
3845  if (!ContextualCheckBlockHeader(block, state, chainstate.m_blockman, chainstate.m_chainman, pindexPrev, adjusted_time_callback()))
3846  return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, state.ToString());
3847  if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3848  return error("%s: Consensus::CheckBlock: %s", __func__, state.ToString());
3849  if (!ContextualCheckBlock(block, state, chainstate.m_chainman, pindexPrev))
3850  return error("%s: Consensus::ContextualCheckBlock: %s", __func__, state.ToString());
3851  if (!chainstate.ConnectBlock(block, state, &indexDummy, viewNew, true)) {
3852  return false;
3853  }
3854  assert(state.IsValid());
3855 
3856  return true;
3857 }
3858 
3859 /* This function is called from the RPC code for pruneblockchain */
3860 void PruneBlockFilesManual(CChainState& active_chainstate, int nManualPruneHeight)
3861 {
3862  BlockValidationState state;
3863  if (!active_chainstate.FlushStateToDisk(
3864  state, FlushStateMode::NONE, nManualPruneHeight)) {
3865  LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
3866  }
3867 }
3868 
3870 {
3871  if (!m_mempool) return;
3872  if (args.GetBoolArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
3873  ::LoadMempool(*m_mempool, *this);
3874  }
3876 }
3877 
3879 {
3881  const CCoinsViewCache& coins_cache = CoinsTip();
3882  assert(!coins_cache.GetBestBlock().IsNull()); // Never called when the coins view is empty
3883  const CBlockIndex* tip = m_chain.Tip();
3884 
3885  if (tip && tip->GetBlockHash() == coins_cache.GetBestBlock()) {
3886  return true;
3887  }
3888 
3889  // Load pointer to end of best chain
3890  CBlockIndex* pindex = m_blockman.LookupBlockIndex(coins_cache.GetBestBlock());
3891  if (!pindex) {
3892  return false;
3893  }
3894  m_chain.SetTip(pindex);
3896 
3897  tip = m_chain.Tip();
3898  LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
3899  tip->GetBlockHash().ToString(),
3900  m_chain.Height(),
3903  return true;
3904 }
3905 
3907 {
3908  uiInterface.ShowProgress(_("Verifying blocks…").translated, 0, false);
3909 }
3910 
3912 {
3913  uiInterface.ShowProgress("", 100, false);
3914 }
3915 
3917  CChainState& chainstate,
3918  const Consensus::Params& consensus_params,
3919  CCoinsView& coinsview,
3920  int nCheckLevel, int nCheckDepth)
3921 {
3923 
3924  if (chainstate.m_chain.Tip() == nullptr || chainstate.m_chain.Tip()->pprev == nullptr) {
3925  return true;
3926  }
3927 
3928  // Verify blocks in the best chain
3929  if (nCheckDepth <= 0 || nCheckDepth > chainstate.m_chain.Height()) {
3930  nCheckDepth = chainstate.m_chain.Height();
3931  }
3932  nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3933  LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3934  CCoinsViewCache coins(&coinsview);
3935  CBlockIndex* pindex;
3936  CBlockIndex* pindexFailure = nullptr;
3937  int nGoodTransactions = 0;
3938  BlockValidationState state;
3939  int reportDone = 0;
3940  LogPrintf("[0%%]..."); /* Continued */
3941 
3942  const bool is_snapshot_cs{!chainstate.m_from_snapshot_blockhash};
3943 
3944  for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
3945  const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3946  if (reportDone < percentageDone / 10) {
3947  // report every 10% step
3948  LogPrintf("[%d%%]...", percentageDone); /* Continued */
3949  reportDone = percentageDone / 10;
3950  }
3951  uiInterface.ShowProgress(_("Verifying blocks…").translated, percentageDone, false);
3952  if (pindex->nHeight <= chainstate.m_chain.Height() - nCheckDepth) {
3953  break;
3954  }
3955  if ((fPruneMode || is_snapshot_cs) && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3956  // If pruning or running under an assumeutxo snapshot, only go
3957  // back as far as we have data.
3958  LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3959  break;
3960  }
3961  CBlock block;
3962  // check level 0: read from disk
3963  if (!ReadBlockFromDisk(block, pindex, consensus_params)) {
3964  return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3965  }
3966  // check level 1: verify block validity
3967  if (nCheckLevel >= 1 && !CheckBlock(block, state, consensus_params)) {
3968  return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3969  pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
3970  }
3971  // check level 2: verify undo validity
3972  if (nCheckLevel >= 2 && pindex) {
3973  CBlockUndo undo;
3974  if (!pindex->GetUndoPos().IsNull()) {
3975  if (!UndoReadFromDisk(undo, pindex)) {
3976  return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3977  }
3978  }
3979  }
3980  // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3981  size_t curr_coins_usage = coins.DynamicMemoryUsage() + chainstate.CoinsTip().DynamicMemoryUsage();
3982 
3983  if (nCheckLevel >= 3 && curr_coins_usage <= chainstate.m_coinstip_cache_size_bytes) {
3984  assert(coins.GetBestBlock() == pindex->GetBlockHash());
3985  DisconnectResult res = chainstate.DisconnectBlock(block, pindex, coins);
3986  if (res == DISCONNECT_FAILED) {
3987  return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3988  }
3989  if (res == DISCONNECT_UNCLEAN) {
3990  nGoodTransactions = 0;
3991  pindexFailure = pindex;
3992  } else {
3993  nGoodTransactions += block.vtx.size();
3994  }
3995  }
3996  if (ShutdownRequested()) return true;
3997  }
3998  if (pindexFailure) {
3999  return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainstate.m_chain.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
4000  }
4001 
4002  // store block count as we move pindex at check level >= 4
4003  int block_count = chainstate.m_chain.Height() - pindex->nHeight;
4004 
4005  // check level 4: try reconnecting blocks
4006  if (nCheckLevel >= 4) {
4007  while (pindex != chainstate.m_chain.Tip()) {
4008  const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
4009  if (reportDone < percentageDone / 10) {
4010  // report every 10% step
4011  LogPrintf("[%d%%]...", percentageDone); /* Continued */
4012  reportDone = percentageDone / 10;
4013  }
4014  uiInterface.ShowProgress(_("Verifying blocks…").translated, percentageDone, false);
4015  pindex = chainstate.m_chain.Next(pindex);
4016  CBlock block;
4017  if (!ReadBlockFromDisk(block, pindex, consensus_params))
4018  return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4019  if (!chainstate.ConnectBlock(block, state, pindex, coins)) {
4020  return error("VerifyDB(): *** found unconnectable block at %d, hash=%s (%s)", pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
4021  }
4022  if (ShutdownRequested()) return true;
4023  }
4024  }
4025 
4026  LogPrintf("[DONE].\n");
4027  LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", block_count, nGoodTransactions);
4028 
4029  return true;
4030 }
4031 
4034 {
4036  // TODO: merge with ConnectBlock
4037  CBlock block;
4038  if (!ReadBlockFromDisk(block, pindex, m_params.GetConsensus())) {
4039  return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4040  }
4041 
4042  for (const CTransactionRef& tx : block.vtx) {
4043  if (!tx->IsCoinBase()) {
4044  for (const CTxIn &txin : tx->vin) {
4045  inputs.SpendCoin(txin.prevout);
4046  }
4047  }
4048  // Pass check = true as every addition may be an overwrite.
4049  AddCoins(inputs, *tx, pindex->nHeight, true);
4050  }
4051  return true;
4052 }
4053 
4055 {
4056  LOCK(cs_main);
4057 
4058  CCoinsView& db = this->CoinsDB();
4059  CCoinsViewCache cache(&db);
4060 
4061  std::vector<uint256> hashHeads = db.GetHeadBlocks();
4062  if (hashHeads.empty()) return true; // We're already in a consistent state.
4063  if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
4064 
4065  uiInterface.ShowProgress(_("Replaying blocks…").translated, 0, false);
4066  LogPrintf("Replaying blocks\n");
4067 
4068  const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
4069  const CBlockIndex* pindexNew; // New tip during the interrupted flush.
4070  const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
4071 
4072  if (m_blockman.m_block_index.count(hashHeads[0]) == 0) {
4073  return error("ReplayBlocks(): reorganization to unknown block requested");
4074  }
4075  pindexNew = &(m_blockman.m_block_index[hashHeads[0]]);
4076 
4077  if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
4078  if (m_blockman.m_block_index.count(hashHeads[1]) == 0) {
4079  return error("ReplayBlocks(): reorganization from unknown block requested");
4080  }
4081  pindexOld = &(m_blockman.m_block_index[hashHeads[1]]);
4082  pindexFork = LastCommonAncestor(pindexOld, pindexNew);
4083  assert(pindexFork != nullptr);
4084  }
4085 
4086  // Rollback along the old branch.
4087  while (pindexOld != pindexFork) {
4088  if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
4089  CBlock block;
4090  if (!ReadBlockFromDisk(block, pindexOld, m_params.GetConsensus())) {
4091  return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4092  }
4093  LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
4094  DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
4095  if (res == DISCONNECT_FAILED) {
4096  return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4097  }
4098  // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
4099  // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
4100  // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
4101  // the result is still a version of the UTXO set with the effects of that block undone.
4102  }
4103  pindexOld = pindexOld->pprev;
4104  }
4105 
4106  // Roll forward from the forking point to the new tip.
4107  int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
4108  for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
4109  const CBlockIndex& pindex{*Assert(pindexNew->GetAncestor(nHeight))};
4110 
4111  LogPrintf("Rolling forward %s (%i)\n", pindex.GetBlockHash().ToString(), nHeight);
4112  uiInterface.ShowProgress(_("Replaying blocks…").translated, (int) ((nHeight - nForkHeight) * 100.0 / (pindexNew->nHeight - nForkHeight)) , false);
4113  if (!RollforwardBlock(&pindex, cache)) return false;
4114  }
4115 
4116  cache.SetBestBlock(pindexNew->GetBlockHash());
4117  cache.Flush();
4118  uiInterface.ShowProgress("", 100, false);
4119  return true;
4120 }
4121 
4123 {
4125 
4126  // At and above m_params.SegwitHeight, segwit consensus rules must be validated
4127  CBlockIndex* block{m_chain.Tip()};
4128 
4129  while (block != nullptr && DeploymentActiveAt(*block, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) {
4130  if (!(block->nStatus & BLOCK_OPT_WITNESS)) {
4131  // block is insufficiently validated for a segwit client
4132  return true;
4133  }
4134  block = block->pprev;
4135  }
4136 
4137  return false;
4138 }
4139 
4140 void CChainState::UnloadBlockIndex()
4141 {
4143  nBlockSequenceId = 1;
4144  setBlockIndexCandidates.clear();
4145 }
4146 
4148 {
4150  // Load block index from databases
4151  bool needs_init = fReindex;
4152  if (!fReindex) {
4153  bool ret = m_blockman.LoadBlockIndexDB(GetConsensus());
4154  if (!ret) return false;
4155 
4156  std::vector<CBlockIndex*> vSortedByHeight{m_blockman.GetAllBlockIndices()};
4157  std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
4159 
4160  // Find start of assumed-valid region.
4161  int first_assumed_valid_height = std::numeric_limits<int>::max();
4162 
4163  for (const CBlockIndex* block : vSortedByHeight) {
4164  if (block->IsAssumedValid()) {
4165  auto chainstates = GetAll();
4166 
4167  // If we encounter an assumed-valid block index entry, ensure that we have
4168  // one chainstate that tolerates assumed-valid entries and another that does
4169  // not (i.e. the background validation chainstate), since assumed-valid
4170  // entries should always be pending validation by a fully-validated chainstate.
4171  auto any_chain = [&](auto fnc) { return std::any_of(chainstates.cbegin(), chainstates.cend(), fnc); };
4172  assert(any_chain([](auto chainstate) { return chainstate->reliesOnAssumedValid(); }));
4173  assert(any_chain([](auto chainstate) { return !chainstate->reliesOnAssumedValid(); }));
4174 
4175  first_assumed_valid_height = block->nHeight;
4176  break;
4177  }
4178  }
4179 
4180  for (CBlockIndex* pindex : vSortedByHeight) {
4181  if (ShutdownRequested()) return false;
4182  if (pindex->IsAssumedValid() ||
4183  (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) &&
4184  (pindex->HaveTxsDownloaded() || pindex->pprev == nullptr))) {
4185 
4186  // Fill each chainstate's block candidate set. Only add assumed-valid
4187  // blocks to the tip candidate set if the chainstate is allowed to rely on
4188  // assumed-valid blocks.
4189  //
4190  // If all setBlockIndexCandidates contained the assumed-valid blocks, the
4191  // background chainstate's ActivateBestChain() call would add assumed-valid
4192  // blocks to the chain (based on how FindMostWorkChain() works). Obviously
4193  // we don't want this since the purpose of the background validation chain
4194  // is to validate assued-valid blocks.
4195  //
4196  // Note: This is considering all blocks whose height is greater or equal to
4197  // the first assumed-valid block to be assumed-valid blocks, and excluding
4198  // them from the background chainstate's setBlockIndexCandidates set. This
4199  // does mean that some blocks which are not technically assumed-valid
4200  // (later blocks on a fork beginning before the first assumed-valid block)
4201  // might not get added to the background chainstate, but this is ok,
4202  // because they will still be attached to the active chainstate if they
4203  // actually contain more work.
4204  //
4205  // Instead of this height-based approach, an earlier attempt was made at
4206  // detecting "holistically" whether the block index under consideration
4207  // relied on an assumed-valid ancestor, but this proved to be too slow to
4208  // be practical.
4209  for (CChainState* chainstate : GetAll()) {
4210  if (chainstate->reliesOnAssumedValid() ||
4211  pindex->nHeight < first_assumed_valid_height) {
4212  chainstate->setBlockIndexCandidates.insert(pindex);
4213  }
4214  }
4215  }
4216  if (pindex->nStatus & BLOCK_FAILED_MASK && (!m_best_invalid || pindex->nChainWork > m_best_invalid->nChainWork)) {
4217  m_best_invalid = pindex;
4218  }
4219  if (pindex->IsValid(BLOCK_VALID_TREE) && (m_best_header == nullptr || CBlockIndexWorkComparator()(m_best_header, pindex)))
4220  m_best_header = pindex;
4221  }
4222 
4223  needs_init = m_blockman.m_block_index.empty();
4224  }
4225 
4226  if (needs_init) {
4227  // Everything here is for *new* reindex/DBs. Thus, though
4228  // LoadBlockIndexDB may have set fReindex if we shut down
4229  // mid-reindex previously, we don't check fReindex and
4230  // instead only check it prior to LoadBlockIndexDB to set
4231  // needs_init.
4232 
4233  LogPrintf("Initializing databases...\n");
4234  }
4235  return true;
4236 }
4237 
4239 {
4240  LOCK(cs_main);
4241 
4242  // Check whether we're already initialized by checking for genesis in
4243  // m_blockman.m_block_index. Note that we can't use m_chain here, since it is
4244  // set based on the coins db, not the block index db, which is the only
4245  // thing loaded at this point.
4246  if (m_blockman.m_block_index.count(m_params.GenesisBlock().GetHash()))
4247  return true;
4248 
4249  try {
4250  const CBlock& block = m_params.GenesisBlock();
4251  FlatFilePos blockPos{m_blockman.SaveBlockToDisk(block, 0, m_chain, m_params, nullptr)};
4252  if (blockPos.IsNull()) {
4253  return error("%s: writing genesis block to disk failed", __func__);
4254  }
4256  ReceivedBlockTransactions(block, pindex, blockPos);
4257  } catch (const std::runtime_error& e) {
4258  return error("%s: failed to write genesis block: %s", __func__, e.what());
4259  }
4260 
4261  return true;
4262 }
4263 
4264 void CChainState::LoadExternalBlockFile(FILE* fileIn, FlatFilePos* dbp)
4265 {
4267  // Map of disk positions for blocks with unknown parent (only used for reindex)
4268  static std::multimap<uint256, FlatFilePos> mapBlocksUnknownParent;
4269  int64_t nStart = GetTimeMillis();
4270 
4271  int nLoaded = 0;
4272  try {
4273  // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4275  uint64_t nRewind = blkdat.GetPos();
4276  while (!blkdat.eof()) {
4277  if (ShutdownRequested()) return;
4278 
4279  blkdat.SetPos(nRewind);
4280  nRewind++; // start one byte further next time, in case of failure
4281  blkdat.SetLimit(); // remove former limit
4282  unsigned int nSize = 0;
4283  try {
4284  // locate a header
4285  unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
4286  blkdat.FindByte(m_params.MessageStart()[0]);
4287  nRewind = blkdat.GetPos() + 1;
4288  blkdat >> buf;
4290  continue;
4291  }
4292  // read size
4293  blkdat >> nSize;
4294  if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
4295  continue;
4296  } catch (const std::exception&) {
4297  // no valid block header found; don't complain
4298  break;
4299  }
4300  try {
4301  // read block
4302  uint64_t nBlockPos = blkdat.GetPos();
4303  if (dbp)
4304  dbp->nPos = nBlockPos;
4305  blkdat.SetLimit(nBlockPos + nSize);
4306  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4307  CBlock& block = *pblock;
4308  blkdat >> block;
4309  nRewind = blkdat.GetPos();
4310 
4311  uint256 hash = block.GetHash();
4312  {
4313  LOCK(cs_main);
4314  // detect out of order blocks, and store them for later
4315  if (hash != m_params.GetConsensus().hashGenesisBlock && !m_blockman.LookupBlockIndex(block.hashPrevBlock)) {
4316  LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4317  block.hashPrevBlock.ToString());
4318  if (dbp)
4319  mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4320  continue;
4321  }
4322 
4323  // process in case the block isn't known yet
4324  const CBlockIndex* pindex = m_blockman.LookupBlockIndex(hash);
4325  if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) {
4326  BlockValidationState state;
4327  if (AcceptBlock(pblock, state, nullptr, true, dbp, nullptr)) {
4328  nLoaded++;
4329  }
4330  if (state.IsError()) {
4331  break;
4332  }
4333  } else if (hash != m_params.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
4334  LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
4335  }
4336  }
4337 
4338  // Activate the genesis block so normal node progress can continue
4339  if (hash == m_params.GetConsensus().hashGenesisBlock) {
4340  BlockValidationState state;
4341  if (!ActivateBestChain(state, nullptr)) {
4342  break;
4343  }
4344  }
4345 
4346  NotifyHeaderTip(*this);
4347 
4348  // Recursively process earlier encountered successors of this block
4349  std::deque<uint256> queue;
4350  queue.push_back(hash);
4351  while (!queue.empty()) {
4352  uint256 head = queue.front();
4353  queue.pop_front();
4354  std::pair<std::multimap<uint256, FlatFilePos>::iterator, std::multimap<uint256, FlatFilePos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4355  while (range.first != range.second) {
4356  std::multimap<uint256, FlatFilePos>::iterator it = range.first;
4357  std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4358  if (ReadBlockFromDisk(*pblockrecursive, it->second, m_params.GetConsensus())) {
4359  LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4360  head.ToString());
4361  LOCK(cs_main);
4362  BlockValidationState dummy;
4363  if (AcceptBlock(pblockrecursive, dummy, nullptr, true, &it->second, nullptr)) {
4364  nLoaded++;
4365  queue.push_back(pblockrecursive->GetHash());
4366  }
4367  }
4368  range.first++;
4369  mapBlocksUnknownParent.erase(it);
4370  NotifyHeaderTip(*this);
4371  }
4372  }
4373  } catch (const std::exception& e) {
4374  LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4375  }
4376  }
4377  } catch (const std::runtime_error& e) {
4378  AbortNode(std::string("System error: ") + e.what());
4379  }
4380  LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4381 }
4382 
4384 {
4385  if (!fCheckBlockIndex) {
4386  return;
4387  }
4388 
4389  LOCK(cs_main);
4390 
4391  // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4392  // so we have the genesis block in m_blockman.m_block_index but no active chain. (A few of the
4393  // tests when iterating the block tree require that m_chain has been initialized.)
4394  if (m_chain.Height() < 0) {
4395  assert(m_blockman.m_block_index.size() <= 1);
4396  return;
4397  }
4398 
4399  // Build forward-pointing map of the entire block tree.
4400  std::multimap<CBlockIndex*,CBlockIndex*> forward;
4401  for (auto& [_, block_index] : m_blockman.m_block_index) {
4402  forward.emplace(block_index.pprev, &block_index);
4403  }
4404 
4405  assert(forward.size() == m_blockman.m_block_index.size());
4406 
4407  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4408  CBlockIndex *pindex = rangeGenesis.first->second;
4409  rangeGenesis.first++;
4410  assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4411 
4412  // Iterate over the entire block tree, using depth-first search.
4413  // Along the way, remember whether there are blocks on the path from genesis
4414  // block being explored which are the first to have certain properties.
4415  size_t nNodes = 0;
4416  int nHeight = 0;
4417  CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4418  CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4419  CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4420  CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4421  CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4422  CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4423  CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4424  while (pindex != nullptr) {
4425  nNodes++;
4426  if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4427  // Assumed-valid index entries will not have data since we haven't downloaded the
4428  // full block yet.
4429  if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA) && !pindex->IsAssumedValid()) {
4430  pindexFirstMissing = pindex;
4431  }
4432  if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4433  if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4434 
4435  if (pindex->pprev != nullptr && !pindex->IsAssumedValid()) {
4436  // Skip validity flag checks for BLOCK_ASSUMED_VALID index entries, since these
4437  // *_VALID_MASK flags will not be present for index entries we are temporarily assuming
4438  // valid.
4439  if (pindexFirstNotTransactionsValid == nullptr &&
4440  (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) {
4441  pindexFirstNotTransactionsValid = pindex;
4442  }
4443 
4444  if (pindexFirstNotChainValid == nullptr &&
4445  (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) {
4446  pindexFirstNotChainValid = pindex;
4447  }
4448 
4449  if (pindexFirstNotScriptsValid == nullptr &&
4450  (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) {
4451  pindexFirstNotScriptsValid = pindex;
4452  }
4453  }
4454 
4455  // Begin: actual consistency checks.
4456  if (pindex->pprev == nullptr) {
4457  // Genesis block checks.
4458  assert(pindex->GetBlockHash() == m_params.GetConsensus().hashGenesisBlock); // Genesis block's hash must match.
4459  assert(pindex == m_chain.Genesis()); // The current active chain's genesis block must be this block.
4460  }
4461  if (!pindex->HaveTxsDownloaded()) assert(pindex->nSequenceId <= 0); // nSequenceId can't be set positive for blocks that aren't linked (negative is used for preciousblock)
4462  // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4463  // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4464  // Unless these indexes are assumed valid and pending block download on a
4465  // background chainstate.
4466  if (!m_blockman.m_have_pruned && !pindex->IsAssumedValid()) {
4467  // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4468  assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4469  assert(pindexFirstMissing == pindexFirstNeverProcessed);
4470  } else {
4471  // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4472  if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4473  }
4474  if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4475  if (pindex->IsAssumedValid()) {
4476  // Assumed-valid blocks should have some nTx value.
4477  assert(pindex->nTx > 0);
4478  // Assumed-valid blocks should connect to the main chain.
4479  assert((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE);
4480  } else {
4481  // Otherwise there should only be an nTx value if we have
4482  // actually seen a block's transactions.
4483  assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4484  }
4485  // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to HaveTxsDownloaded().
4486  assert((pindexFirstNeverProcessed == nullptr) == pindex->HaveTxsDownloaded());
4487  assert((pindexFirstNotTransactionsValid == nullptr) == pindex->HaveTxsDownloaded());
4488  assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4489  assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
4490  assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4491  assert(pindexFirstNotTreeValid == nullptr); // All m_blockman.m_block_index entries must at least be TREE valid
4492  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4493  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4494  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4495  if (pindexFirstInvalid == nullptr) {
4496  // Checks for not-invalid blocks.
4497  assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4498  }
4499  if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && pindexFirstNeverProcessed == nullptr) {
4500  if (pindexFirstInvalid == nullptr) {
4501  const bool is_active = this == &m_chainman.ActiveChainstate();
4502 
4503  // If this block sorts at least as good as the current tip and
4504  // is valid and we have all data for its parents, it must be in
4505  // setBlockIndexCandidates. m_chain.Tip() must also be there
4506  // even if some data has been pruned.
4507  //
4508  // Don't perform this check for the background chainstate since
4509  // its setBlockIndexCandidates shouldn't have some entries (i.e. those past the
4510  // snapshot block) which do exist in the block index for the active chainstate.
4511  if (is_active && (pindexFirstMissing == nullptr || pindex == m_chain.Tip())) {
4512  assert(setBlockIndexCandidates.count(pindex));
4513  }
4514  // If some parent is missing, then it could be that this block was in
4515  // setBlockIndexCandidates but had to be removed because of the missing data.
4516  // In this case it must be in m_blocks_unlinked -- see test below.
4517  }
4518  } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4519  assert(setBlockIndexCandidates.count(pindex) == 0);
4520  }
4521  // Check whether this block is in m_blocks_unlinked.
4522  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = m_blockman.m_blocks_unlinked.equal_range(pindex->pprev);
4523  bool foundInUnlinked = false;
4524  while (rangeUnlinked.first != rangeUnlinked.second) {
4525  assert(rangeUnlinked.first->first == pindex->pprev);
4526  if (rangeUnlinked.first->second == pindex) {
4527  foundInUnlinked = true;
4528  break;
4529  }
4530  rangeUnlinked.first++;
4531  }
4532  if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4533  // If this block has block data available, some parent was never received, and has no invalid parents, it must be in m_blocks_unlinked.
4534  assert(foundInUnlinked);
4535  }
4536  if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in m_blocks_unlinked if we don't HAVE_DATA
4537  if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in m_blocks_unlinked.
4538  if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4539  // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4540  assert(m_blockman.m_have_pruned); // We must have pruned.
4541  // This block may have entered m_blocks_unlinked if:
4542  // - it has a descendant that at some point had more work than the
4543  // tip, and
4544  // - we tried switching to that descendant but were missing
4545  // data for some intermediate block between m_chain and the
4546  // tip.
4547  // So if this block is itself better than m_chain.Tip() and it wasn't in
4548  // setBlockIndexCandidates, then it must be in m_blocks_unlinked.
4549  if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4550  if (pindexFirstInvalid == nullptr) {
4551  assert(foundInUnlinked);
4552  }
4553  }
4554  }
4555  // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4556  // End: actual consistency checks.
4557 
4558  // Try descending into the first subnode.
4559  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4560  if (range.first != range.second) {
4561  // A subnode was found.
4562  pindex = range.first->second;
4563  nHeight++;
4564  continue;
4565  }
4566  // This is a leaf node.
4567  // Move upwards until we reach a node of which we have not yet visited the last child.
4568  while (pindex) {
4569  // We are going to either move to a parent or a sibling of pindex.
4570  // If pindex was the first with a certain property, unset the corresponding variable.
4571  if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4572  if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4573  if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4574  if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4575  if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4576  if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4577  if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4578  // Find our parent.
4579  CBlockIndex* pindexPar = pindex->pprev;
4580  // Find which child we just visited.
4581  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4582  while (rangePar.first->second != pindex) {
4583  assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4584  rangePar.first++;
4585  }
4586  // Proceed to the next one.
4587  rangePar.first++;
4588  if (rangePar.first != rangePar.second) {
4589  // Move to the sibling.
4590  pindex = rangePar.first->second;
4591  break;
4592  } else {
4593  // Move up further.
4594  pindex = pindexPar;
4595  nHeight--;
4596  continue;
4597  }
4598  }
4599  }
4600 
4601  // Check that we actually traversed the entire map.
4602  assert(nNodes == forward.size());
4603 }
4604 
4605 std::string CChainState::ToString()
4606 {
4608  CBlockIndex* tip = m_chain.Tip();
4609  return strprintf("Chainstate [%s] @ height %d (%s)",
4610  m_from_snapshot_blockhash ? "snapshot" : "ibd",
4611  tip ? tip->nHeight : -1, tip ? tip->GetBlockHash().ToString() : "null");
4612 }
4613 
4614 bool CChainState::ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
4615 {
4617  if (coinstip_size == m_coinstip_cache_size_bytes &&
4618  coinsdb_size == m_coinsdb_cache_size_bytes) {
4619  // Cache sizes are unchanged, no need to continue.
4620  return true;
4621  }
4622  size_t old_coinstip_size = m_coinstip_cache_size_bytes;
4623  m_coinstip_cache_size_bytes = coinstip_size;
4624  m_coinsdb_cache_size_bytes = coinsdb_size;
4625  CoinsDB().ResizeCache(coinsdb_size);
4626 
4627  LogPrintf("[%s] resized coinsdb cache to %.1f MiB\n",
4628  this->ToString(), coinsdb_size * (1.0 / 1024 / 1024));
4629  LogPrintf("[%s] resized coinstip cache to %.1f MiB\n",
4630  this->ToString(), coinstip_size * (1.0 / 1024 / 1024));
4631 
4632  BlockValidationState state;
4633  bool ret;
4634 
4635  if (coinstip_size > old_coinstip_size) {
4636  // Likely no need to flush if cache sizes have grown.
4638  } else {
4639  // Otherwise, flush state to disk and deallocate the in-memory coins map.
4642  }
4643  return ret;
4644 }
4645 
4646 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4647 
4648 bool LoadMempool(CTxMemPool& pool, CChainState& active_chainstate, FopenFn mockable_fopen_function)
4649 {
4650  int64_t nExpiryTimeout = gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4651  FILE* filestr{mockable_fopen_function(gArgs.GetDataDirNet() / "mempool.dat", "rb")};
4652  CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4653  if (file.IsNull()) {
4654  LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4655  return false;
4656  }
4657 
4658  int64_t count = 0;
4659  int64_t expired = 0;
4660  int64_t failed = 0;
4661  int64_t already_there = 0;
4662  int64_t unbroadcast = 0;
4663  int64_t nNow = GetTime();
4664 
4665  try {
4666  uint64_t version;
4667  file >> version;
4668  if (version != MEMPOOL_DUMP_VERSION) {
4669  return false;
4670  }
4671  uint64_t num;
4672  file >> num;
4673  while (num) {
4674  --num;
4675  CTransactionRef tx;
4676  int64_t nTime;
4677  int64_t nFeeDelta;
4678  file >> tx;
4679  file >> nTime;
4680  file >> nFeeDelta;
4681 
4682  CAmount amountdelta = nFeeDelta;
4683  if (amountdelta) {
4684  pool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4685  }
4686  if (nTime > nNow - nExpiryTimeout) {
4687  LOCK(cs_main);
4688  const auto& accepted = AcceptToMemoryPool(active_chainstate, tx, nTime, /*bypass_limits=*/false, /*test_accept=*/false);
4689  if (accepted.m_result_type == MempoolAcceptResult::ResultType::VALID) {
4690  ++count;
4691  } else {
4692  // mempool may contain the transaction already, e.g. from
4693  // wallet(s) having loaded it while we were processing
4694  // mempool transactions; consider these as valid, instead of
4695  // failed, but mark them as 'already there'
4696  if (pool.exists(GenTxid::Txid(tx->GetHash()))) {
4697  ++already_there;
4698  } else {
4699  ++failed;
4700  }
4701  }
4702  } else {
4703  ++expired;
4704  }
4705  if (ShutdownRequested())
4706  return false;
4707  }
4708  std::map<uint256, CAmount> mapDeltas;
4709  file >> mapDeltas;
4710 
4711  for (const auto& i : mapDeltas) {
4712  pool.PrioritiseTransaction(i.first, i.second);
4713  }
4714 
4715  std::set<uint256> unbroadcast_txids;
4716  file >> unbroadcast_txids;
4717  unbroadcast = unbroadcast_txids.size();
4718  for (const auto& txid : unbroadcast_txids) {
4719  // Ensure transactions were accepted to mempool then add to
4720  // unbroadcast set.
4721  if (pool.get(txid) != nullptr) pool.AddUnbroadcastTx(txid);
4722  }
4723  } catch (const std::exception& e) {
4724  LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4725  return false;
4726  }
4727 
4728  LogPrintf("Imported mempool transactions from disk: %i succeeded, %i failed, %i expired, %i already there, %i waiting for initial broadcast\n", count, failed, expired, already_there, unbroadcast);
4729  return true;
4730 }
4731 
4732 bool DumpMempool(const CTxMemPool& pool, FopenFn mockable_fopen_function, bool skip_file_commit)
4733 {
4734  int64_t start = GetTimeMicros();
4735 
4736  std::map<uint256, CAmount> mapDeltas;
4737  std::vector<TxMempoolInfo> vinfo;
4738  std::set<uint256> unbroadcast_txids;
4739 
4740  static Mutex dump_mutex;
4741  LOCK(dump_mutex);
4742 
4743  {
4744  LOCK(pool.cs);
4745  for (const auto &i : pool.mapDeltas) {
4746  mapDeltas[i.first] = i.second;
4747  }
4748  vinfo = pool.infoAll();
4749  unbroadcast_txids = pool.GetUnbroadcastTxs();
4750  }
4751 
4752  int64_t mid = GetTimeMicros();
4753 
4754  try {
4755  FILE* filestr{mockable_fopen_function(gArgs.GetDataDirNet() / "mempool.dat.new", "wb")};
4756  if (!filestr) {
4757  return false;
4758  }
4759 
4760  CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4761 
4762  uint64_t version = MEMPOOL_DUMP_VERSION;
4763  file << version;
4764 
4765  file << (uint64_t)vinfo.size();
4766  for (const auto& i : vinfo) {
4767  file << *(i.tx);
4768  file << int64_t{count_seconds(i.m_time)};
4769  file << int64_t{i.nFeeDelta};
4770  mapDeltas.erase(i.tx->GetHash());
4771  }
4772 
4773  file << mapDeltas;
4774 
4775  LogPrintf("Writing %d unbroadcast transactions to disk.\n", unbroadcast_txids.size());
4776  file << unbroadcast_txids;
4777 
4778  if (!skip_file_commit && !FileCommit(file.Get()))
4779  throw std::runtime_error("FileCommit failed");
4780  file.fclose();
4781  if (!RenameOver(gArgs.GetDataDirNet() / "mempool.dat.new", gArgs.GetDataDirNet() / "mempool.dat")) {
4782  throw std::runtime_error("Rename failed");
4783  }
4784  int64_t last = GetTimeMicros();
4785  LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
4786  } catch (const std::exception& e) {
4787  LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4788  return false;
4789  }
4790  return true;
4791 }
4792 
4795 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex *pindex) {
4796  if (pindex == nullptr)
4797  return 0.0;
4798 
4799  int64_t nNow = time(nullptr);
4800 
4801  double fTxTotal;
4802 
4803  if (pindex->nChainTx <= data.nTxCount) {
4804  fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4805  } else {
4806  fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4807  }
4808 
4809  return std::min<double>(pindex->nChainTx / fTxTotal, 1.0);
4810 }
4811 
4812 std::optional<uint256> ChainstateManager::SnapshotBlockhash() const
4813 {
4814  LOCK(::cs_main);
4815  if (m_active_chainstate && m_active_chainstate->m_from_snapshot_blockhash) {
4816  // If a snapshot chainstate exists, it will always be our active.
4817  return m_active_chainstate->m_from_snapshot_blockhash;
4818  }
4819  return std::nullopt;
4820 }
4821 
4822 std::vector<CChainState*> ChainstateManager::GetAll()
4823 {
4824  LOCK(::cs_main);
4825  std::vector<CChainState*> out;
4826 
4827  if (!IsSnapshotValidated() && m_ibd_chainstate) {
4828  out.push_back(m_ibd_chainstate.get());
4829  }
4830 
4831  if (m_snapshot_chainstate) {
4832  out.push_back(m_snapshot_chainstate.get());
4833  }
4834 
4835  return out;
4836 }
4837 
4838 CChainState& ChainstateManager::InitializeChainstate(
4839  CTxMemPool* mempool, const std::optional<uint256>& snapshot_blockhash)
4840 {
4842  bool is_snapshot = snapshot_blockhash.has_value();
4843  std::unique_ptr<CChainState>& to_modify =
4844  is_snapshot ? m_snapshot_chainstate : m_ibd_chainstate;
4845 
4846  if (to_modify) {
4847  throw std::logic_error("should not be overwriting a chainstate");
4848  }
4849  to_modify.reset(new CChainState(mempool, m_blockman, *this, snapshot_blockhash));
4850 
4851  // Snapshot chainstates and initial IBD chaintates always become active.
4852  if (is_snapshot || (!is_snapshot && !m_active_chainstate)) {
4853  LogPrintf("Switching active chainstate to %s\n", to_modify->ToString());
4854  m_active_chainstate = to_modify.get();
4855  } else {
4856  throw std::logic_error("unexpected chainstate activation");
4857  }
4858 
4859  return *to_modify;
4860 }
4861 
4863  const int height, const CChainParams& chainparams)
4864 {
4865  const MapAssumeutxo& valid_assumeutxos_map = chainparams.Assumeutxo();
4866  const auto assumeutxo_found = valid_assumeutxos_map.find(height);
4867 
4868  if (assumeutxo_found != valid_assumeutxos_map.end()) {
4869  return &assumeutxo_found->second;
4870  }
4871  return nullptr;
4872 }
4873 
4875  CAutoFile& coins_file,
4876  const SnapshotMetadata& metadata,
4877  bool in_memory)
4878 {
4879  uint256 base_blockhash = metadata.m_base_blockhash;
4880 
4881  if (this->SnapshotBlockhash()) {
4882  LogPrintf("[snapshot] can't activate a snapshot-based chainstate more than once\n");
4883  return false;
4884  }
4885 
4886  int64_t current_coinsdb_cache_size{0};
4887  int64_t current_coinstip_cache_size{0};
4888 
4889  // Cache percentages to allocate to each chainstate.
4890  //
4891  // These particular percentages don't matter so much since they will only be
4892  // relevant during snapshot activation; caches are rebalanced at the conclusion of
4893  // this function. We want to give (essentially) all available cache capacity to the
4894  // snapshot to aid the bulk load later in this function.
4895  static constexpr double IBD_CACHE_PERC = 0.01;
4896  static constexpr double SNAPSHOT_CACHE_PERC = 0.99;
4897 
4898  {
4899  LOCK(::cs_main);
4900  // Resize the coins caches to ensure we're not exceeding memory limits.
4901  //
4902  // Allocate the majority of the cache to the incoming snapshot chainstate, since
4903  // (optimistically) getting to its tip will be the top priority. We'll need to call
4904  // `MaybeRebalanceCaches()` once we're done with this function to ensure
4905  // the right allocation (including the possibility that no snapshot was activated
4906  // and that we should restore the active chainstate caches to their original size).
4907  //
4908  current_coinsdb_cache_size = this->ActiveChainstate().m_coinsdb_cache_size_bytes;
4909  current_coinstip_cache_size = this->ActiveChainstate().m_coinstip_cache_size_bytes;
4910 
4911  // Temporarily resize the active coins cache to make room for the newly-created
4912  // snapshot chain.
4913  this->ActiveChainstate().ResizeCoinsCaches(
4914  static_cast<size_t>(current_coinstip_cache_size * IBD_CACHE_PERC),
4915  static_cast<size_t>(current_coinsdb_cache_size * IBD_CACHE_PERC));
4916  }
4917 
4918  auto snapshot_chainstate = WITH_LOCK(::cs_main,
4919  return std::make_unique<CChainState>(
4920  /*mempool=*/nullptr, m_blockman, *this, base_blockhash));
4921 
4922  {
4923  LOCK(::cs_main);
4924  snapshot_chainstate->InitCoinsDB(
4925  static_cast<size_t>(current_coinsdb_cache_size * SNAPSHOT_CACHE_PERC),
4926  in_memory, false, "chainstate");
4927  snapshot_chainstate->InitCoinsCache(
4928  static_cast<size_t>(current_coinstip_cache_size * SNAPSHOT_CACHE_PERC));
4929  }
4930 
4931  const bool snapshot_ok = this->PopulateAndValidateSnapshot(
4932  *snapshot_chainstate, coins_file, metadata);
4933 
4934  if (!snapshot_ok) {
4935  WITH_LOCK(::cs_main, this->MaybeRebalanceCaches());
4936  return false;
4937  }
4938 
4939  {
4940  LOCK(::cs_main);
4941  assert(!m_snapshot_chainstate);
4942  m_snapshot_chainstate.swap(snapshot_chainstate);
4943  const bool chaintip_loaded = m_snapshot_chainstate->LoadChainTip();
4944  assert(chaintip_loaded);
4945 
4946  m_active_chainstate = m_snapshot_chainstate.get();
4947 
4948  LogPrintf("[snapshot] successfully activated snapshot %s\n", base_blockhash.ToString());
4949  LogPrintf("[snapshot] (%.2f MB)\n",
4950  m_snapshot_chainstate->CoinsTip().DynamicMemoryUsage() / (1000 * 1000));
4951 
4952  this->MaybeRebalanceCaches();
4953  }
4954  return true;
4955 }
4956 
4957 static void FlushSnapshotToDisk(CCoinsViewCache& coins_cache, bool snapshot_loaded)
4958 {
4960  strprintf("%s (%.2f MB)",
4961  snapshot_loaded ? "saving snapshot chainstate" : "flushing coins cache",
4962  coins_cache.DynamicMemoryUsage() / (1000 * 1000)),
4964 
4965  coins_cache.Flush();
4966 }
4967 
4969  CChainState& snapshot_chainstate,
4970  CAutoFile& coins_file,
4971  const SnapshotMetadata& metadata)
4972 {
4973  // It's okay to release cs_main before we're done using `coins_cache` because we know
4974  // that nothing else will be referencing the newly created snapshot_chainstate yet.
4975  CCoinsViewCache& coins_cache = *WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsTip());
4976 
4977  uint256 base_blockhash = metadata.m_base_blockhash;
4978 
4979  CBlockIndex* snapshot_start_block = WITH_LOCK(::cs_main, return m_blockman.LookupBlockIndex(base_blockhash));
4980 
4981  if (!snapshot_start_block) {
4982  // Needed for ComputeUTXOStats and ExpectedAssumeutxo to determine the
4983  // height and to avoid a crash when base_blockhash.IsNull()
4984  LogPrintf("[snapshot] Did not find snapshot start blockheader %s\n",
4985  base_blockhash.ToString());
4986  return false;
4987  }
4988 
4989  int base_height = snapshot_start_block->nHeight;
4990  auto maybe_au_data = ExpectedAssumeutxo(base_height, GetParams());
4991 
4992  if (!maybe_au_data) {
4993  LogPrintf("[snapshot] assumeutxo height in snapshot metadata not recognized " /* Continued */
4994  "(%d) - refusing to load snapshot\n", base_height);
4995  return false;
4996  }
4997 
4998  const AssumeutxoData& au_data = *maybe_au_data;
4999 
5000  COutPoint outpoint;
5001  Coin coin;
5002  const uint64_t coins_count = metadata.m_coins_count;
5003  uint64_t coins_left = metadata.m_coins_count;
5004 
5005  LogPrintf("[snapshot] loading coins from snapshot %s\n", base_blockhash.ToString());
5006  int64_t coins_processed{0};
5007 
5008  while (coins_left > 0) {
5009  try {
5010  coins_file >> outpoint;
5011  coins_file >> coin;
5012  } catch (const std::ios_base::failure&) {
5013  LogPrintf("[snapshot] bad snapshot format or truncated snapshot after deserializing %d coins\n",
5014  coins_count - coins_left);
5015  return false;
5016  }
5017  if (coin.nHeight > base_height ||
5018  outpoint.n >= std::numeric_limits<decltype(outpoint.n)>::max() // Avoid integer wrap-around in coinstats.cpp:ApplyHash
5019  ) {
5020  LogPrintf("[snapshot] bad snapshot data after deserializing %d coins\n",
5021  coins_count - coins_left);
5022  return false;
5023  }
5024 
5025  coins_cache.EmplaceCoinInternalDANGER(std::move(outpoint), std::move(coin));
5026 
5027  --coins_left;
5028  ++coins_processed;
5029 
5030  if (coins_processed % 1000000 == 0) {
5031  LogPrintf("[snapshot] %d coins loaded (%.2f%%, %.2f MB)\n",
5032  coins_processed,
5033  static_cast<float>(coins_processed) * 100 / static_cast<float>(coins_count),
5034  coins_cache.DynamicMemoryUsage() / (1000 * 1000));
5035  }
5036 
5037  // Batch write and flush (if we need to) every so often.
5038  //
5039  // If our average Coin size is roughly 41 bytes, checking every 120,000 coins
5040  // means <5MB of memory imprecision.
5041  if (coins_processed % 120000 == 0) {
5042  if (ShutdownRequested()) {
5043  return false;
5044  }
5045 
5046  const auto snapshot_cache_state = WITH_LOCK(::cs_main,
5047  return snapshot_chainstate.GetCoinsCacheSizeState());