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