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