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