Bitcoin Core  0.21.1
P2P Digital Currency
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules
validation.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <validation.h>
7 
8 #include <arith_uint256.h>
9 #include <chain.h>
10 #include <chainparams.h>
11 #include <checkqueue.h>
12 #include <consensus/consensus.h>
13 #include <consensus/merkle.h>
14 #include <consensus/tx_check.h>
15 #include <consensus/tx_verify.h>
16 #include <consensus/validation.h>
17 #include <cuckoocache.h>
18 #include <flatfile.h>
19 #include <hash.h>
20 #include <index/txindex.h>
21 #include <logging.h>
22 #include <logging/timer.h>
23 #include <node/ui_interface.h>
24 #include <optional.h>
25 #include <policy/fees.h>
26 #include <policy/policy.h>
27 #include <policy/settings.h>
28 #include <pow.h>
29 #include <primitives/block.h>
30 #include <primitives/transaction.h>
31 #include <random.h>
32 #include <reverse_iterator.h>
33 #include <script/script.h>
34 #include <script/sigcache.h>
35 #include <shutdown.h>
36 #include <signet.h>
37 #include <timedata.h>
38 #include <tinyformat.h>
39 #include <txdb.h>
40 #include <txmempool.h>
41 #include <uint256.h>
42 #include <undo.h>
43 #include <util/check.h> // For NDEBUG compile time check
44 #include <util/moneystr.h>
45 #include <util/rbf.h>
46 #include <util/strencodings.h>
47 #include <util/system.h>
48 #include <util/translation.h>
49 #include <validationinterface.h>
50 #include <warnings.h>
51 
52 #include <string>
53 
54 #include <boost/algorithm/string/replace.hpp>
55 
56 #define MICRO 0.000001
57 #define MILLI 0.001
58 
64 static const unsigned int EXTRA_DESCENDANT_TX_SIZE_LIMIT = 10000;
66 static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000;
68 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
70 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
72 static constexpr std::chrono::hours DATABASE_WRITE_INTERVAL{1};
74 static constexpr std::chrono::hours DATABASE_FLUSH_INTERVAL{24};
76 static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE{3};
77 const std::vector<std::string> CHECKLEVEL_DOC {
78  "level 0 reads the blocks from disk",
79  "level 1 verifies block validity",
80  "level 2 verifies undo data",
81  "level 3 checks disconnection of tip blocks",
82  "level 4 tries to reconnect the blocks",
83  "each level includes the checks of the previous levels",
84 };
85 
87  // First sort by most total work, ...
88  if (pa->nChainWork > pb->nChainWork) return false;
89  if (pa->nChainWork < pb->nChainWork) return true;
90 
91  // ... then by earliest time received, ...
92  if (pa->nSequenceId < pb->nSequenceId) return false;
93  if (pa->nSequenceId > pb->nSequenceId) return true;
94 
95  // Use pointer address as tie breaker (should only happen with blocks
96  // loaded from disk, as those all have id 0).
97  if (pa < pb) return false;
98  if (pa > pb) return true;
99 
100  // Identical blocks.
101  return false;
102 }
103 
105 
107 {
108  LOCK(::cs_main);
109  assert(g_chainman.m_active_chainstate);
110  return *g_chainman.m_active_chainstate;
111 }
112 
114 {
115  LOCK(::cs_main);
117 }
118 
130 
133 std::condition_variable g_best_block_cv;
136 std::atomic_bool fImporting(false);
137 std::atomic_bool fReindex(false);
138 bool fHavePruned = false;
139 bool fPruneMode = false;
140 bool fRequireStandard = true;
141 bool fCheckBlockIndex = false;
143 uint64_t nPruneTarget = 0;
145 
148 
150 
152 
153 // Internal stuff
154 namespace {
155  CBlockIndex* pindexBestInvalid = nullptr;
156 
157  RecursiveMutex cs_LastBlockFile;
158  std::vector<CBlockFileInfo> vinfoBlockFile;
159  int nLastBlockFile = 0;
164  bool fCheckForPruning = false;
165 
167  std::set<CBlockIndex*> setDirtyBlockIndex;
168 
170  std::set<int> setDirtyFileInfo;
171 } // anon namespace
172 
174 {
175  AssertLockHeld(cs_main);
176  BlockMap::const_iterator it = g_chainman.BlockIndex().find(hash);
177  return it == g_chainman.BlockIndex().end() ? nullptr : it->second;
178 }
179 
181 {
182  AssertLockHeld(cs_main);
183 
184  // Find the latest block common to locator and chain - we expect that
185  // locator.vHave is sorted descending by height.
186  for (const uint256& hash : locator.vHave) {
187  CBlockIndex* pindex = LookupBlockIndex(hash);
188  if (pindex) {
189  if (chain.Contains(pindex))
190  return pindex;
191  if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
192  return chain.Tip();
193  }
194  }
195  }
196  return chain.Genesis();
197 }
198 
199 std::unique_ptr<CBlockTreeDB> pblocktree;
200 
201 bool CheckInputScripts(const CTransaction& tx, TxValidationState &state, const CCoinsViewCache &inputs, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks = nullptr);
202 static FILE* OpenUndoFile(const FlatFilePos &pos, bool fReadOnly = false);
203 static FlatFileSeq BlockFileSeq();
204 static FlatFileSeq UndoFileSeq();
205 
206 bool CheckFinalTx(const CTransaction &tx, int flags)
207 {
208  AssertLockHeld(cs_main);
209 
210  // By convention a negative value for flags indicates that the
211  // current network-enforced consensus rules should be used. In
212  // a future soft-fork scenario that would mean checking which
213  // rules would be enforced for the next block and setting the
214  // appropriate flags. At the present time no soft-forks are
215  // scheduled, so no flags are set.
216  flags = std::max(flags, 0);
217 
218  // CheckFinalTx() uses ::ChainActive().Height()+1 to evaluate
219  // nLockTime because when IsFinalTx() is called within
220  // CBlock::AcceptBlock(), the height of the block *being*
221  // evaluated is what is used. Thus if we want to know if a
222  // transaction can be part of the *next* block, we need to call
223  // IsFinalTx() with one more than ::ChainActive().Height().
224  const int nBlockHeight = ::ChainActive().Height() + 1;
225 
226  // BIP113 requires that time-locked transactions have nLockTime set to
227  // less than the median time of the previous block they're contained in.
228  // When the next block is created its previous block will be the current
229  // chain tip, so we use that to calculate the median time passed to
230  // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
231  const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
233  : GetAdjustedTime();
234 
235  return IsFinalTx(tx, nBlockHeight, nBlockTime);
236 }
237 
239 {
240  AssertLockHeld(cs_main);
241  assert(lp);
242  // If there are relative lock times then the maxInputBlock will be set
243  // If there are no relative lock times, the LockPoints don't depend on the chain
244  if (lp->maxInputBlock) {
245  // Check whether ::ChainActive() is an extension of the block at which the LockPoints
246  // calculation was valid. If not LockPoints are no longer valid
247  if (!::ChainActive().Contains(lp->maxInputBlock)) {
248  return false;
249  }
250  }
251 
252  // LockPoints still valid
253  return true;
254 }
255 
256 bool CheckSequenceLocks(const CTxMemPool& pool, const CTransaction& tx, int flags, LockPoints* lp, bool useExistingLockPoints)
257 {
258  AssertLockHeld(cs_main);
259  AssertLockHeld(pool.cs);
260 
261  CBlockIndex* tip = ::ChainActive().Tip();
262  assert(tip != nullptr);
263 
264  CBlockIndex index;
265  index.pprev = tip;
266  // CheckSequenceLocks() uses ::ChainActive().Height()+1 to evaluate
267  // height based locks because when SequenceLocks() is called within
268  // ConnectBlock(), the height of the block *being*
269  // evaluated is what is used.
270  // Thus if we want to know if a transaction can be part of the
271  // *next* block, we need to use one more than ::ChainActive().Height()
272  index.nHeight = tip->nHeight + 1;
273 
274  std::pair<int, int64_t> lockPair;
275  if (useExistingLockPoints) {
276  assert(lp);
277  lockPair.first = lp->height;
278  lockPair.second = lp->time;
279  }
280  else {
281  // CoinsTip() contains the UTXO set for ::ChainActive().Tip()
282  CCoinsViewMemPool viewMemPool(&::ChainstateActive().CoinsTip(), pool);
283  std::vector<int> prevheights;
284  prevheights.resize(tx.vin.size());
285  for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
286  const CTxIn& txin = tx.vin[txinIndex];
287  Coin coin;
288  if (!viewMemPool.GetCoin(txin.prevout, coin)) {
289  return error("%s: Missing input", __func__);
290  }
291  if (coin.nHeight == MEMPOOL_HEIGHT) {
292  // Assume all mempool transaction confirm in the next block
293  prevheights[txinIndex] = tip->nHeight + 1;
294  } else {
295  prevheights[txinIndex] = coin.nHeight;
296  }
297  }
298  lockPair = CalculateSequenceLocks(tx, flags, prevheights, index);
299  if (lp) {
300  lp->height = lockPair.first;
301  lp->time = lockPair.second;
302  // Also store the hash of the block with the highest height of
303  // all the blocks which have sequence locked prevouts.
304  // This hash needs to still be on the chain
305  // for these LockPoint calculations to be valid
306  // Note: It is impossible to correctly calculate a maxInputBlock
307  // if any of the sequence locked inputs depend on unconfirmed txs,
308  // except in the special case where the relative lock time/height
309  // is 0, which is equivalent to no sequence lock. Since we assume
310  // input height of tip+1 for mempool txs and test the resulting
311  // lockPair from CalculateSequenceLocks against tip+1. We know
312  // EvaluateSequenceLocks will fail if there was a non-zero sequence
313  // lock on a mempool input, so we can use the return value of
314  // CheckSequenceLocks to indicate the LockPoints validity
315  int maxInputHeight = 0;
316  for (const int height : prevheights) {
317  // Can ignore mempool inputs since we'll fail if they had non-zero locks
318  if (height != tip->nHeight+1) {
319  maxInputHeight = std::max(maxInputHeight, height);
320  }
321  }
322  lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
323  }
324  }
325  return EvaluateSequenceLocks(index, lockPair);
326 }
327 
328 // Returns the script flags which should be checked for a given block
329 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
330 
331 static void LimitMempoolSize(CTxMemPool& pool, size_t limit, std::chrono::seconds age)
332  EXCLUSIVE_LOCKS_REQUIRED(pool.cs, ::cs_main)
333 {
334  int expired = pool.Expire(GetTime<std::chrono::seconds>() - age);
335  if (expired != 0) {
336  LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
337  }
338 
339  std::vector<COutPoint> vNoSpendsRemaining;
340  pool.TrimToSize(limit, &vNoSpendsRemaining);
341  for (const COutPoint& removed : vNoSpendsRemaining)
342  ::ChainstateActive().CoinsTip().Uncache(removed);
343 }
344 
346 {
347  AssertLockHeld(cs_main);
348  if (::ChainstateActive().IsInitialBlockDownload())
349  return false;
350  if (::ChainActive().Tip()->GetBlockTime() < count_seconds(GetTime<std::chrono::seconds>() - MAX_FEE_ESTIMATION_TIP_AGE))
351  return false;
352  if (::ChainActive().Height() < pindexBestHeader->nHeight - 1)
353  return false;
354  return true;
355 }
356 
357 /* Make mempool consistent after a reorg, by re-adding or recursively erasing
358  * disconnected block transactions from the mempool, and also removing any
359  * other transactions from the mempool that are no longer valid given the new
360  * tip/height.
361  *
362  * Note: we assume that disconnectpool only contains transactions that are NOT
363  * confirmed in the current chain nor already in the mempool (otherwise,
364  * in-mempool descendants of such transactions would be removed).
365  *
366  * Passing fAddToMempool=false will skip trying to add the transactions back,
367  * and instead just erase from the mempool as needed.
368  */
369 
370 static void UpdateMempoolForReorg(CTxMemPool& mempool, DisconnectedBlockTransactions& disconnectpool, bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, mempool.cs)
371 {
372  AssertLockHeld(cs_main);
373  AssertLockHeld(mempool.cs);
374  std::vector<uint256> vHashUpdate;
375  // disconnectpool's insertion_order index sorts the entries from
376  // oldest to newest, but the oldest entry will be the last tx from the
377  // latest mined block that was disconnected.
378  // Iterate disconnectpool in reverse, so that we add transactions
379  // back to the mempool starting with the earliest transaction that had
380  // been previously seen in a block.
381  auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
382  while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
383  // ignore validation errors in resurrected transactions
384  TxValidationState stateDummy;
385  if (!fAddToMempool || (*it)->IsCoinBase() ||
386  !AcceptToMemoryPool(mempool, stateDummy, *it,
387  nullptr /* plTxnReplaced */, true /* bypass_limits */)) {
388  // If the transaction doesn't make it in to the mempool, remove any
389  // transactions that depend on it (which would now be orphans).
390  mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
391  } else if (mempool.exists((*it)->GetHash())) {
392  vHashUpdate.push_back((*it)->GetHash());
393  }
394  ++it;
395  }
396  disconnectpool.queuedTx.clear();
397  // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
398  // no in-mempool children, which is generally not true when adding
399  // previously-confirmed transactions back to the mempool.
400  // UpdateTransactionsFromBlock finds descendants of any transactions in
401  // the disconnectpool that were added back and cleans up the mempool state.
402  mempool.UpdateTransactionsFromBlock(vHashUpdate);
403 
404  // We also need to remove any now-immature transactions
405  mempool.removeForReorg(&::ChainstateActive().CoinsTip(), ::ChainActive().Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
406  // Re-limit mempool size, in case we added any transactions
407  LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
408 }
409 
410 // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
411 // were somehow broken and returning the wrong scriptPubKeys
412 static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, TxValidationState& state, const CCoinsViewCache& view, const CTxMemPool& pool,
413  unsigned int flags, PrecomputedTransactionData& txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
414  AssertLockHeld(cs_main);
415 
416  // pool.cs should be locked already, but go ahead and re-take the lock here
417  // to enforce that mempool doesn't change between when we check the view
418  // and when we actually call through to CheckInputScripts
419  LOCK(pool.cs);
420 
421  assert(!tx.IsCoinBase());
422  for (const CTxIn& txin : tx.vin) {
423  const Coin& coin = view.AccessCoin(txin.prevout);
424 
425  // AcceptToMemoryPoolWorker has already checked that the coins are
426  // available, so this shouldn't fail. If the inputs are not available
427  // here then return false.
428  if (coin.IsSpent()) return false;
429 
430  // Check equivalence for available inputs.
431  const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
432  if (txFrom) {
433  assert(txFrom->GetHash() == txin.prevout.hash);
434  assert(txFrom->vout.size() > txin.prevout.n);
435  assert(txFrom->vout[txin.prevout.n] == coin.out);
436  } else {
437  const Coin& coinFromDisk = ::ChainstateActive().CoinsTip().AccessCoin(txin.prevout);
438  assert(!coinFromDisk.IsSpent());
439  assert(coinFromDisk.out == coin.out);
440  }
441  }
442 
443  // Call CheckInputScripts() to cache signature and script validity against current tip consensus rules.
444  return CheckInputScripts(tx, state, view, flags, /* cacheSigStore = */ true, /* cacheFullSciptStore = */ true, txdata);
445 }
446 
447 namespace {
448 
449 class MemPoolAccept
450 {
451 public:
452  MemPoolAccept(CTxMemPool& mempool) : m_pool(mempool), m_view(&m_dummy), m_viewmempool(&::ChainstateActive().CoinsTip(), m_pool),
453  m_limit_ancestors(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT)),
454  m_limit_ancestor_size(gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000),
455  m_limit_descendants(gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT)),
456  m_limit_descendant_size(gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000) {}
457 
458  // We put the arguments we're handed into a struct, so we can pass them
459  // around easier.
460  struct ATMPArgs {
461  const CChainParams& m_chainparams;
462  TxValidationState &m_state;
463  const int64_t m_accept_time;
464  std::list<CTransactionRef>* m_replaced_transactions;
465  const bool m_bypass_limits;
466  /*
467  * Return any outpoints which were not previously present in the coins
468  * cache, but were added as a result of validating the tx for mempool
469  * acceptance. This allows the caller to optionally remove the cache
470  * additions if the associated transaction ends up being rejected by
471  * the mempool.
472  */
473  std::vector<COutPoint>& m_coins_to_uncache;
474  const bool m_test_accept;
475  CAmount* m_fee_out;
476  };
477 
478  // Single transaction acceptance
479  bool AcceptSingleTransaction(const CTransactionRef& ptx, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
480 
481 private:
482  // All the intermediate state that gets passed between the various levels
483  // of checking a given transaction.
484  struct Workspace {
485  Workspace(const CTransactionRef& ptx) : m_ptx(ptx), m_hash(ptx->GetHash()) {}
486  std::set<uint256> m_conflicts;
487  CTxMemPool::setEntries m_all_conflicting;
488  CTxMemPool::setEntries m_ancestors;
489  std::unique_ptr<CTxMemPoolEntry> m_entry;
490 
491  bool m_replacement_transaction;
492  CAmount m_modified_fees;
493  CAmount m_conflicting_fees;
494  size_t m_conflicting_size;
495 
496  const CTransactionRef& m_ptx;
497  const uint256& m_hash;
498  };
499 
500  // Run the policy checks on a given transaction, excluding any script checks.
501  // Looks up inputs, calculates feerate, considers replacement, evaluates
502  // package limits, etc. As this function can be invoked for "free" by a peer,
503  // only tests that are fast should be done here (to avoid CPU DoS).
504  bool PreChecks(ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
505 
506  // Run the script checks using our policy flags. As this can be slow, we should
507  // only invoke this on transactions that have otherwise passed policy checks.
508  bool PolicyScriptChecks(ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
509 
510  // Re-run the script checks, using consensus flags, and try to cache the
511  // result in the scriptcache. This should be done after
512  // PolicyScriptChecks(). This requires that all inputs either be in our
513  // utxo set or in the mempool.
514  bool ConsensusScriptChecks(ATMPArgs& args, Workspace& ws, PrecomputedTransactionData &txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
515 
516  // Try to add the transaction to the mempool, removing any conflicts first.
517  // Returns true if the transaction is in the mempool after any size
518  // limiting is performed, false otherwise.
519  bool Finalize(ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
520 
521  // Compare a package's feerate against minimum allowed.
522  bool CheckFeeRate(size_t package_size, CAmount package_fee, TxValidationState& state)
523  {
524  CAmount mempoolRejectFee = m_pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(package_size);
525  if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) {
526  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool min fee not met", strprintf("%d < %d", package_fee, mempoolRejectFee));
527  }
528 
529  if (package_fee < ::minRelayTxFee.GetFee(package_size)) {
530  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "min relay fee not met", strprintf("%d < %d", package_fee, ::minRelayTxFee.GetFee(package_size)));
531  }
532  return true;
533  }
534 
535 private:
536  CTxMemPool& m_pool;
537  CCoinsViewCache m_view;
538  CCoinsViewMemPool m_viewmempool;
539  CCoinsView m_dummy;
540 
541  // The package limits in effect at the time of invocation.
542  const size_t m_limit_ancestors;
543  const size_t m_limit_ancestor_size;
544  // These may be modified while evaluating a transaction (eg to account for
545  // in-mempool conflicts; see below).
546  size_t m_limit_descendants;
547  size_t m_limit_descendant_size;
548 };
549 
550 bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
551 {
552  const CTransactionRef& ptx = ws.m_ptx;
553  const CTransaction& tx = *ws.m_ptx;
554  const uint256& hash = ws.m_hash;
555 
556  // Copy/alias what we need out of args
557  TxValidationState &state = args.m_state;
558  const int64_t nAcceptTime = args.m_accept_time;
559  const bool bypass_limits = args.m_bypass_limits;
560  std::vector<COutPoint>& coins_to_uncache = args.m_coins_to_uncache;
561 
562  // Alias what we need out of ws
563  std::set<uint256>& setConflicts = ws.m_conflicts;
564  CTxMemPool::setEntries& allConflicting = ws.m_all_conflicting;
565  CTxMemPool::setEntries& setAncestors = ws.m_ancestors;
566  std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
567  bool& fReplacementTransaction = ws.m_replacement_transaction;
568  CAmount& nModifiedFees = ws.m_modified_fees;
569  CAmount& nConflictingFees = ws.m_conflicting_fees;
570  size_t& nConflictingSize = ws.m_conflicting_size;
571 
572  if (!CheckTransaction(tx, state)) {
573  return false; // state filled in by CheckTransaction
574  }
575 
576  // Coinbase is only valid in a block, not as a loose transaction
577  if (tx.IsCoinBase())
578  return state.Invalid(TxValidationResult::TX_CONSENSUS, "coinbase");
579 
580  // Rather not work on nonstandard transactions (unless -testnet/-regtest)
581  std::string reason;
582  if (fRequireStandard && !IsStandardTx(tx, reason))
583  return state.Invalid(TxValidationResult::TX_NOT_STANDARD, reason);
584 
585  // Do not work on transactions that are too small.
586  // A transaction with 1 segwit input and 1 P2WPHK output has non-witness size of 82 bytes.
587  // Transactions smaller than this are not relayed to mitigate CVE-2017-12842 by not relaying
588  // 64-byte transactions.
590  return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "tx-size-small");
591 
592  // Only accept nLockTime-using transactions that can be mined in the next
593  // block; we don't want our mempool filled up with transactions that can't
594  // be mined yet.
596  return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-final");
597 
598  // is it already in the memory pool?
599  if (m_pool.exists(hash)) {
600  return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-in-mempool");
601  }
602 
603  // Check for conflicts with in-memory transactions
604  for (const CTxIn &txin : tx.vin)
605  {
606  const CTransaction* ptxConflicting = m_pool.GetConflictTx(txin.prevout);
607  if (ptxConflicting) {
608  if (!setConflicts.count(ptxConflicting->GetHash()))
609  {
610  // Allow opt-out of transaction replacement by setting
611  // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
612  //
613  // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
614  // non-replaceable transactions. All inputs rather than just one
615  // is for the sake of multi-party protocols, where we don't
616  // want a single party to be able to disable replacement.
617  //
618  // The opt-out ignores descendants as anyone relying on
619  // first-seen mempool behavior should be checking all
620  // unconfirmed ancestors anyway; doing otherwise is hopelessly
621  // insecure.
622  bool fReplacementOptOut = true;
623  for (const CTxIn &_txin : ptxConflicting->vin)
624  {
625  if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
626  {
627  fReplacementOptOut = false;
628  break;
629  }
630  }
631  if (fReplacementOptOut) {
632  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "txn-mempool-conflict");
633  }
634 
635  setConflicts.insert(ptxConflicting->GetHash());
636  }
637  }
638  }
639 
640  LockPoints lp;
641  m_view.SetBackend(m_viewmempool);
642 
643  CCoinsViewCache& coins_cache = ::ChainstateActive().CoinsTip();
644  // do all inputs exist?
645  for (const CTxIn& txin : tx.vin) {
646  if (!coins_cache.HaveCoinInCache(txin.prevout)) {
647  coins_to_uncache.push_back(txin.prevout);
648  }
649 
650  // Note: this call may add txin.prevout to the coins cache
651  // (coins_cache.cacheCoins) by way of FetchCoin(). It should be removed
652  // later (via coins_to_uncache) if this tx turns out to be invalid.
653  if (!m_view.HaveCoin(txin.prevout)) {
654  // Are inputs missing because we already have the tx?
655  for (size_t out = 0; out < tx.vout.size(); out++) {
656  // Optimistically just do efficient check of cache for outputs
657  if (coins_cache.HaveCoinInCache(COutPoint(hash, out))) {
658  return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-known");
659  }
660  }
661  // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
662  return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent");
663  }
664  }
665 
666  // Bring the best block into scope
667  m_view.GetBestBlock();
668 
669  // we have all inputs cached now, so switch back to dummy (to protect
670  // against bugs where we pull more inputs from disk that miss being added
671  // to coins_to_uncache)
672  m_view.SetBackend(m_dummy);
673 
674  // Only accept BIP68 sequence locked transactions that can be mined in the next
675  // block; we don't want our mempool filled up with transactions that can't
676  // be mined yet.
677  // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
678  // CoinsViewCache instead of create its own
679  if (!CheckSequenceLocks(m_pool, tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
680  return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-BIP68-final");
681 
682  CAmount nFees = 0;
683  if (!Consensus::CheckTxInputs(tx, state, m_view, GetSpendHeight(m_view), nFees)) {
684  return false; // state filled in by CheckTxInputs
685  }
686 
687  // If fee_out is passed, return the fee to the caller
688  if (args.m_fee_out) {
689  *args.m_fee_out = nFees;
690  }
691 
692  // Check for non-standard pay-to-script-hash in inputs
693  const auto& params = args.m_chainparams.GetConsensus();
694  auto taproot_state = VersionBitsState(::ChainActive().Tip(), params, Consensus::DEPLOYMENT_TAPROOT, versionbitscache);
695  if (fRequireStandard && !AreInputsStandard(tx, m_view, taproot_state == ThresholdState::ACTIVE)) {
696  return state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs");
697  }
698 
699  // Check for non-standard witness in P2WSH
700  if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, m_view))
701  return state.Invalid(TxValidationResult::TX_WITNESS_MUTATED, "bad-witness-nonstandard");
702 
703  int64_t nSigOpsCost = GetTransactionSigOpCost(tx, m_view, STANDARD_SCRIPT_VERIFY_FLAGS);
704 
705  // nModifiedFees includes any fee deltas from PrioritiseTransaction
706  nModifiedFees = nFees;
707  m_pool.ApplyDelta(hash, nModifiedFees);
708 
709  // Keep track of transactions that spend a coinbase, which we re-scan
710  // during reorgs to ensure COINBASE_MATURITY is still met.
711  bool fSpendsCoinbase = false;
712  for (const CTxIn &txin : tx.vin) {
713  const Coin &coin = m_view.AccessCoin(txin.prevout);
714  if (coin.IsCoinBase()) {
715  fSpendsCoinbase = true;
716  break;
717  }
718  }
719 
720  entry.reset(new CTxMemPoolEntry(ptx, nFees, nAcceptTime, ::ChainActive().Height(),
721  fSpendsCoinbase, nSigOpsCost, lp));
722  unsigned int nSize = entry->GetTxSize();
723 
724  if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
725  return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "bad-txns-too-many-sigops",
726  strprintf("%d", nSigOpsCost));
727 
728  // No transactions are allowed below minRelayTxFee except from disconnected
729  // blocks
730  if (!bypass_limits && !CheckFeeRate(nSize, nModifiedFees, state)) return false;
731 
732  const CTxMemPool::setEntries setIterConflicting = m_pool.GetIterSet(setConflicts);
733  // Calculate in-mempool ancestors, up to a limit.
734  if (setConflicts.size() == 1) {
735  // In general, when we receive an RBF transaction with mempool conflicts, we want to know whether we
736  // would meet the chain limits after the conflicts have been removed. However, there isn't a practical
737  // way to do this short of calculating the ancestor and descendant sets with an overlay cache of
738  // changed mempool entries. Due to both implementation and runtime complexity concerns, this isn't
739  // very realistic, thus we only ensure a limited set of transactions are RBF'able despite mempool
740  // conflicts here. Importantly, we need to ensure that some transactions which were accepted using
741  // the below carve-out are able to be RBF'ed, without impacting the security the carve-out provides
742  // for off-chain contract systems (see link in the comment below).
743  //
744  // Specifically, the subset of RBF transactions which we allow despite chain limits are those which
745  // conflict directly with exactly one other transaction (but may evict children of said transaction),
746  // and which are not adding any new mempool dependencies. Note that the "no new mempool dependencies"
747  // check is accomplished later, so we don't bother doing anything about it here, but if BIP 125 is
748  // amended, we may need to move that check to here instead of removing it wholesale.
749  //
750  // Such transactions are clearly not merging any existing packages, so we are only concerned with
751  // ensuring that (a) no package is growing past the package size (not count) limits and (b) we are
752  // not allowing something to effectively use the (below) carve-out spot when it shouldn't be allowed
753  // to.
754  //
755  // To check these we first check if we meet the RBF criteria, above, and increment the descendant
756  // limits by the direct conflict and its descendants (as these are recalculated in
757  // CalculateMempoolAncestors by assuming the new transaction being added is a new descendant, with no
758  // removals, of each parent's existing dependent set). The ancestor count limits are unmodified (as
759  // the ancestor limits should be the same for both our new transaction and any conflicts).
760  // We don't bother incrementing m_limit_descendants by the full removal count as that limit never comes
761  // into force here (as we're only adding a single transaction).
762  assert(setIterConflicting.size() == 1);
763  CTxMemPool::txiter conflict = *setIterConflicting.begin();
764 
765  m_limit_descendants += 1;
766  m_limit_descendant_size += conflict->GetSizeWithDescendants();
767  }
768 
769  std::string errString;
770  if (!m_pool.CalculateMemPoolAncestors(*entry, setAncestors, m_limit_ancestors, m_limit_ancestor_size, m_limit_descendants, m_limit_descendant_size, errString)) {
771  setAncestors.clear();
772  // If CalculateMemPoolAncestors fails second time, we want the original error string.
773  std::string dummy_err_string;
774  // Contracting/payment channels CPFP carve-out:
775  // If the new transaction is relatively small (up to 40k weight)
776  // and has at most one ancestor (ie ancestor limit of 2, including
777  // the new transaction), allow it if its parent has exactly the
778  // descendant limit descendants.
779  //
780  // This allows protocols which rely on distrusting counterparties
781  // being able to broadcast descendants of an unconfirmed transaction
782  // to be secure by simply only having two immediately-spendable
783  // outputs - one for each counterparty. For more info on the uses for
784  // this, see https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html
785  if (nSize > EXTRA_DESCENDANT_TX_SIZE_LIMIT ||
786  !m_pool.CalculateMemPoolAncestors(*entry, setAncestors, 2, m_limit_ancestor_size, m_limit_descendants + 1, m_limit_descendant_size + EXTRA_DESCENDANT_TX_SIZE_LIMIT, dummy_err_string)) {
787  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too-long-mempool-chain", errString);
788  }
789  }
790 
791  // A transaction that spends outputs that would be replaced by it is invalid. Now
792  // that we have the set of all ancestors we can detect this
793  // pathological case by making sure setConflicts and setAncestors don't
794  // intersect.
795  for (CTxMemPool::txiter ancestorIt : setAncestors)
796  {
797  const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
798  if (setConflicts.count(hashAncestor))
799  {
800  return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-spends-conflicting-tx",
801  strprintf("%s spends conflicting transaction %s",
802  hash.ToString(),
803  hashAncestor.ToString()));
804  }
805  }
806 
807  // Check if it's economically rational to mine this transaction rather
808  // than the ones it replaces.
809  nConflictingFees = 0;
810  nConflictingSize = 0;
811  uint64_t nConflictingCount = 0;
812 
813  // If we don't hold the lock allConflicting might be incomplete; the
814  // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
815  // mempool consistency for us.
816  fReplacementTransaction = setConflicts.size();
817  if (fReplacementTransaction)
818  {
819  CFeeRate newFeeRate(nModifiedFees, nSize);
820  std::set<uint256> setConflictsParents;
821  const int maxDescendantsToVisit = 100;
822  for (const auto& mi : setIterConflicting) {
823  // Don't allow the replacement to reduce the feerate of the
824  // mempool.
825  //
826  // We usually don't want to accept replacements with lower
827  // feerates than what they replaced as that would lower the
828  // feerate of the next block. Requiring that the feerate always
829  // be increased is also an easy-to-reason about way to prevent
830  // DoS attacks via replacements.
831  //
832  // We only consider the feerates of transactions being directly
833  // replaced, not their indirect descendants. While that does
834  // mean high feerate children are ignored when deciding whether
835  // or not to replace, we do require the replacement to pay more
836  // overall fees too, mitigating most cases.
837  CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
838  if (newFeeRate <= oldFeeRate)
839  {
840  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee",
841  strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
842  hash.ToString(),
843  newFeeRate.ToString(),
844  oldFeeRate.ToString()));
845  }
846 
847  for (const CTxIn &txin : mi->GetTx().vin)
848  {
849  setConflictsParents.insert(txin.prevout.hash);
850  }
851 
852  nConflictingCount += mi->GetCountWithDescendants();
853  }
854  // This potentially overestimates the number of actual descendants
855  // but we just want to be conservative to avoid doing too much
856  // work.
857  if (nConflictingCount <= maxDescendantsToVisit) {
858  // If not too many to replace, then calculate the set of
859  // transactions that would have to be evicted
860  for (CTxMemPool::txiter it : setIterConflicting) {
861  m_pool.CalculateDescendants(it, allConflicting);
862  }
863  for (CTxMemPool::txiter it : allConflicting) {
864  nConflictingFees += it->GetModifiedFee();
865  nConflictingSize += it->GetTxSize();
866  }
867  } else {
868  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too many potential replacements",
869  strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
870  hash.ToString(),
871  nConflictingCount,
872  maxDescendantsToVisit));
873  }
874 
875  for (unsigned int j = 0; j < tx.vin.size(); j++)
876  {
877  // We don't want to accept replacements that require low
878  // feerate junk to be mined first. Ideally we'd keep track of
879  // the ancestor feerates and make the decision based on that,
880  // but for now requiring all new inputs to be confirmed works.
881  //
882  // Note that if you relax this to make RBF a little more useful,
883  // this may break the CalculateMempoolAncestors RBF relaxation,
884  // above. See the comment above the first CalculateMempoolAncestors
885  // call for more info.
886  if (!setConflictsParents.count(tx.vin[j].prevout.hash))
887  {
888  // Rather than check the UTXO set - potentially expensive -
889  // it's cheaper to just check if the new input refers to a
890  // tx that's in the mempool.
891  if (m_pool.exists(tx.vin[j].prevout.hash)) {
892  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "replacement-adds-unconfirmed",
893  strprintf("replacement %s adds unconfirmed input, idx %d",
894  hash.ToString(), j));
895  }
896  }
897  }
898 
899  // The replacement must pay greater fees than the transactions it
900  // replaces - if we did the bandwidth used by those conflicting
901  // transactions would not be paid for.
902  if (nModifiedFees < nConflictingFees)
903  {
904  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee",
905  strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
906  hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
907  }
908 
909  // Finally in addition to paying more fees than the conflicts the
910  // new transaction must pay for its own bandwidth.
911  CAmount nDeltaFees = nModifiedFees - nConflictingFees;
912  if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
913  {
914  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee",
915  strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
916  hash.ToString(),
917  FormatMoney(nDeltaFees),
919  }
920  }
921  return true;
922 }
923 
924 bool MemPoolAccept::PolicyScriptChecks(ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata)
925 {
926  const CTransaction& tx = *ws.m_ptx;
927 
928  TxValidationState &state = args.m_state;
929 
930  constexpr unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
931 
932  // Check input scripts and signatures.
933  // This is done last to help prevent CPU exhaustion denial-of-service attacks.
934  if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, false, txdata)) {
935  // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
936  // need to turn both off, and compare against just turning off CLEANSTACK
937  // to see if the failure is specifically due to witness validation.
938  TxValidationState state_dummy; // Want reported failures to be from first CheckInputScripts
939  if (!tx.HasWitness() && CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
940  !CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
941  // Only the witness is missing, so the transaction itself may be fine.
943  state.GetRejectReason(), state.GetDebugMessage());
944  }
945  return false; // state filled in by CheckInputScripts
946  }
947 
948  return true;
949 }
950 
951 bool MemPoolAccept::ConsensusScriptChecks(ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata)
952 {
953  const CTransaction& tx = *ws.m_ptx;
954  const uint256& hash = ws.m_hash;
955 
956  TxValidationState &state = args.m_state;
957  const CChainParams& chainparams = args.m_chainparams;
958 
959  // Check again against the current block tip's script verification
960  // flags to cache our script execution flags. This is, of course,
961  // useless if the next block has different script flags from the
962  // previous one, but because the cache tracks script flags for us it
963  // will auto-invalidate and we'll just have a few blocks of extra
964  // misses on soft-fork activation.
965  //
966  // This is also useful in case of bugs in the standard flags that cause
967  // transactions to pass as valid when they're actually invalid. For
968  // instance the STRICTENC flag was incorrectly allowing certain
969  // CHECKSIG NOT scripts to pass, even though they were invalid.
970  //
971  // There is a similar check in CreateNewBlock() to prevent creating
972  // invalid blocks (using TestBlockValidity), however allowing such
973  // transactions into the mempool can be exploited as a DoS attack.
974  unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(::ChainActive().Tip(), chainparams.GetConsensus());
975  if (!CheckInputsFromMempoolAndCache(tx, state, m_view, m_pool, currentBlockScriptVerifyFlags, txdata)) {
976  return error("%s: BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not STANDARD flags %s, %s",
977  __func__, hash.ToString(), state.ToString());
978  }
979 
980  return true;
981 }
982 
983 bool MemPoolAccept::Finalize(ATMPArgs& args, Workspace& ws)
984 {
985  const CTransaction& tx = *ws.m_ptx;
986  const uint256& hash = ws.m_hash;
987  TxValidationState &state = args.m_state;
988  const bool bypass_limits = args.m_bypass_limits;
989 
990  CTxMemPool::setEntries& allConflicting = ws.m_all_conflicting;
991  CTxMemPool::setEntries& setAncestors = ws.m_ancestors;
992  const CAmount& nModifiedFees = ws.m_modified_fees;
993  const CAmount& nConflictingFees = ws.m_conflicting_fees;
994  const size_t& nConflictingSize = ws.m_conflicting_size;
995  const bool fReplacementTransaction = ws.m_replacement_transaction;
996  std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
997 
998  // Remove conflicting transactions from the mempool
999  for (CTxMemPool::txiter it : allConflicting)
1000  {
1001  LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s additional fees, %d delta bytes\n",
1002  it->GetTx().GetHash().ToString(),
1003  hash.ToString(),
1004  FormatMoney(nModifiedFees - nConflictingFees),
1005  (int)entry->GetTxSize() - (int)nConflictingSize);
1006  if (args.m_replaced_transactions)
1007  args.m_replaced_transactions->push_back(it->GetSharedTx());
1008  }
1009  m_pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
1010 
1011  // This transaction should only count for fee estimation if:
1012  // - it isn't a BIP 125 replacement transaction (may not be widely supported)
1013  // - it's not being re-added during a reorg which bypasses typical mempool fee limits
1014  // - the node is not behind
1015  // - the transaction is not dependent on any other transactions in the mempool
1016  bool validForFeeEstimation = !fReplacementTransaction && !bypass_limits && IsCurrentForFeeEstimation() && m_pool.HasNoInputsOf(tx);
1017 
1018  // Store transaction in memory
1019  m_pool.addUnchecked(*entry, setAncestors, validForFeeEstimation);
1020 
1021  // trim mempool and check if tx was trimmed
1022  if (!bypass_limits) {
1023  LimitMempoolSize(m_pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
1024  if (!m_pool.exists(hash))
1025  return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
1026  }
1027  return true;
1028 }
1029 
1030 bool MemPoolAccept::AcceptSingleTransaction(const CTransactionRef& ptx, ATMPArgs& args)
1031 {
1032  AssertLockHeld(cs_main);
1033  LOCK(m_pool.cs); // mempool "read lock" (held through GetMainSignals().TransactionAddedToMempool())
1034 
1035  Workspace workspace(ptx);
1036 
1037  if (!PreChecks(args, workspace)) return false;
1038 
1039  // Only compute the precomputed transaction data if we need to verify
1040  // scripts (ie, other policy checks pass). We perform the inexpensive
1041  // checks first and avoid hashing and signature verification unless those
1042  // checks pass, to mitigate CPU exhaustion denial-of-service attacks.
1044 
1045  if (!PolicyScriptChecks(args, workspace, txdata)) return false;
1046 
1047  if (!ConsensusScriptChecks(args, workspace, txdata)) return false;
1048 
1049  // Tx was accepted, but not added
1050  if (args.m_test_accept) return true;
1051 
1052  if (!Finalize(args, workspace)) return false;
1053 
1054  GetMainSignals().TransactionAddedToMempool(ptx, m_pool.GetAndIncrementSequence());
1055 
1056  return true;
1057 }
1058 
1059 } // anon namespace
1060 
1062 static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, TxValidationState &state, const CTransactionRef &tx,
1063  int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
1064  bool bypass_limits, bool test_accept, CAmount* fee_out=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
1065 {
1066  std::vector<COutPoint> coins_to_uncache;
1067  MemPoolAccept::ATMPArgs args { chainparams, state, nAcceptTime, plTxnReplaced, bypass_limits, coins_to_uncache, test_accept, fee_out };
1068  bool res = MemPoolAccept(pool).AcceptSingleTransaction(tx, args);
1069  if (!res) {
1070  // Remove coins that were not present in the coins cache before calling ATMPW;
1071  // this is to prevent memory DoS in case we receive a large number of
1072  // invalid transactions that attempt to overrun the in-memory coins cache
1073  // (`CCoinsViewCache::cacheCoins`).
1074 
1075  for (const COutPoint& hashTx : coins_to_uncache)
1076  ::ChainstateActive().CoinsTip().Uncache(hashTx);
1077  }
1078  // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
1079  BlockValidationState state_dummy;
1080  ::ChainstateActive().FlushStateToDisk(chainparams, state_dummy, FlushStateMode::PERIODIC);
1081  return res;
1082 }
1083 
1085  std::list<CTransactionRef>* plTxnReplaced,
1086  bool bypass_limits, bool test_accept, CAmount* fee_out)
1087 {
1088  const CChainParams& chainparams = Params();
1089  return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, GetTime(), plTxnReplaced, bypass_limits, test_accept, fee_out);
1090 }
1091 
1092 CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const uint256& hash, const Consensus::Params& consensusParams, uint256& hashBlock)
1093 {
1094  LOCK(cs_main);
1095 
1096  if (block_index) {
1097  CBlock block;
1098  if (ReadBlockFromDisk(block, block_index, consensusParams)) {
1099  for (const auto& tx : block.vtx) {
1100  if (tx->GetHash() == hash) {
1101  hashBlock = block_index->GetBlockHash();
1102  return tx;
1103  }
1104  }
1105  }
1106  return nullptr;
1107  }
1108  if (mempool) {
1109  CTransactionRef ptx = mempool->get(hash);
1110  if (ptx) return ptx;
1111  }
1112  if (g_txindex) {
1113  CTransactionRef tx;
1114  if (g_txindex->FindTx(hash, hashBlock, tx)) return tx;
1115  }
1116  return nullptr;
1117 }
1118 
1120 //
1121 // CBlock and CBlockIndex
1122 //
1123 
1124 static bool WriteBlockToDisk(const CBlock& block, FlatFilePos& pos, const CMessageHeader::MessageStartChars& messageStart)
1125 {
1126  // Open history file to append
1128  if (fileout.IsNull())
1129  return error("WriteBlockToDisk: OpenBlockFile failed");
1130 
1131  // Write index header
1132  unsigned int nSize = GetSerializeSize(block, fileout.GetVersion());
1133  fileout << messageStart << nSize;
1134 
1135  // Write block
1136  long fileOutPos = ftell(fileout.Get());
1137  if (fileOutPos < 0)
1138  return error("WriteBlockToDisk: ftell failed");
1139  pos.nPos = (unsigned int)fileOutPos;
1140  fileout << block;
1141 
1142  return true;
1143 }
1144 
1145 bool ReadBlockFromDisk(CBlock& block, const FlatFilePos& pos, const Consensus::Params& consensusParams)
1146 {
1147  block.SetNull();
1148 
1149  // Open history file to read
1150  CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1151  if (filein.IsNull())
1152  return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1153 
1154  // Read block
1155  try {
1156  filein >> block;
1157  }
1158  catch (const std::exception& e) {
1159  return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1160  }
1161 
1162  // Check the header
1163  if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1164  return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1165 
1166  // Signet only: check block solution
1167  if (consensusParams.signet_blocks && !CheckSignetBlockSolution(block, consensusParams)) {
1168  return error("ReadBlockFromDisk: Errors in block solution at %s", pos.ToString());
1169  }
1170 
1171  return true;
1172 }
1173 
1174 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1175 {
1176  FlatFilePos blockPos;
1177  {
1178  LOCK(cs_main);
1179  blockPos = pindex->GetBlockPos();
1180  }
1181 
1182  if (!ReadBlockFromDisk(block, blockPos, consensusParams))
1183  return false;
1184  if (block.GetHash() != pindex->GetBlockHash())
1185  return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1186  pindex->ToString(), pindex->GetBlockPos().ToString());
1187  return true;
1188 }
1189 
1190 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatFilePos& pos, const CMessageHeader::MessageStartChars& message_start)
1191 {
1192  FlatFilePos hpos = pos;
1193  hpos.nPos -= 8; // Seek back 8 bytes for meta header
1194  CAutoFile filein(OpenBlockFile(hpos, true), SER_DISK, CLIENT_VERSION);
1195  if (filein.IsNull()) {
1196  return error("%s: OpenBlockFile failed for %s", __func__, pos.ToString());
1197  }
1198 
1199  try {
1201  unsigned int blk_size;
1202 
1203  filein >> blk_start >> blk_size;
1204 
1205  if (memcmp(blk_start, message_start, CMessageHeader::MESSAGE_START_SIZE)) {
1206  return error("%s: Block magic mismatch for %s: %s versus expected %s", __func__, pos.ToString(),
1207  HexStr(blk_start),
1208  HexStr(message_start));
1209  }
1210 
1211  if (blk_size > MAX_SIZE) {
1212  return error("%s: Block data is larger than maximum deserialization size for %s: %s versus %s", __func__, pos.ToString(),
1213  blk_size, MAX_SIZE);
1214  }
1215 
1216  block.resize(blk_size); // Zeroing of memory is intentional here
1217  filein.read((char*)block.data(), blk_size);
1218  } catch(const std::exception& e) {
1219  return error("%s: Read from block file failed: %s for %s", __func__, e.what(), pos.ToString());
1220  }
1221 
1222  return true;
1223 }
1224 
1225 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CBlockIndex* pindex, const CMessageHeader::MessageStartChars& message_start)
1226 {
1227  FlatFilePos block_pos;
1228  {
1229  LOCK(cs_main);
1230  block_pos = pindex->GetBlockPos();
1231  }
1232 
1233  return ReadRawBlockFromDisk(block, block_pos, message_start);
1234 }
1235 
1236 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1237 {
1238  int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1239  // Force block reward to zero when right shift is undefined.
1240  if (halvings >= 64)
1241  return 0;
1242 
1243  CAmount nSubsidy = 50 * COIN;
1244  // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1245  nSubsidy >>= halvings;
1246  return nSubsidy;
1247 }
1248 
1250  std::string ldb_name,
1251  size_t cache_size_bytes,
1252  bool in_memory,
1253  bool should_wipe) : m_dbview(
1254  GetDataDir() / ldb_name, cache_size_bytes, in_memory, should_wipe),
1255  m_catcherview(&m_dbview) {}
1256 
1257 void CoinsViews::InitCache()
1258 {
1259  m_cacheview = MakeUnique<CCoinsViewCache>(&m_catcherview);
1260 }
1261 
1262 CChainState::CChainState(CTxMemPool& mempool, BlockManager& blockman, uint256 from_snapshot_blockhash)
1263  : m_blockman(blockman),
1264  m_mempool(mempool),
1265  m_from_snapshot_blockhash(from_snapshot_blockhash) {}
1266 
1268  size_t cache_size_bytes,
1269  bool in_memory,
1270  bool should_wipe,
1271  std::string leveldb_name)
1272 {
1274  leveldb_name += "_" + m_from_snapshot_blockhash.ToString();
1275  }
1276 
1277  m_coins_views = MakeUnique<CoinsViews>(
1278  leveldb_name, cache_size_bytes, in_memory, should_wipe);
1279 }
1280 
1281 void CChainState::InitCoinsCache(size_t cache_size_bytes)
1282 {
1283  assert(m_coins_views != nullptr);
1284  m_coinstip_cache_size_bytes = cache_size_bytes;
1285  m_coins_views->InitCache();
1286 }
1287 
1288 // Note that though this is marked const, we may end up modifying `m_cached_finished_ibd`, which
1289 // is a performance-related implementation detail. This function must be marked
1290 // `const` so that `CValidationInterface` clients (which are given a `const CChainState*`)
1291 // can call it.
1292 //
1294 {
1295  // Optimization: pre-test latch before taking the lock.
1296  if (m_cached_finished_ibd.load(std::memory_order_relaxed))
1297  return false;
1298 
1299  LOCK(cs_main);
1300  if (m_cached_finished_ibd.load(std::memory_order_relaxed))
1301  return false;
1302  if (fImporting || fReindex)
1303  return true;
1304  if (m_chain.Tip() == nullptr)
1305  return true;
1307  return true;
1308  if (m_chain.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1309  return true;
1310  LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1311  m_cached_finished_ibd.store(true, std::memory_order_relaxed);
1312  return false;
1313 }
1314 
1315 static CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
1316 
1317 static void AlertNotify(const std::string& strMessage)
1318 {
1319  uiInterface.NotifyAlertChanged();
1320 #if HAVE_SYSTEM
1321  std::string strCmd = gArgs.GetArg("-alertnotify", "");
1322  if (strCmd.empty()) return;
1323 
1324  // Alert text should be plain ascii coming from a trusted source, but to
1325  // be safe we first strip anything not in safeChars, then add single quotes around
1326  // the whole string before passing it to the shell:
1327  std::string singleQuote("'");
1328  std::string safeStatus = SanitizeString(strMessage);
1329  safeStatus = singleQuote+safeStatus+singleQuote;
1330  boost::replace_all(strCmd, "%s", safeStatus);
1331 
1332  std::thread t(runCommand, strCmd);
1333  t.detach(); // thread runs free
1334 #endif
1335 }
1336 
1338 {
1339  AssertLockHeld(cs_main);
1340  // Before we get past initial download, we cannot reliably alert about forks
1341  // (we assume we don't get stuck on a fork before finishing our initial sync)
1342  if (::ChainstateActive().IsInitialBlockDownload())
1343  return;
1344 
1345  // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1346  // of our head, drop it
1347  if (pindexBestForkTip && ::ChainActive().Height() - pindexBestForkTip->nHeight >= 72)
1348  pindexBestForkTip = nullptr;
1349 
1350  if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > ::ChainActive().Tip()->nChainWork + (GetBlockProof(*::ChainActive().Tip()) * 6)))
1351  {
1353  {
1354  std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1355  pindexBestForkBase->phashBlock->ToString() + std::string("'");
1356  AlertNotify(warning);
1357  }
1358  if (pindexBestForkTip && pindexBestForkBase)
1359  {
1360  LogPrintf("%s: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n", __func__,
1362  pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1363  SetfLargeWorkForkFound(true);
1364  }
1365  else
1366  {
1367  LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1369  }
1370  }
1371  else
1372  {
1373  SetfLargeWorkForkFound(false);
1375  }
1376 }
1377 
1379 {
1380  AssertLockHeld(cs_main);
1381  // If we are on a fork that is sufficiently large, set a warning flag
1382  CBlockIndex* pfork = pindexNewForkTip;
1383  CBlockIndex* plonger = ::ChainActive().Tip();
1384  while (pfork && pfork != plonger)
1385  {
1386  while (plonger && plonger->nHeight > pfork->nHeight)
1387  plonger = plonger->pprev;
1388  if (pfork == plonger)
1389  break;
1390  pfork = pfork->pprev;
1391  }
1392 
1393  // We define a condition where we should warn the user about as a fork of at least 7 blocks
1394  // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1395  // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1396  // hash rate operating on the fork.
1397  // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1398  // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1399  // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1400  if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
1401  pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1402  ::ChainActive().Height() - pindexNewForkTip->nHeight < 72)
1403  {
1404  pindexBestForkTip = pindexNewForkTip;
1405  pindexBestForkBase = pfork;
1406  }
1407 
1409 }
1410 
1411 // Called both upon regular invalid block discovery *and* InvalidateBlock
1413 {
1414  if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1415  pindexBestInvalid = pindexNew;
1416  if (pindexBestHeader != nullptr && pindexBestHeader->GetAncestor(pindexNew->nHeight) == pindexNew) {
1417  pindexBestHeader = ::ChainActive().Tip();
1418  }
1419 
1420  LogPrintf("%s: invalid block=%s height=%d log2_work=%f date=%s\n", __func__,
1421  pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1422  log(pindexNew->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(pindexNew->GetBlockTime()));
1423  CBlockIndex *tip = ::ChainActive().Tip();
1424  assert (tip);
1425  LogPrintf("%s: current best=%s height=%d log2_work=%f date=%s\n", __func__,
1426  tip->GetBlockHash().ToString(), ::ChainActive().Height(), log(tip->nChainWork.getdouble())/log(2.0),
1429 }
1430 
1431 // Same as InvalidChainFound, above, except not called directly from InvalidateBlock,
1432 // which does its own setBlockIndexCandidates manageent.
1435  pindex->nStatus |= BLOCK_FAILED_VALID;
1436  m_blockman.m_failed_blocks.insert(pindex);
1437  setDirtyBlockIndex.insert(pindex);
1438  setBlockIndexCandidates.erase(pindex);
1439  InvalidChainFound(pindex);
1440  }
1441 }
1442 
1443 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1444 {
1445  // mark inputs spent
1446  if (!tx.IsCoinBase()) {
1447  txundo.vprevout.reserve(tx.vin.size());
1448  for (const CTxIn &txin : tx.vin) {
1449  txundo.vprevout.emplace_back();
1450  bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1451  assert(is_spent);
1452  }
1453  }
1454  // add outputs
1455  AddCoins(inputs, tx, nHeight);
1456 }
1457 
1458 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1459 {
1460  CTxUndo txundo;
1461  UpdateCoins(tx, inputs, txundo, nHeight);
1462 }
1463 
1465  const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1466  const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1468 }
1469 
1471 {
1472  LOCK(cs_main);
1473  CBlockIndex* pindexPrev = LookupBlockIndex(inputs.GetBestBlock());
1474  return pindexPrev->nHeight + 1;
1475 }
1476 
1477 
1480 
1482  // Setup the salted hasher
1483  uint256 nonce = GetRandHash();
1484  // We want the nonce to be 64 bytes long to force the hasher to process
1485  // this chunk, which makes later hash computations more efficient. We
1486  // just write our 32-byte entropy twice to fill the 64 bytes.
1487  g_scriptExecutionCacheHasher.Write(nonce.begin(), 32);
1488  g_scriptExecutionCacheHasher.Write(nonce.begin(), 32);
1489  // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1490  // setup_bytes creates the minimum possible cache (2 elements).
1491  size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
1492  size_t nElems = g_scriptExecutionCache.setup_bytes(nMaxCacheSize);
1493  LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1494  (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1495 }
1496 
1516 bool CheckInputScripts(const CTransaction& tx, TxValidationState &state, const CCoinsViewCache &inputs, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
1517 {
1518  if (tx.IsCoinBase()) return true;
1519 
1520  if (pvChecks) {
1521  pvChecks->reserve(tx.vin.size());
1522  }
1523 
1524  // First check if script executions have been cached with the same
1525  // flags. Note that this assumes that the inputs provided are
1526  // correct (ie that the transaction hash which is in tx's prevouts
1527  // properly commits to the scriptPubKey in the inputs view of that
1528  // transaction).
1529  uint256 hashCacheEntry;
1531  hasher.Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1532  AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1533  if (g_scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1534  return true;
1535  }
1536 
1537  if (!txdata.m_spent_outputs_ready) {
1538  std::vector<CTxOut> spent_outputs;
1539  spent_outputs.reserve(tx.vin.size());
1540 
1541  for (const auto& txin : tx.vin) {
1542  const COutPoint& prevout = txin.prevout;
1543  const Coin& coin = inputs.AccessCoin(prevout);
1544  assert(!coin.IsSpent());
1545  spent_outputs.emplace_back(coin.out);
1546  }
1547  txdata.Init(tx, std::move(spent_outputs));
1548  }
1549  assert(txdata.m_spent_outputs.size() == tx.vin.size());
1550 
1551  for (unsigned int i = 0; i < tx.vin.size(); i++) {
1552 
1553  // We very carefully only pass in things to CScriptCheck which
1554  // are clearly committed to by tx' witness hash. This provides
1555  // a sanity check that our caching is not introducing consensus
1556  // failures through additional data in, eg, the coins being
1557  // spent being checked as a part of CScriptCheck.
1558 
1559  // Verify signature
1560  CScriptCheck check(txdata.m_spent_outputs[i], tx, i, flags, cacheSigStore, &txdata);
1561  if (pvChecks) {
1562  pvChecks->push_back(CScriptCheck());
1563  check.swap(pvChecks->back());
1564  } else if (!check()) {
1566  // Check whether the failure was caused by a
1567  // non-mandatory script verification check, such as
1568  // non-standard DER encodings or non-null dummy
1569  // arguments; if so, ensure we return NOT_STANDARD
1570  // instead of CONSENSUS to avoid downstream users
1571  // splitting the network between upgraded and
1572  // non-upgraded nodes by banning CONSENSUS-failing
1573  // data providers.
1574  CScriptCheck check2(txdata.m_spent_outputs[i], tx, i,
1575  flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1576  if (check2())
1577  return state.Invalid(TxValidationResult::TX_NOT_STANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1578  }
1579  // MANDATORY flag failures correspond to
1580  // TxValidationResult::TX_CONSENSUS. Because CONSENSUS
1581  // failures are the most serious case of validation
1582  // failures, we may need to consider using
1583  // RECENT_CONSENSUS_CHANGE for any script failure that
1584  // could be due to non-upgraded nodes which we may want to
1585  // support, to avoid splitting the network (but this
1586  // depends on the details of how net_processing handles
1587  // such errors).
1588  return state.Invalid(TxValidationResult::TX_CONSENSUS, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1589  }
1590  }
1591 
1592  if (cacheFullScriptStore && !pvChecks) {
1593  // We executed all of the provided scripts, and were told to
1594  // cache the result. Do so now.
1595  g_scriptExecutionCache.insert(hashCacheEntry);
1596  }
1597 
1598  return true;
1599 }
1600 
1601 static bool UndoWriteToDisk(const CBlockUndo& blockundo, FlatFilePos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1602 {
1603  // Open history file to append
1605  if (fileout.IsNull())
1606  return error("%s: OpenUndoFile failed", __func__);
1607 
1608  // Write index header
1609  unsigned int nSize = GetSerializeSize(blockundo, fileout.GetVersion());
1610  fileout << messageStart << nSize;
1611 
1612  // Write undo data
1613  long fileOutPos = ftell(fileout.Get());
1614  if (fileOutPos < 0)
1615  return error("%s: ftell failed", __func__);
1616  pos.nPos = (unsigned int)fileOutPos;
1617  fileout << blockundo;
1618 
1619  // calculate & write checksum
1621  hasher << hashBlock;
1622  hasher << blockundo;
1623  fileout << hasher.GetHash();
1624 
1625  return true;
1626 }
1627 
1628 bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex* pindex)
1629 {
1630  FlatFilePos pos = pindex->GetUndoPos();
1631  if (pos.IsNull()) {
1632  return error("%s: no undo data available", __func__);
1633  }
1634 
1635  // Open history file to read
1636  CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1637  if (filein.IsNull())
1638  return error("%s: OpenUndoFile failed", __func__);
1639 
1640  // Read block
1641  uint256 hashChecksum;
1642  CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1643  try {
1644  verifier << pindex->pprev->GetBlockHash();
1645  verifier >> blockundo;
1646  filein >> hashChecksum;
1647  }
1648  catch (const std::exception& e) {
1649  return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1650  }
1651 
1652  // Verify checksum
1653  if (hashChecksum != verifier.GetHash())
1654  return error("%s: Checksum mismatch", __func__);
1655 
1656  return true;
1657 }
1658 
1660 static bool AbortNode(const std::string& strMessage, bilingual_str user_message = bilingual_str())
1661 {
1662  SetMiscWarning(Untranslated(strMessage));
1663  LogPrintf("*** %s\n", strMessage);
1664  if (user_message.empty()) {
1665  user_message = _("A fatal internal error occurred, see debug.log for details");
1666  }
1667  AbortError(user_message);
1668  StartShutdown();
1669  return false;
1670 }
1671 
1672 static bool AbortNode(BlockValidationState& state, const std::string& strMessage, const bilingual_str& userMessage = bilingual_str())
1673 {
1674  AbortNode(strMessage, userMessage);
1675  return state.Error(strMessage);
1676 }
1677 
1685 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1686 {
1687  bool fClean = true;
1688 
1689  if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1690 
1691  if (undo.nHeight == 0) {
1692  // Missing undo metadata (height and coinbase). Older versions included this
1693  // information only in undo records for the last spend of a transactions'
1694  // outputs. This implies that it must be present for some other output of the same tx.
1695  const Coin& alternate = AccessByTxid(view, out.hash);
1696  if (!alternate.IsSpent()) {
1697  undo.nHeight = alternate.nHeight;
1698  undo.fCoinBase = alternate.fCoinBase;
1699  } else {
1700  return DISCONNECT_FAILED; // adding output for transaction without known metadata
1701  }
1702  }
1703  // If the coin already exists as an unspent coin in the cache, then the
1704  // possible_overwrite parameter to AddCoin must be set to true. We have
1705  // already checked whether an unspent coin exists above using HaveCoin, so
1706  // we don't need to guess. When fClean is false, an unspent coin already
1707  // existed and it is an overwrite.
1708  view.AddCoin(out, std::move(undo), !fClean);
1709 
1710  return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1711 }
1712 
1716 {
1717  bool fClean = true;
1718 
1719  CBlockUndo blockUndo;
1720  if (!UndoReadFromDisk(blockUndo, pindex)) {
1721  error("DisconnectBlock(): failure reading undo data");
1722  return DISCONNECT_FAILED;
1723  }
1724 
1725  if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1726  error("DisconnectBlock(): block and undo data inconsistent");
1727  return DISCONNECT_FAILED;
1728  }
1729 
1730  // undo transactions in reverse order
1731  for (int i = block.vtx.size() - 1; i >= 0; i--) {
1732  const CTransaction &tx = *(block.vtx[i]);
1733  uint256 hash = tx.GetHash();
1734  bool is_coinbase = tx.IsCoinBase();
1735 
1736  // Check that all outputs are available and match the outputs in the block itself
1737  // exactly.
1738  for (size_t o = 0; o < tx.vout.size(); o++) {
1739  if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1740  COutPoint out(hash, o);
1741  Coin coin;
1742  bool is_spent = view.SpendCoin(out, &coin);
1743  if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1744  fClean = false; // transaction output mismatch
1745  }
1746  }
1747  }
1748 
1749  // restore inputs
1750  if (i > 0) { // not coinbases
1751  CTxUndo &txundo = blockUndo.vtxundo[i-1];
1752  if (txundo.vprevout.size() != tx.vin.size()) {
1753  error("DisconnectBlock(): transaction and undo data inconsistent");
1754  return DISCONNECT_FAILED;
1755  }
1756  for (unsigned int j = tx.vin.size(); j-- > 0;) {
1757  const COutPoint &out = tx.vin[j].prevout;
1758  int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1759  if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1760  fClean = fClean && res != DISCONNECT_UNCLEAN;
1761  }
1762  // At this point, all of txundo.vprevout should have been moved out.
1763  }
1764  }
1765 
1766  // move best block pointer to prevout block
1767  view.SetBestBlock(pindex->pprev->GetBlockHash());
1768 
1769  return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1770 }
1771 
1772 static void FlushUndoFile(int block_file, bool finalize = false)
1773 {
1774  FlatFilePos undo_pos_old(block_file, vinfoBlockFile[block_file].nUndoSize);
1775  if (!UndoFileSeq().Flush(undo_pos_old, finalize)) {
1776  AbortNode("Flushing undo file to disk failed. This is likely the result of an I/O error.");
1777  }
1778 }
1779 
1780 static void FlushBlockFile(bool fFinalize = false, bool finalize_undo = false)
1781 {
1782  LOCK(cs_LastBlockFile);
1783  FlatFilePos block_pos_old(nLastBlockFile, vinfoBlockFile[nLastBlockFile].nSize);
1784  if (!BlockFileSeq().Flush(block_pos_old, fFinalize)) {
1785  AbortNode("Flushing block file to disk failed. This is likely the result of an I/O error.");
1786  }
1787  // we do not always flush the undo file, as the chain tip may be lagging behind the incoming blocks,
1788  // e.g. during IBD or a sync after a node going offline
1789  if (!fFinalize || finalize_undo) FlushUndoFile(nLastBlockFile, finalize_undo);
1790 }
1791 
1792 static bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize);
1793 
1794 static bool WriteUndoDataForBlock(const CBlockUndo& blockundo, BlockValidationState& state, CBlockIndex* pindex, const CChainParams& chainparams)
1795 {
1796  // Write undo information to disk
1797  if (pindex->GetUndoPos().IsNull()) {
1798  FlatFilePos _pos;
1799  if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, CLIENT_VERSION) + 40))
1800  return error("ConnectBlock(): FindUndoPos failed");
1801  if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1802  return AbortNode(state, "Failed to write undo data");
1803  // rev files are written in block height order, whereas blk files are written as blocks come in (often out of order)
1804  // we want to flush the rev (undo) file once we've written the last block, which is indicated by the last height
1805  // in the block file info as below; note that this does not catch the case where the undo writes are keeping up
1806  // with the block writes (usually when a synced up node is getting newly mined blocks) -- this case is caught in
1807  // the FindBlockPos function
1808  if (_pos.nFile < nLastBlockFile && static_cast<uint32_t>(pindex->nHeight) == vinfoBlockFile[_pos.nFile].nHeightLast) {
1809  FlushUndoFile(_pos.nFile, true);
1810  }
1811 
1812  // update nUndoPos in block index
1813  pindex->nUndoPos = _pos.nPos;
1814  pindex->nStatus |= BLOCK_HAVE_UNDO;
1815  setDirtyBlockIndex.insert(pindex);
1816  }
1817 
1818  return true;
1819 }
1820 
1822 
1823 void ThreadScriptCheck(int worker_num) {
1824  util::ThreadRename(strprintf("scriptch.%i", worker_num));
1825  scriptcheckqueue.Thread();
1826 }
1827 
1829 
1830 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1831 {
1832  LOCK(cs_main);
1833  int32_t nVersion = VERSIONBITS_TOP_BITS;
1834 
1835  for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1836  ThresholdState state = VersionBitsState(pindexPrev, params, static_cast<Consensus::DeploymentPos>(i), versionbitscache);
1837  if (state == ThresholdState::LOCKED_IN || state == ThresholdState::STARTED) {
1838  nVersion |= VersionBitsMask(params, static_cast<Consensus::DeploymentPos>(i));
1839  }
1840  }
1841 
1842  return nVersion;
1843 }
1844 
1849 {
1850 private:
1851  int bit;
1852 
1853 public:
1854  explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1855 
1856  int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1857  int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1858  int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1859  int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1860 
1861  bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1862  {
1863  return pindex->nHeight >= params.MinBIP9WarningHeight &&
1865  ((pindex->nVersion >> bit) & 1) != 0 &&
1866  ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1867  }
1868 };
1869 
1870 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS] GUARDED_BY(cs_main);
1871 
1872 // 0.13.0 was shipped with a segwit deployment defined for testnet, but not for
1873 // mainnet. We no longer need to support disabling the segwit deployment
1874 // except for testing purposes, due to limitations of the functional test
1875 // environment. See test/functional/p2p-segwit.py.
1876 static bool IsScriptWitnessEnabled(const Consensus::Params& params)
1877 {
1878  return params.SegwitHeight != std::numeric_limits<int>::max();
1879 }
1880 
1881 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
1882  AssertLockHeld(cs_main);
1883 
1884  unsigned int flags = SCRIPT_VERIFY_NONE;
1885 
1886  // BIP16 didn't become active until Apr 1 2012 (on mainnet, and
1887  // retroactively applied to testnet)
1888  // However, only one historical block violated the P2SH rules (on both
1889  // mainnet and testnet), so for simplicity, always leave P2SH
1890  // on except for the one violating block.
1891  if (consensusparams.BIP16Exception.IsNull() || // no bip16 exception on this chain
1892  pindex->phashBlock == nullptr || // this is a new candidate block, eg from TestBlockValidity()
1893  *pindex->phashBlock != consensusparams.BIP16Exception) // this block isn't the historical exception
1894  {
1895  flags |= SCRIPT_VERIFY_P2SH;
1896  }
1897 
1898  // Enforce WITNESS rules whenever P2SH is in effect (and the segwit
1899  // deployment is defined).
1900  if (flags & SCRIPT_VERIFY_P2SH && IsScriptWitnessEnabled(consensusparams)) {
1901  flags |= SCRIPT_VERIFY_WITNESS;
1902  }
1903 
1904  // Start enforcing the DERSIG (BIP66) rule
1905  if (pindex->nHeight >= consensusparams.BIP66Height) {
1906  flags |= SCRIPT_VERIFY_DERSIG;
1907  }
1908 
1909  // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1910  if (pindex->nHeight >= consensusparams.BIP65Height) {
1912  }
1913 
1914  // Start enforcing BIP112 (CHECKSEQUENCEVERIFY)
1915  if (pindex->nHeight >= consensusparams.CSVHeight) {
1917  }
1918 
1919  // Start enforcing Taproot using versionbits logic.
1921  flags |= SCRIPT_VERIFY_TAPROOT;
1922  }
1923 
1924  // Start enforcing BIP147 NULLDUMMY (activated simultaneously with segwit)
1925  if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
1926  flags |= SCRIPT_VERIFY_NULLDUMMY;
1927  }
1928 
1929  return flags;
1930 }
1931 
1932 
1933 
1934 static int64_t nTimeCheck = 0;
1935 static int64_t nTimeForks = 0;
1936 static int64_t nTimeVerify = 0;
1937 static int64_t nTimeConnect = 0;
1938 static int64_t nTimeIndex = 0;
1939 static int64_t nTimeCallbacks = 0;
1940 static int64_t nTimeTotal = 0;
1941 static int64_t nBlocksTotal = 0;
1942 
1947  CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck)
1948 {
1949  AssertLockHeld(cs_main);
1950  assert(pindex);
1951  assert(*pindex->phashBlock == block.GetHash());
1952  int64_t nTimeStart = GetTimeMicros();
1953 
1954  // Check it again in case a previous version let a bad block in
1955  // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
1956  // ContextualCheckBlockHeader() here. This means that if we add a new
1957  // consensus rule that is enforced in one of those two functions, then we
1958  // may have let in a block that violates the rule prior to updating the
1959  // software, and we would NOT be enforcing the rule here. Fully solving
1960  // upgrade from one software version to the next after a consensus rule
1961  // change is potentially tricky and issue-specific (see RewindBlockIndex()
1962  // for one general approach that was used for BIP 141 deployment).
1963  // Also, currently the rule against blocks more than 2 hours in the future
1964  // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
1965  // re-enforce that rule here (at least until we make it impossible for
1966  // GetAdjustedTime() to go backward).
1967  if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck)) {
1969  // We don't write down blocks to disk if they may have been
1970  // corrupted, so this should be impossible unless we're having hardware
1971  // problems.
1972  return AbortNode(state, "Corrupt block found indicating potential hardware failure; shutting down");
1973  }
1974  return error("%s: Consensus::CheckBlock: %s", __func__, state.ToString());
1975  }
1976 
1977  // verify that the view's current state corresponds to the previous block
1978  uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
1979  assert(hashPrevBlock == view.GetBestBlock());
1980 
1981  nBlocksTotal++;
1982 
1983  // Special case for the genesis block, skipping connection of its transactions
1984  // (its coinbase is unspendable)
1985  if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1986  if (!fJustCheck)
1987  view.SetBestBlock(pindex->GetBlockHash());
1988  return true;
1989  }
1990 
1991  bool fScriptChecks = true;
1992  if (!hashAssumeValid.IsNull()) {
1993  // We've been configured with the hash of a block which has been externally verified to have a valid history.
1994  // A suitable default value is included with the software and updated from time to time. Because validity
1995  // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1996  // This setting doesn't force the selection of any particular chain but makes validating some faster by
1997  // effectively caching the result of part of the verification.
1998  BlockMap::const_iterator it = m_blockman.m_block_index.find(hashAssumeValid);
1999  if (it != m_blockman.m_block_index.end()) {
2000  if (it->second->GetAncestor(pindex->nHeight) == pindex &&
2001  pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
2002  pindexBestHeader->nChainWork >= nMinimumChainWork) {
2003  // This block is a member of the assumed verified chain and an ancestor of the best header.
2004  // Script verification is skipped when connecting blocks under the
2005  // assumevalid block. Assuming the assumevalid block is valid this
2006  // is safe because block merkle hashes are still computed and checked,
2007  // Of course, if an assumed valid block is invalid due to false scriptSigs
2008  // this optimization would allow an invalid chain to be accepted.
2009  // The equivalent time check discourages hash power from extorting the network via DOS attack
2010  // into accepting an invalid block through telling users they must manually set assumevalid.
2011  // Requiring a software change or burying the invalid block, regardless of the setting, makes
2012  // it hard to hide the implication of the demand. This also avoids having release candidates
2013  // that are hardly doing any signature verification at all in testing without having to
2014  // artificially set the default assumed verified block further back.
2015  // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
2016  // least as good as the expected chain.
2017  fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
2018  }
2019  }
2020  }
2021 
2022  int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
2023  LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
2024 
2025  // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2026  // unless those are already completely spent.
2027  // If such overwrites are allowed, coinbases and transactions depending upon those
2028  // can be duplicated to remove the ability to spend the first instance -- even after
2029  // being sent to another address.
2030  // See BIP30, CVE-2012-1909, and http://r6.ca/blog/20120206T005236Z.html for more information.
2031  // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
2032  // already refuses previously-known transaction ids entirely.
2033  // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
2034  // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
2035  // two in the chain that violate it. This prevents exploiting the issue against nodes during their
2036  // initial block download.
2037  bool fEnforceBIP30 = !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
2038  (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
2039 
2040  // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
2041  // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
2042  // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
2043  // before the first had been spent. Since those coinbases are sufficiently buried it's no longer possible to create further
2044  // duplicate transactions descending from the known pairs either.
2045  // 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.
2046 
2047  // BIP34 requires that a block at height X (block X) has its coinbase
2048  // scriptSig start with a CScriptNum of X (indicated height X). The above
2049  // logic of no longer requiring BIP30 once BIP34 activates is flawed in the
2050  // case that there is a block X before the BIP34 height of 227,931 which has
2051  // an indicated height Y where Y is greater than X. The coinbase for block
2052  // X would also be a valid coinbase for block Y, which could be a BIP30
2053  // violation. An exhaustive search of all mainnet coinbases before the
2054  // BIP34 height which have an indicated height greater than the block height
2055  // reveals many occurrences. The 3 lowest indicated heights found are
2056  // 209,921, 490,897, and 1,983,702 and thus coinbases for blocks at these 3
2057  // heights would be the first opportunity for BIP30 to be violated.
2058 
2059  // The search reveals a great many blocks which have an indicated height
2060  // greater than 1,983,702, so we simply remove the optimization to skip
2061  // BIP30 checking for blocks at height 1,983,702 or higher. Before we reach
2062  // that block in another 25 years or so, we should take advantage of a
2063  // future consensus change to do a new and improved version of BIP34 that
2064  // will actually prevent ever creating any duplicate coinbases in the
2065  // future.
2066  static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
2067 
2068  // There is no potential to create a duplicate coinbase at block 209,921
2069  // because this is still before the BIP34 height and so explicit BIP30
2070  // checking is still active.
2071 
2072  // The final case is block 176,684 which has an indicated height of
2073  // 490,897. Unfortunately, this issue was not discovered until about 2 weeks
2074  // before block 490,897 so there was not much opportunity to address this
2075  // case other than to carefully analyze it and determine it would not be a
2076  // problem. Block 490,897 was, in fact, mined with a different coinbase than
2077  // block 176,684, but it is important to note that even if it hadn't been or
2078  // is remined on an alternate fork with a duplicate coinbase, we would still
2079  // not run into a BIP30 violation. This is because the coinbase for 176,684
2080  // is spent in block 185,956 in transaction
2081  // d4f7fbbf92f4a3014a230b2dc70b8058d02eb36ac06b4a0736d9d60eaa9e8781. This
2082  // spending transaction can't be duplicated because it also spends coinbase
2083  // 0328dd85c331237f18e781d692c92de57649529bd5edf1d01036daea32ffde29. This
2084  // coinbase has an indicated height of over 4.2 billion, and wouldn't be
2085  // duplicatable until that height, and it's currently impossible to create a
2086  // chain that long. Nevertheless we may wish to consider a future soft fork
2087  // which retroactively prevents block 490,897 from creating a duplicate
2088  // coinbase. The two historical BIP30 violations often provide a confusing
2089  // edge case when manipulating the UTXO and it would be simpler not to have
2090  // another edge case to deal with.
2091 
2092  // testnet3 has no blocks before the BIP34 height with indicated heights
2093  // post BIP34 before approximately height 486,000,000 and presumably will
2094  // be reset before it reaches block 1,983,702 and starts doing unnecessary
2095  // BIP30 checking again.
2096  assert(pindex->pprev);
2097  CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
2098  //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
2099  fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
2100 
2101  // TODO: Remove BIP30 checking from block height 1,983,702 on, once we have a
2102  // consensus change that ensures coinbases at those heights can not
2103  // duplicate earlier coinbases.
2104  if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
2105  for (const auto& tx : block.vtx) {
2106  for (size_t o = 0; o < tx->vout.size(); o++) {
2107  if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
2108  LogPrintf("ERROR: ConnectBlock(): tried to overwrite transaction\n");
2109  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-BIP30");
2110  }
2111  }
2112  }
2113  }
2114 
2115  // Start enforcing BIP68 (sequence locks)
2116  int nLockTimeFlags = 0;
2117  if (pindex->nHeight >= chainparams.GetConsensus().CSVHeight) {
2118  nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
2119  }
2120 
2121  // Get the script flags for this block
2122  unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
2123 
2124  int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
2125  LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
2126 
2127  CBlockUndo blockundo;
2128 
2129  // Precomputed transaction data pointers must not be invalidated
2130  // until after `control` has run the script checks (potentially
2131  // in multiple threads). Preallocate the vector size so a new allocation
2132  // doesn't invalidate pointers into the vector, and keep txsdata in scope
2133  // for as long as `control`.
2134  CCheckQueueControl<CScriptCheck> control(fScriptChecks && g_parallel_script_checks ? &scriptcheckqueue : nullptr);
2135  std::vector<PrecomputedTransactionData> txsdata(block.vtx.size());
2136 
2137  std::vector<int> prevheights;
2138  CAmount nFees = 0;
2139  int nInputs = 0;
2140  int64_t nSigOpsCost = 0;
2141  blockundo.vtxundo.reserve(block.vtx.size() - 1);
2142  for (unsigned int i = 0; i < block.vtx.size(); i++)
2143  {
2144  const CTransaction &tx = *(block.vtx[i]);
2145 
2146  nInputs += tx.vin.size();
2147 
2148  if (!tx.IsCoinBase())
2149  {
2150  CAmount txfee = 0;
2151  TxValidationState tx_state;
2152  if (!Consensus::CheckTxInputs(tx, tx_state, view, pindex->nHeight, txfee)) {
2153  // Any transaction validation failure in ConnectBlock is a block consensus failure
2155  tx_state.GetRejectReason(), tx_state.GetDebugMessage());
2156  return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), state.ToString());
2157  }
2158  nFees += txfee;
2159  if (!MoneyRange(nFees)) {
2160  LogPrintf("ERROR: %s: accumulated fee in the block out of range.\n", __func__);
2161  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-accumulated-fee-outofrange");
2162  }
2163 
2164  // Check that transaction is BIP68 final
2165  // BIP68 lock checks (as opposed to nLockTime checks) must
2166  // be in ConnectBlock because they require the UTXO set
2167  prevheights.resize(tx.vin.size());
2168  for (size_t j = 0; j < tx.vin.size(); j++) {
2169  prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
2170  }
2171 
2172  if (!SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
2173  LogPrintf("ERROR: %s: contains a non-BIP68-final transaction\n", __func__);
2174  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal");
2175  }
2176  }
2177 
2178  // GetTransactionSigOpCost counts 3 types of sigops:
2179  // * legacy (always)
2180  // * p2sh (when P2SH enabled in flags and excludes coinbase)
2181  // * witness (when witness enabled in flags and excludes coinbase)
2182  nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
2183  if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST) {
2184  LogPrintf("ERROR: ConnectBlock(): too many sigops\n");
2185  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops");
2186  }
2187 
2188  if (!tx.IsCoinBase())
2189  {
2190  std::vector<CScriptCheck> vChecks;
2191  bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
2192  TxValidationState tx_state;
2193  if (fScriptChecks && !CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], g_parallel_script_checks ? &vChecks : nullptr)) {
2194  // Any transaction validation failure in ConnectBlock is a block consensus failure
2196  tx_state.GetRejectReason(), tx_state.GetDebugMessage());
2197  return error("ConnectBlock(): CheckInputScripts on %s failed with %s",
2198  tx.GetHash().ToString(), state.ToString());
2199  }
2200  control.Add(vChecks);
2201  }
2202 
2203  CTxUndo undoDummy;
2204  if (i > 0) {
2205  blockundo.vtxundo.push_back(CTxUndo());
2206  }
2207  UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2208  }
2209  int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
2210  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);
2211 
2212  CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2213  if (block.vtx[0]->GetValueOut() > blockReward) {
2214  LogPrintf("ERROR: ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)\n", block.vtx[0]->GetValueOut(), blockReward);
2215  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-amount");
2216  }
2217 
2218  if (!control.Wait()) {
2219  LogPrintf("ERROR: %s: CheckQueue failed\n", __func__);
2220  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "block-validation-failed");
2221  }
2222  int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
2223  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);
2224 
2225  if (fJustCheck)
2226  return true;
2227 
2228  if (!WriteUndoDataForBlock(blockundo, state, pindex, chainparams))
2229  return false;
2230 
2231  if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
2233  setDirtyBlockIndex.insert(pindex);
2234  }
2235 
2236  assert(pindex->phashBlock);
2237  // add this block to the view's block chain
2238  view.SetBestBlock(pindex->GetBlockHash());
2239 
2240  int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
2241  LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
2242 
2243  int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
2244  LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
2245 
2246  return true;
2247 }
2248 
2249 CoinsCacheSizeState CChainState::GetCoinsCacheSizeState(const CTxMemPool* tx_pool)
2250 {
2251  return this->GetCoinsCacheSizeState(
2252  tx_pool,
2254  gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
2255 }
2256 
2257 CoinsCacheSizeState CChainState::GetCoinsCacheSizeState(
2258  const CTxMemPool* tx_pool,
2259  size_t max_coins_cache_size_bytes,
2260  size_t max_mempool_size_bytes)
2261 {
2262  const int64_t nMempoolUsage = tx_pool ? tx_pool->DynamicMemoryUsage() : 0;
2263  int64_t cacheSize = CoinsTip().DynamicMemoryUsage();
2264  int64_t nTotalSpace =
2265  max_coins_cache_size_bytes + std::max<int64_t>(max_mempool_size_bytes - nMempoolUsage, 0);
2266 
2268  static constexpr int64_t MAX_BLOCK_COINSDB_USAGE_BYTES = 10 * 1024 * 1024; // 10MB
2269  int64_t large_threshold =
2270  std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE_BYTES);
2271 
2272  if (cacheSize > nTotalSpace) {
2273  LogPrintf("Cache size (%s) exceeds total space (%s)\n", cacheSize, nTotalSpace);
2275  } else if (cacheSize > large_threshold) {
2277  }
2278  return CoinsCacheSizeState::OK;
2279 }
2280 
2281 bool CChainState::FlushStateToDisk(
2282  const CChainParams& chainparams,
2283  BlockValidationState &state,
2284  FlushStateMode mode,
2285  int nManualPruneHeight)
2286 {
2287  LOCK(cs_main);
2288  assert(this->CanFlushToDisk());
2289  static std::chrono::microseconds nLastWrite{0};
2290  static std::chrono::microseconds nLastFlush{0};
2291  std::set<int> setFilesToPrune;
2292  bool full_flush_completed = false;
2293 
2294  const size_t coins_count = CoinsTip().GetCacheSize();
2295  const size_t coins_mem_usage = CoinsTip().DynamicMemoryUsage();
2296 
2297  try {
2298  {
2299  bool fFlushForPrune = false;
2300  bool fDoFullFlush = false;
2301  CoinsCacheSizeState cache_state = GetCoinsCacheSizeState(&m_mempool);
2302  LOCK(cs_LastBlockFile);
2303  if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
2304  if (nManualPruneHeight > 0) {
2305  LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune (manual)", BCLog::BENCH);
2306 
2307  m_blockman.FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight, m_chain.Height());
2308  } else {
2309  LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune", BCLog::BENCH);
2310 
2311  m_blockman.FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight(), m_chain.Height(), IsInitialBlockDownload());
2312  fCheckForPruning = false;
2313  }
2314  if (!setFilesToPrune.empty()) {
2315  fFlushForPrune = true;
2316  if (!fHavePruned) {
2317  pblocktree->WriteFlag("prunedblockfiles", true);
2318  fHavePruned = true;
2319  }
2320  }
2321  }
2322  const auto nNow = GetTime<std::chrono::microseconds>();
2323  // Avoid writing/flushing immediately after startup.
2324  if (nLastWrite.count() == 0) {
2325  nLastWrite = nNow;
2326  }
2327  if (nLastFlush.count() == 0) {
2328  nLastFlush = nNow;
2329  }
2330  // 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).
2331  bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
2332  // The cache is over the limit, we have to write now.
2333  bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
2334  // 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.
2335  bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > nLastWrite + DATABASE_WRITE_INTERVAL;
2336  // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2337  bool fPeriodicFlush = mode == FlushStateMode::PERIODIC && nNow > nLastFlush + DATABASE_FLUSH_INTERVAL;
2338  // Combine all conditions that result in a full cache flush.
2339  fDoFullFlush = (mode == FlushStateMode::ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2340  // Write blocks and block index to disk.
2341  if (fDoFullFlush || fPeriodicWrite) {
2342  // Depend on nMinDiskSpace to ensure we can write block index
2343  if (!CheckDiskSpace(GetBlocksDir())) {
2344  return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
2345  }
2346  {
2347  LOG_TIME_MILLIS_WITH_CATEGORY("write block and undo data to disk", BCLog::BENCH);
2348 
2349  // First make sure all block and undo data is flushed to disk.
2350  FlushBlockFile();
2351  }
2352 
2353  // Then update all block file information (which may refer to block and undo files).
2354  {
2355  LOG_TIME_MILLIS_WITH_CATEGORY("write block index to disk", BCLog::BENCH);
2356 
2357  std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2358  vFiles.reserve(setDirtyFileInfo.size());
2359  for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2360  vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
2361  setDirtyFileInfo.erase(it++);
2362  }
2363  std::vector<const CBlockIndex*> vBlocks;
2364  vBlocks.reserve(setDirtyBlockIndex.size());
2365  for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2366  vBlocks.push_back(*it);
2367  setDirtyBlockIndex.erase(it++);
2368  }
2369  if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2370  return AbortNode(state, "Failed to write to block index database");
2371  }
2372  }
2373  // Finally remove any pruned files
2374  if (fFlushForPrune) {
2375  LOG_TIME_MILLIS_WITH_CATEGORY("unlink pruned files", BCLog::BENCH);
2376 
2377  UnlinkPrunedFiles(setFilesToPrune);
2378  }
2379  nLastWrite = nNow;
2380  }
2381  // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2382  if (fDoFullFlush && !CoinsTip().GetBestBlock().IsNull()) {
2383  LOG_TIME_SECONDS(strprintf("write coins cache to disk (%d coins, %.2fkB)",
2384  coins_count, coins_mem_usage / 1000));
2385 
2386  // Typical Coin structures on disk are around 48 bytes in size.
2387  // Pushing a new one to the database can cause it to be written
2388  // twice (once in the log, and once in the tables). This is already
2389  // an overestimation, as most will delete an existing entry or
2390  // overwrite one. Still, use a conservative safety factor of 2.
2391  if (!CheckDiskSpace(GetDataDir(), 48 * 2 * 2 * CoinsTip().GetCacheSize())) {
2392  return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
2393  }
2394  // Flush the chainstate (which may refer to block index entries).
2395  if (!CoinsTip().Flush())
2396  return AbortNode(state, "Failed to write to coin database");
2397  nLastFlush = nNow;
2398  full_flush_completed = true;
2399  }
2400  }
2401  if (full_flush_completed) {
2402  // Update best block in wallet (so we can detect restored wallets).
2404  }
2405  } catch (const std::runtime_error& e) {
2406  return AbortNode(state, std::string("System error while flushing: ") + e.what());
2407  }
2408  return true;
2409 }
2410 
2412  BlockValidationState state;
2413  const CChainParams& chainparams = Params();
2414  if (!this->FlushStateToDisk(chainparams, state, FlushStateMode::ALWAYS)) {
2415  LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
2416  }
2417 }
2418 
2420  BlockValidationState state;
2421  fCheckForPruning = true;
2422  const CChainParams& chainparams = Params();
2423 
2424  if (!this->FlushStateToDisk(chainparams, state, FlushStateMode::NONE)) {
2425  LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
2426  }
2427 }
2428 
2429 static void DoWarning(const bilingual_str& warning)
2430 {
2431  static bool fWarned = false;
2432  SetMiscWarning(warning);
2433  if (!fWarned) {
2434  AlertNotify(warning.original);
2435  fWarned = true;
2436  }
2437 }
2438 
2440 static void AppendWarning(bilingual_str& res, const bilingual_str& warn)
2441 {
2442  if (!res.empty()) res += Untranslated(", ");
2443  res += warn;
2444 }
2445 
2447 static void UpdateTip(CTxMemPool& mempool, const CBlockIndex* pindexNew, const CChainParams& chainParams)
2448  EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
2449 {
2450  // New best block
2451  mempool.AddTransactionsUpdated(1);
2452 
2453  {
2454  LOCK(g_best_block_mutex);
2455  g_best_block = pindexNew->GetBlockHash();
2456  g_best_block_cv.notify_all();
2457  }
2458 
2459  bilingual_str warning_messages;
2460  int num_unexpected_version = 0;
2461  if (!::ChainstateActive().IsInitialBlockDownload())
2462  {
2463  const CBlockIndex* pindex = pindexNew;
2464  for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2465  WarningBitsConditionChecker checker(bit);
2466  ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2467  if (state == ThresholdState::ACTIVE || state == ThresholdState::LOCKED_IN) {
2468  const bilingual_str warning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2469  if (state == ThresholdState::ACTIVE) {
2470  DoWarning(warning);
2471  } else {
2472  AppendWarning(warning_messages, warning);
2473  }
2474  }
2475  }
2476  // Check the version of the last 100 blocks to see if we need to upgrade:
2477  for (int i = 0; i < 100 && pindex != nullptr; i++)
2478  {
2479  int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2480  if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2481  ++num_unexpected_version;
2482  pindex = pindex->pprev;
2483  }
2484  }
2485  LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)%s\n", __func__,
2486  pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, pindexNew->nVersion,
2487  log(pindexNew->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
2488  FormatISO8601DateTime(pindexNew->GetBlockTime()),
2489  GuessVerificationProgress(chainParams.TxData(), pindexNew), ::ChainstateActive().CoinsTip().DynamicMemoryUsage() * (1.0 / (1<<20)), ::ChainstateActive().CoinsTip().GetCacheSize(),
2490  !warning_messages.empty() ? strprintf(" warning='%s'", warning_messages.original) : "");
2491 
2492  if (num_unexpected_version > 0) {
2493  LogPrint(BCLog::VALIDATION, "%d of last 100 blocks have unexpected version\n", num_unexpected_version);
2494  }
2495 }
2496 
2508 {
2509  AssertLockHeld(cs_main);
2511 
2512  CBlockIndex *pindexDelete = m_chain.Tip();
2513  assert(pindexDelete);
2514  // Read block from disk.
2515  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2516  CBlock& block = *pblock;
2517  if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2518  return error("DisconnectTip(): Failed to read block");
2519  // Apply the block atomically to the chain state.
2520  int64_t nStart = GetTimeMicros();
2521  {
2522  CCoinsViewCache view(&CoinsTip());
2523  assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2524  if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2525  return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2526  bool flushed = view.Flush();
2527  assert(flushed);
2528  }
2529  LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
2530  // Write the chain state to disk, if necessary.
2531  if (!FlushStateToDisk(chainparams, state, FlushStateMode::IF_NEEDED))
2532  return false;
2533 
2534  if (disconnectpool) {
2535  // Save transactions to re-add to mempool at end of reorg
2536  for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2537  disconnectpool->addTransaction(*it);
2538  }
2539  while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2540  // Drop the earliest entry, and remove its children from the mempool.
2541  auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2543  disconnectpool->removeEntry(it);
2544  }
2545  }
2546 
2547  m_chain.SetTip(pindexDelete->pprev);
2548 
2549  UpdateTip(m_mempool, pindexDelete->pprev, chainparams);
2550  // Let wallets know transactions went from 1-confirmed to
2551  // 0-confirmed or conflicted:
2552  GetMainSignals().BlockDisconnected(pblock, pindexDelete);
2553  return true;
2554 }
2555 
2556 static int64_t nTimeReadFromDisk = 0;
2557 static int64_t nTimeConnectTotal = 0;
2558 static int64_t nTimeFlush = 0;
2559 static int64_t nTimeChainState = 0;
2560 static int64_t nTimePostConnect = 0;
2561 
2563  CBlockIndex* pindex = nullptr;
2564  std::shared_ptr<const CBlock> pblock;
2566 };
2575 private:
2576  std::vector<PerBlockConnectTrace> blocksConnected;
2577 
2578 public:
2579  explicit ConnectTrace() : blocksConnected(1) {}
2580 
2581  void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2582  assert(!blocksConnected.back().pindex);
2583  assert(pindex);
2584  assert(pblock);
2585  blocksConnected.back().pindex = pindex;
2586  blocksConnected.back().pblock = std::move(pblock);
2587  blocksConnected.emplace_back();
2588  }
2589 
2590  std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2591  // We always keep one extra block at the end of our list because
2592  // blocks are added after all the conflicted transactions have
2593  // been filled in. Thus, the last entry should always be an empty
2594  // one waiting for the transactions from the next block. We pop
2595  // the last entry here to make sure the list we return is sane.
2596  assert(!blocksConnected.back().pindex);
2597  blocksConnected.pop_back();
2598  return blocksConnected;
2599  }
2600 };
2601 
2608 bool CChainState::ConnectTip(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
2609 {
2610  AssertLockHeld(cs_main);
2612 
2613  assert(pindexNew->pprev == m_chain.Tip());
2614  // Read block from disk.
2615  int64_t nTime1 = GetTimeMicros();
2616  std::shared_ptr<const CBlock> pthisBlock;
2617  if (!pblock) {
2618  std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2619  if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2620  return AbortNode(state, "Failed to read block");
2621  pthisBlock = pblockNew;
2622  } else {
2623  pthisBlock = pblock;
2624  }
2625  const CBlock& blockConnecting = *pthisBlock;
2626  // Apply the block atomically to the chain state.
2627  int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2628  int64_t nTime3;
2629  LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
2630  {
2631  CCoinsViewCache view(&CoinsTip());
2632  bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2633  GetMainSignals().BlockChecked(blockConnecting, state);
2634  if (!rv) {
2635  if (state.IsInvalid())
2636  InvalidBlockFound(pindexNew, state);
2637  return error("%s: ConnectBlock %s failed, %s", __func__, pindexNew->GetBlockHash().ToString(), state.ToString());
2638  }
2639  nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2640  assert(nBlocksTotal > 0);
2641  LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
2642  bool flushed = view.Flush();
2643  assert(flushed);
2644  }
2645  int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2646  LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
2647  // Write the chain state to disk, if necessary.
2648  if (!FlushStateToDisk(chainparams, state, FlushStateMode::IF_NEEDED))
2649  return false;
2650  int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2651  LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
2652  // Remove conflicting transactions from the mempool.;
2653  m_mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2654  disconnectpool.removeForBlock(blockConnecting.vtx);
2655  // Update m_chain & related variables.
2656  m_chain.SetTip(pindexNew);
2657  UpdateTip(m_mempool, pindexNew, chainparams);
2658 
2659  int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2660  LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
2661  LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
2662 
2663  connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2664  return true;
2665 }
2666 
2672  do {
2673  CBlockIndex *pindexNew = nullptr;
2674 
2675  // Find the best candidate header.
2676  {
2677  std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2678  if (it == setBlockIndexCandidates.rend())
2679  return nullptr;
2680  pindexNew = *it;
2681  }
2682 
2683  // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2684  // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2685  CBlockIndex *pindexTest = pindexNew;
2686  bool fInvalidAncestor = false;
2687  while (pindexTest && !m_chain.Contains(pindexTest)) {
2688  assert(pindexTest->HaveTxsDownloaded() || pindexTest->nHeight == 0);
2689 
2690  // Pruned nodes may have entries in setBlockIndexCandidates for
2691  // which block files have been deleted. Remove those as candidates
2692  // for the most work chain if we come across them; we can't switch
2693  // to a chain unless we have all the non-active-chain parent blocks.
2694  bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2695  bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2696  if (fFailedChain || fMissingData) {
2697  // Candidate chain is not usable (either invalid or missing data)
2698  if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2699  pindexBestInvalid = pindexNew;
2700  CBlockIndex *pindexFailed = pindexNew;
2701  // Remove the entire chain from the set.
2702  while (pindexTest != pindexFailed) {
2703  if (fFailedChain) {
2704  pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2705  } else if (fMissingData) {
2706  // If we're missing data, then add back to m_blocks_unlinked,
2707  // so that if the block arrives in the future we can try adding
2708  // to setBlockIndexCandidates again.
2710  std::make_pair(pindexFailed->pprev, pindexFailed));
2711  }
2712  setBlockIndexCandidates.erase(pindexFailed);
2713  pindexFailed = pindexFailed->pprev;
2714  }
2715  setBlockIndexCandidates.erase(pindexTest);
2716  fInvalidAncestor = true;
2717  break;
2718  }
2719  pindexTest = pindexTest->pprev;
2720  }
2721  if (!fInvalidAncestor)
2722  return pindexNew;
2723  } while(true);
2724 }
2725 
2728  // Note that we can't delete the current block itself, as we may need to return to it later in case a
2729  // reorganization to a better block fails.
2730  std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2731  while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) {
2732  setBlockIndexCandidates.erase(it++);
2733  }
2734  // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2735  assert(!setBlockIndexCandidates.empty());
2736 }
2737 
2744 bool CChainState::ActivateBestChainStep(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2745 {
2746  AssertLockHeld(cs_main);
2748 
2749  const CBlockIndex *pindexOldTip = m_chain.Tip();
2750  const CBlockIndex *pindexFork = m_chain.FindFork(pindexMostWork);
2751 
2752  // Disconnect active blocks which are no longer in the best chain.
2753  bool fBlocksDisconnected = false;
2754  DisconnectedBlockTransactions disconnectpool;
2755  while (m_chain.Tip() && m_chain.Tip() != pindexFork) {
2756  if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2757  // This is likely a fatal error, but keep the mempool consistent,
2758  // just in case. Only remove from the mempool in this case.
2759  UpdateMempoolForReorg(m_mempool, disconnectpool, false);
2760 
2761  // If we're unable to disconnect a block during normal operation,
2762  // then that is a failure of our local system -- we should abort
2763  // rather than stay on a less work chain.
2764  AbortNode(state, "Failed to disconnect block; see debug.log for details");
2765  return false;
2766  }
2767  fBlocksDisconnected = true;
2768  }
2769 
2770  // Build list of new blocks to connect.
2771  std::vector<CBlockIndex*> vpindexToConnect;
2772  bool fContinue = true;
2773  int nHeight = pindexFork ? pindexFork->nHeight : -1;
2774  while (fContinue && nHeight != pindexMostWork->nHeight) {
2775  // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2776  // a few blocks along the way.
2777  int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2778  vpindexToConnect.clear();
2779  vpindexToConnect.reserve(nTargetHeight - nHeight);
2780  CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2781  while (pindexIter && pindexIter->nHeight != nHeight) {
2782  vpindexToConnect.push_back(pindexIter);
2783  pindexIter = pindexIter->pprev;
2784  }
2785  nHeight = nTargetHeight;
2786 
2787  // Connect new blocks.
2788  for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
2789  if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2790  if (state.IsInvalid()) {
2791  // The block violates a consensus rule.
2793  InvalidChainFound(vpindexToConnect.front());
2794  }
2795  state = BlockValidationState();
2796  fInvalidFound = true;
2797  fContinue = false;
2798  break;
2799  } else {
2800  // A system error occurred (disk space, database error, ...).
2801  // Make the mempool consistent with the current tip, just in case
2802  // any observers try to use it before shutdown.
2803  UpdateMempoolForReorg(m_mempool, disconnectpool, false);
2804  return false;
2805  }
2806  } else {
2808  if (!pindexOldTip || m_chain.Tip()->nChainWork > pindexOldTip->nChainWork) {
2809  // We're in a better position than we were. Return temporarily to release the lock.
2810  fContinue = false;
2811  break;
2812  }
2813  }
2814  }
2815  }
2816 
2817  if (fBlocksDisconnected) {
2818  // If any blocks were disconnected, disconnectpool may be non empty. Add
2819  // any disconnected transactions back to the mempool.
2820  UpdateMempoolForReorg(m_mempool, disconnectpool, true);
2821  }
2822  m_mempool.check(&CoinsTip());
2823 
2824  // Callbacks/notifications for a new best chain.
2825  if (fInvalidFound)
2826  CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2827  else
2829 
2830  return true;
2831 }
2832 
2834 {
2835  if (!init) return SynchronizationState::POST_INIT;
2838 }
2839 
2840 static bool NotifyHeaderTip() LOCKS_EXCLUDED(cs_main) {
2841  bool fNotify = false;
2842  bool fInitialBlockDownload = false;
2843  static CBlockIndex* pindexHeaderOld = nullptr;
2844  CBlockIndex* pindexHeader = nullptr;
2845  {
2846  LOCK(cs_main);
2847  pindexHeader = pindexBestHeader;
2848 
2849  if (pindexHeader != pindexHeaderOld) {
2850  fNotify = true;
2851  fInitialBlockDownload = ::ChainstateActive().IsInitialBlockDownload();
2852  pindexHeaderOld = pindexHeader;
2853  }
2854  }
2855  // Send block tip changed notifications without cs_main
2856  if (fNotify) {
2857  uiInterface.NotifyHeaderTip(GetSynchronizationState(fInitialBlockDownload), pindexHeader);
2858  }
2859  return fNotify;
2860 }
2861 
2863  AssertLockNotHeld(cs_main);
2864 
2865  if (GetMainSignals().CallbacksPending() > 10) {
2867  }
2868 }
2869 
2870 bool CChainState::ActivateBestChain(BlockValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2871  // Note that while we're often called here from ProcessNewBlock, this is
2872  // far from a guarantee. Things in the P2P/RPC will often end up calling
2873  // us in the middle of ProcessNewBlock - do not assume pblock is set
2874  // sanely for performance or correctness!
2875  AssertLockNotHeld(cs_main);
2876 
2877  // ABC maintains a fair degree of expensive-to-calculate internal state
2878  // because this function periodically releases cs_main so that it does not lock up other threads for too long
2879  // during large connects - and to allow for e.g. the callback queue to drain
2880  // we use m_cs_chainstate to enforce mutual exclusion so that only one caller may execute this function at a time
2882 
2883  CBlockIndex *pindexMostWork = nullptr;
2884  CBlockIndex *pindexNewTip = nullptr;
2885  int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2886  do {
2887  // Block until the validation queue drains. This should largely
2888  // never happen in normal operation, however may happen during
2889  // reindex, causing memory blowup if we run too far ahead.
2890  // Note that if a validationinterface callback ends up calling
2891  // ActivateBestChain this may lead to a deadlock! We should
2892  // probably have a DEBUG_LOCKORDER test for this in the future.
2894 
2895  {
2896  LOCK(cs_main);
2897  LOCK(m_mempool.cs); // Lock transaction pool for at least as long as it takes for connectTrace to be consumed
2898  CBlockIndex* starting_tip = m_chain.Tip();
2899  bool blocks_connected = false;
2900  do {
2901  // We absolutely may not unlock cs_main until we've made forward progress
2902  // (with the exception of shutdown due to hardware issues, low disk space, etc).
2903  ConnectTrace connectTrace; // Destructed before cs_main is unlocked
2904 
2905  if (pindexMostWork == nullptr) {
2906  pindexMostWork = FindMostWorkChain();
2907  }
2908 
2909  // Whether we have anything to do at all.
2910  if (pindexMostWork == nullptr || pindexMostWork == m_chain.Tip()) {
2911  break;
2912  }
2913 
2914  bool fInvalidFound = false;
2915  std::shared_ptr<const CBlock> nullBlockPtr;
2916  if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace)) {
2917  // A system error occurred
2918  return false;
2919  }
2920  blocks_connected = true;
2921 
2922  if (fInvalidFound) {
2923  // Wipe cache, we may need another branch now.
2924  pindexMostWork = nullptr;
2925  }
2926  pindexNewTip = m_chain.Tip();
2927 
2928  for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2929  assert(trace.pblock && trace.pindex);
2930  GetMainSignals().BlockConnected(trace.pblock, trace.pindex);
2931  }
2932  } while (!m_chain.Tip() || (starting_tip && CBlockIndexWorkComparator()(m_chain.Tip(), starting_tip)));
2933  if (!blocks_connected) return true;
2934 
2935  const CBlockIndex* pindexFork = m_chain.FindFork(starting_tip);
2936  bool fInitialDownload = IsInitialBlockDownload();
2937 
2938  // Notify external listeners about the new tip.
2939  // Enqueue while holding cs_main to ensure that UpdatedBlockTip is called in the order in which blocks are connected
2940  if (pindexFork != pindexNewTip) {
2941  // Notify ValidationInterface subscribers
2942  GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2943 
2944  // Always notify the UI if a new block tip was connected
2945  uiInterface.NotifyBlockTip(GetSynchronizationState(fInitialDownload), pindexNewTip);
2946  }
2947  }
2948  // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2949 
2950  if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2951 
2952  // We check shutdown only after giving ActivateBestChainStep a chance to run once so that we
2953  // never shutdown before connecting the genesis block during LoadChainTip(). Previously this
2954  // caused an assert() failure during shutdown in such cases as the UTXO DB flushing checks
2955  // that the best block hash is non-null.
2956  if (ShutdownRequested()) break;
2957  } while (pindexNewTip != pindexMostWork);
2958  CheckBlockIndex(chainparams.GetConsensus());
2959 
2960  // Write changes periodically to disk, after relay.
2961  if (!FlushStateToDisk(chainparams, state, FlushStateMode::PERIODIC)) {
2962  return false;
2963  }
2964 
2965  return true;
2966 }
2967 
2968 bool ActivateBestChain(BlockValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2969  return ::ChainstateActive().ActivateBestChain(state, chainparams, std::move(pblock));
2970 }
2971 
2973 {
2974  {
2975  LOCK(cs_main);
2976  if (pindex->nChainWork < m_chain.Tip()->nChainWork) {
2977  // Nothing to do, this block is not at the tip.
2978  return true;
2979  }
2981  // The chain has been extended since the last call, reset the counter.
2983  }
2985  setBlockIndexCandidates.erase(pindex);
2987  if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2988  // We can't keep reducing the counter if somebody really wants to
2989  // call preciousblock 2**31-1 times on the same set of tips...
2991  }
2992  if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->HaveTxsDownloaded()) {
2993  setBlockIndexCandidates.insert(pindex);
2995  }
2996  }
2997 
2998  return ActivateBestChain(state, params, std::shared_ptr<const CBlock>());
2999 }
3000 bool PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex *pindex) {
3001  return ::ChainstateActive().PreciousBlock(state, params, pindex);
3002 }
3003 
3005 {
3006  CBlockIndex* to_mark_failed = pindex;
3007  bool pindex_was_in_chain = false;
3008  int disconnected = 0;
3009 
3010  // We do not allow ActivateBestChain() to run while InvalidateBlock() is
3011  // running, as that could cause the tip to change while we disconnect
3012  // blocks.
3014 
3015  // We'll be acquiring and releasing cs_main below, to allow the validation
3016  // callbacks to run. However, we should keep the block index in a
3017  // consistent state as we disconnect blocks -- in particular we need to
3018  // add equal-work blocks to setBlockIndexCandidates as we disconnect.
3019  // To avoid walking the block index repeatedly in search of candidates,
3020  // build a map once so that we can look up candidate blocks by chain
3021  // work as we go.
3022  std::multimap<const arith_uint256, CBlockIndex *> candidate_blocks_by_work;
3023 
3024  {
3025  LOCK(cs_main);
3026  for (const auto& entry : m_blockman.m_block_index) {
3027  CBlockIndex *candidate = entry.second;
3028  // We don't need to put anything in our active chain into the
3029  // multimap, because those candidates will be found and considered
3030  // as we disconnect.
3031  // Instead, consider only non-active-chain blocks that have at
3032  // least as much work as where we expect the new tip to end up.
3033  if (!m_chain.Contains(candidate) &&
3034  !CBlockIndexWorkComparator()(candidate, pindex->pprev) &&
3035  candidate->IsValid(BLOCK_VALID_TRANSACTIONS) &&
3036  candidate->HaveTxsDownloaded()) {
3037  candidate_blocks_by_work.insert(std::make_pair(candidate->nChainWork, candidate));
3038  }
3039  }
3040  }
3041 
3042  // Disconnect (descendants of) pindex, and mark them invalid.
3043  while (true) {
3044  if (ShutdownRequested()) break;
3045 
3046  // Make sure the queue of validation callbacks doesn't grow unboundedly.
3048 
3049  LOCK(cs_main);
3050  LOCK(m_mempool.cs); // Lock for as long as disconnectpool is in scope to make sure UpdateMempoolForReorg is called after DisconnectTip without unlocking in between
3051  if (!m_chain.Contains(pindex)) break;
3052  pindex_was_in_chain = true;
3053  CBlockIndex *invalid_walk_tip = m_chain.Tip();
3054 
3055  // ActivateBestChain considers blocks already in m_chain
3056  // unconditionally valid already, so force disconnect away from it.
3057  DisconnectedBlockTransactions disconnectpool;
3058  bool ret = DisconnectTip(state, chainparams, &disconnectpool);
3059  // DisconnectTip will add transactions to disconnectpool.
3060  // Adjust the mempool to be consistent with the new tip, adding
3061  // transactions back to the mempool if disconnecting was successful,
3062  // and we're not doing a very deep invalidation (in which case
3063  // keeping the mempool up to date is probably futile anyway).
3064  UpdateMempoolForReorg(m_mempool, disconnectpool, /* fAddToMempool = */ (++disconnected <= 10) && ret);
3065  if (!ret) return false;
3066  assert(invalid_walk_tip->pprev == m_chain.Tip());
3067 
3068  // We immediately mark the disconnected blocks as invalid.
3069  // This prevents a case where pruned nodes may fail to invalidateblock
3070  // and be left unable to start as they have no tip candidates (as there
3071  // are no blocks that meet the "have data and are not invalid per
3072  // nStatus" criteria for inclusion in setBlockIndexCandidates).
3073  invalid_walk_tip->nStatus |= BLOCK_FAILED_VALID;
3074  setDirtyBlockIndex.insert(invalid_walk_tip);
3075  setBlockIndexCandidates.erase(invalid_walk_tip);
3076  setBlockIndexCandidates.insert(invalid_walk_tip->pprev);
3077  if (invalid_walk_tip->pprev == to_mark_failed && (to_mark_failed->nStatus & BLOCK_FAILED_VALID)) {
3078  // We only want to mark the last disconnected block as BLOCK_FAILED_VALID; its children
3079  // need to be BLOCK_FAILED_CHILD instead.
3080  to_mark_failed->nStatus = (to_mark_failed->nStatus ^ BLOCK_FAILED_VALID) | BLOCK_FAILED_CHILD;
3081  setDirtyBlockIndex.insert(to_mark_failed);
3082  }
3083 
3084  // Add any equal or more work headers to setBlockIndexCandidates
3085  auto candidate_it = candidate_blocks_by_work.lower_bound(invalid_walk_tip->pprev->nChainWork);
3086  while (candidate_it != candidate_blocks_by_work.end()) {
3087  if (!CBlockIndexWorkComparator()(candidate_it->second, invalid_walk_tip->pprev)) {
3088  setBlockIndexCandidates.insert(candidate_it->second);
3089  candidate_it = candidate_blocks_by_work.erase(candidate_it);
3090  } else {
3091  ++candidate_it;
3092  }
3093  }
3094 
3095  // Track the last disconnected block, so we can correct its BLOCK_FAILED_CHILD status in future
3096  // iterations, or, if it's the last one, call InvalidChainFound on it.
3097  to_mark_failed = invalid_walk_tip;
3098  }
3099 
3100  CheckBlockIndex(chainparams.GetConsensus());
3101 
3102  {
3103  LOCK(cs_main);
3104  if (m_chain.Contains(to_mark_failed)) {
3105  // If the to-be-marked invalid block is in the active chain, something is interfering and we can't proceed.
3106  return false;
3107  }
3108 
3109  // Mark pindex (or the last disconnected block) as invalid, even when it never was in the main chain
3110  to_mark_failed->nStatus |= BLOCK_FAILED_VALID;
3111  setDirtyBlockIndex.insert(to_mark_failed);
3112  setBlockIndexCandidates.erase(to_mark_failed);
3113  m_blockman.m_failed_blocks.insert(to_mark_failed);
3114 
3115  // If any new blocks somehow arrived while we were disconnecting
3116  // (above), then the pre-calculation of what should go into
3117  // setBlockIndexCandidates may have missed entries. This would
3118  // technically be an inconsistency in the block index, but if we clean
3119  // it up here, this should be an essentially unobservable error.
3120  // Loop back over all block index entries and add any missing entries
3121  // to setBlockIndexCandidates.
3122  BlockMap::iterator it = m_blockman.m_block_index.begin();
3123  while (it != m_blockman.m_block_index.end()) {
3124  if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && !setBlockIndexCandidates.value_comp()(it->second, m_chain.Tip())) {
3125  setBlockIndexCandidates.insert(it->second);
3126  }
3127  it++;
3128  }
3129 
3130  InvalidChainFound(to_mark_failed);
3131  }
3132 
3133  // Only notify about a new block tip if the active chain was modified.
3134  if (pindex_was_in_chain) {
3135  uiInterface.NotifyBlockTip(GetSynchronizationState(IsInitialBlockDownload()), to_mark_failed->pprev);
3136  }
3137  return true;
3138 }
3139 
3140 bool InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex) {
3141  return ::ChainstateActive().InvalidateBlock(state, chainparams, pindex);
3142 }
3143 
3145  AssertLockHeld(cs_main);
3146 
3147  int nHeight = pindex->nHeight;
3148 
3149  // Remove the invalidity flag from this block and all its descendants.
3150  BlockMap::iterator it = m_blockman.m_block_index.begin();
3151  while (it != m_blockman.m_block_index.end()) {
3152  if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
3153  it->second->nStatus &= ~BLOCK_FAILED_MASK;
3154  setDirtyBlockIndex.insert(it->second);
3155  if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && setBlockIndexCandidates.value_comp()(m_chain.Tip(), it->second)) {
3156  setBlockIndexCandidates.insert(it->second);
3157  }
3158  if (it->second == pindexBestInvalid) {
3159  // Reset invalid block marker if it was pointing to one of those.
3160  pindexBestInvalid = nullptr;
3161  }
3162  m_blockman.m_failed_blocks.erase(it->second);
3163  }
3164  it++;
3165  }
3166 
3167  // Remove the invalidity flag from all ancestors too.
3168  while (pindex != nullptr) {
3169  if (pindex->nStatus & BLOCK_FAILED_MASK) {
3170  pindex->nStatus &= ~BLOCK_FAILED_MASK;
3171  setDirtyBlockIndex.insert(pindex);
3172  m_blockman.m_failed_blocks.erase(pindex);
3173  }
3174  pindex = pindex->pprev;
3175  }
3176 }
3177 
3180 }
3181 
3183 {
3184  AssertLockHeld(cs_main);
3185 
3186  // Check for duplicate
3187  uint256 hash = block.GetHash();
3188  BlockMap::iterator it = m_block_index.find(hash);
3189  if (it != m_block_index.end())
3190  return it->second;
3191 
3192  // Construct new block index object
3193  CBlockIndex* pindexNew = new CBlockIndex(block);
3194  // We assign the sequence id to blocks only when the full data is available,
3195  // to avoid miners withholding blocks but broadcasting headers, to get a
3196  // competitive advantage.
3197  pindexNew->nSequenceId = 0;
3198  BlockMap::iterator mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
3199  pindexNew->phashBlock = &((*mi).first);
3200  BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
3201  if (miPrev != m_block_index.end())
3202  {
3203  pindexNew->pprev = (*miPrev).second;
3204  pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
3205  pindexNew->BuildSkip();
3206  }
3207  pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
3208  pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
3209  pindexNew->RaiseValidity(BLOCK_VALID_TREE);
3210  if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
3211  pindexBestHeader = pindexNew;
3212 
3213  setDirtyBlockIndex.insert(pindexNew);
3214 
3215  return pindexNew;
3216 }
3217 
3219 void CChainState::ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos, const Consensus::Params& consensusParams)
3220 {
3221  pindexNew->nTx = block.vtx.size();
3222  pindexNew->nChainTx = 0;
3223  pindexNew->nFile = pos.nFile;
3224  pindexNew->nDataPos = pos.nPos;
3225  pindexNew->nUndoPos = 0;
3226  pindexNew->nStatus |= BLOCK_HAVE_DATA;
3227  if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
3228  pindexNew->nStatus |= BLOCK_OPT_WITNESS;
3229  }
3231  setDirtyBlockIndex.insert(pindexNew);
3232 
3233  if (pindexNew->pprev == nullptr || pindexNew->pprev->HaveTxsDownloaded()) {
3234  // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3235  std::deque<CBlockIndex*> queue;
3236  queue.push_back(pindexNew);
3237 
3238  // Recursively process any descendant blocks that now may be eligible to be connected.
3239  while (!queue.empty()) {
3240  CBlockIndex *pindex = queue.front();
3241  queue.pop_front();
3242  pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3243  {
3245  pindex->nSequenceId = nBlockSequenceId++;
3246  }
3247  if (m_chain.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) {
3248  setBlockIndexCandidates.insert(pindex);
3249  }
3250  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = m_blockman.m_blocks_unlinked.equal_range(pindex);
3251  while (range.first != range.second) {
3252  std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3253  queue.push_back(it->second);
3254  range.first++;
3255  m_blockman.m_blocks_unlinked.erase(it);
3256  }
3257  }
3258  } else {
3259  if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3260  m_blockman.m_blocks_unlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3261  }
3262  }
3263 }
3264 
3265 static bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
3266 {
3267  LOCK(cs_LastBlockFile);
3268 
3269  unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3270  if (vinfoBlockFile.size() <= nFile) {
3271  vinfoBlockFile.resize(nFile + 1);
3272  }
3273 
3274  bool finalize_undo = false;
3275  if (!fKnown) {
3276  while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
3277  // when the undo file is keeping up with the block file, we want to flush it explicitly
3278  // when it is lagging behind (more blocks arrive than are being connected), we let the
3279  // undo block write case handle it
3280  finalize_undo = (vinfoBlockFile[nFile].nHeightLast == (unsigned int)ChainActive().Tip()->nHeight);
3281  nFile++;
3282  if (vinfoBlockFile.size() <= nFile) {
3283  vinfoBlockFile.resize(nFile + 1);
3284  }
3285  }
3286  pos.nFile = nFile;
3287  pos.nPos = vinfoBlockFile[nFile].nSize;
3288  }
3289 
3290  if ((int)nFile != nLastBlockFile) {
3291  if (!fKnown) {
3292  LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
3293  }
3294  FlushBlockFile(!fKnown, finalize_undo);
3295  nLastBlockFile = nFile;
3296  }
3297 
3298  vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3299  if (fKnown)
3300  vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3301  else
3302  vinfoBlockFile[nFile].nSize += nAddSize;
3303 
3304  if (!fKnown) {
3305  bool out_of_space;
3306  size_t bytes_allocated = BlockFileSeq().Allocate(pos, nAddSize, out_of_space);
3307  if (out_of_space) {
3308  return AbortNode("Disk space is too low!", _("Disk space is too low!"));
3309  }
3310  if (bytes_allocated != 0 && fPruneMode) {
3311  fCheckForPruning = true;
3312  }
3313  }
3314 
3315  setDirtyFileInfo.insert(nFile);
3316  return true;
3317 }
3318 
3319 static bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
3320 {
3321  pos.nFile = nFile;
3322 
3323  LOCK(cs_LastBlockFile);
3324 
3325  pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3326  vinfoBlockFile[nFile].nUndoSize += nAddSize;
3327  setDirtyFileInfo.insert(nFile);
3328 
3329  bool out_of_space;
3330  size_t bytes_allocated = UndoFileSeq().Allocate(pos, nAddSize, out_of_space);
3331  if (out_of_space) {
3332  return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
3333  }
3334  if (bytes_allocated != 0 && fPruneMode) {
3335  fCheckForPruning = true;
3336  }
3337 
3338  return true;
3339 }
3340 
3341 static bool CheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
3342 {
3343  // Check proof of work matches claimed amount
3344  if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
3345  return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "high-hash", "proof of work failed");
3346 
3347  return true;
3348 }
3349 
3350 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
3351 {
3352  // These are checks that are independent of context.
3353 
3354  if (block.fChecked)
3355  return true;
3356 
3357  // Check that the header is valid (particularly PoW). This is mostly
3358  // redundant with the call in AcceptBlockHeader.
3359  if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
3360  return false;
3361 
3362  // Signet only: check block solution
3363  if (consensusParams.signet_blocks && fCheckPOW && !CheckSignetBlockSolution(block, consensusParams)) {
3364  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-signet-blksig", "signet block signature validation failure");
3365  }
3366 
3367  // Check the merkle root.
3368  if (fCheckMerkleRoot) {
3369  bool mutated;
3370  uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
3371  if (block.hashMerkleRoot != hashMerkleRoot2)
3372  return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txnmrklroot", "hashMerkleRoot mismatch");
3373 
3374  // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3375  // of transactions in a block without affecting the merkle root of a block,
3376  // while still invalidating it.
3377  if (mutated)
3378  return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txns-duplicate", "duplicate transaction");
3379  }
3380 
3381  // All potential-corruption validation must be done before we do any
3382  // transaction validation, as otherwise we may mark the header as invalid
3383  // because we receive the wrong transactions for it.
3384  // Note that witness malleability is checked in ContextualCheckBlock, so no
3385  // checks that use witness data may be performed here.
3386 
3387  // Size limits
3389  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-length", "size limits failed");
3390 
3391  // First transaction must be coinbase, the rest must not be
3392  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
3393  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-missing", "first tx is not coinbase");
3394  for (unsigned int i = 1; i < block.vtx.size(); i++)
3395  if (block.vtx[i]->IsCoinBase())
3396  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple", "more than one coinbase");
3397 
3398  // Check transactions
3399  // Must check for duplicate inputs (see CVE-2018-17144)
3400  for (const auto& tx : block.vtx) {
3401  TxValidationState tx_state;
3402  if (!CheckTransaction(*tx, tx_state)) {
3403  // CheckBlock() does context-free validation checks. The only
3404  // possible failures are consensus failures.
3405  assert(tx_state.GetResult() == TxValidationResult::TX_CONSENSUS);
3407  strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), tx_state.GetDebugMessage()));
3408  }
3409  }
3410  unsigned int nSigOps = 0;
3411  for (const auto& tx : block.vtx)
3412  {
3413  nSigOps += GetLegacySigOpCount(*tx);
3414  }
3416  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "out-of-bounds SigOpCount");
3417 
3418  if (fCheckPOW && fCheckMerkleRoot)
3419  block.fChecked = true;
3420 
3421  return true;
3422 }
3423 
3424 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
3425 {
3426  int height = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
3427  return (height >= params.SegwitHeight);
3428 }
3429 
3430 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
3431 {
3432  int commitpos = GetWitnessCommitmentIndex(block);
3433  static const std::vector<unsigned char> nonce(32, 0x00);
3434  if (commitpos != NO_WITNESS_COMMITMENT && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
3435  CMutableTransaction tx(*block.vtx[0]);
3436  tx.vin[0].scriptWitness.stack.resize(1);
3437  tx.vin[0].scriptWitness.stack[0] = nonce;
3438  block.vtx[0] = MakeTransactionRef(std::move(tx));
3439  }
3440 }
3441 
3442 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
3443 {
3444  std::vector<unsigned char> commitment;
3445  int commitpos = GetWitnessCommitmentIndex(block);
3446  std::vector<unsigned char> ret(32, 0x00);
3447  if (consensusParams.SegwitHeight != std::numeric_limits<int>::max()) {
3448  if (commitpos == NO_WITNESS_COMMITMENT) {
3449  uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
3450  CHash256().Write(witnessroot).Write(ret).Finalize(witnessroot);
3451  CTxOut out;
3452  out.nValue = 0;
3454  out.scriptPubKey[0] = OP_RETURN;
3455  out.scriptPubKey[1] = 0x24;
3456  out.scriptPubKey[2] = 0xaa;
3457  out.scriptPubKey[3] = 0x21;
3458  out.scriptPubKey[4] = 0xa9;
3459  out.scriptPubKey[5] = 0xed;
3460  memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
3461  commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
3462  CMutableTransaction tx(*block.vtx[0]);
3463  tx.vout.push_back(out);
3464  block.vtx[0] = MakeTransactionRef(std::move(tx));
3465  }
3466  }
3467  UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
3468  return commitment;
3469 }
3470 
3473 {
3474  const MapCheckpoints& checkpoints = data.mapCheckpoints;
3475 
3476  for (const MapCheckpoints::value_type& i : reverse_iterate(checkpoints))
3477  {
3478  const uint256& hash = i.second;
3479  CBlockIndex* pindex = LookupBlockIndex(hash);
3480  if (pindex) {
3481  return pindex;
3482  }
3483  }
3484  return nullptr;
3485 }
3486 
3496 static bool ContextualCheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
3497 {
3498  assert(pindexPrev != nullptr);
3499  const int nHeight = pindexPrev->nHeight + 1;
3500 
3501  // Check proof of work
3502  const Consensus::Params& consensusParams = params.GetConsensus();
3503  if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3504  return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits", "incorrect proof of work");
3505 
3506  // Check against checkpoints
3507  if (fCheckpointsEnabled) {
3508  // Don't accept any forks from the main chain prior to last checkpoint.
3509  // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
3510  // BlockIndex().
3511  CBlockIndex* pcheckpoint = GetLastCheckpoint(params.Checkpoints());
3512  if (pcheckpoint && nHeight < pcheckpoint->nHeight) {
3513  LogPrintf("ERROR: %s: forked chain older than last checkpoint (height %d)\n", __func__, nHeight);
3514  return state.Invalid(BlockValidationResult::BLOCK_CHECKPOINT, "bad-fork-prior-to-checkpoint");
3515  }
3516  }
3517 
3518  // Check timestamp against prev
3519  if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3520  return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-too-old", "block's timestamp is too early");
3521 
3522  // Check timestamp
3523  if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
3524  return state.Invalid(BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new", "block timestamp too far in the future");
3525 
3526  // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
3527  // check for version 2, 3 and 4 upgrades
3528  if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
3529  (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
3530  (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
3531  return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, strprintf("bad-version(0x%08x)", block.nVersion),
3532  strprintf("rejected nVersion=0x%08x block", block.nVersion));
3533 
3534  return true;
3535 }
3536 
3543 static bool ContextualCheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
3544 {
3545  const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
3546 
3547  // Start enforcing BIP113 (Median Time Past).
3548  int nLockTimeFlags = 0;
3549  if (nHeight >= consensusParams.CSVHeight) {
3550  assert(pindexPrev != nullptr);
3551  nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
3552  }
3553 
3554  int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3555  ? pindexPrev->GetMedianTimePast()
3556  : block.GetBlockTime();
3557 
3558  // Check that all transactions are finalized
3559  for (const auto& tx : block.vtx) {
3560  if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
3561  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal", "non-final transaction");
3562  }
3563  }
3564 
3565  // Enforce rule that the coinbase starts with serialized block height
3566  if (nHeight >= consensusParams.BIP34Height)
3567  {
3568  CScript expect = CScript() << nHeight;
3569  if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
3570  !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
3571  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-height", "block height mismatch in coinbase");
3572  }
3573  }
3574 
3575  // Validation for witness commitments.
3576  // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
3577  // coinbase (where 0x0000....0000 is used instead).
3578  // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness reserved value (unconstrained).
3579  // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
3580  // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
3581  // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness reserved value). In case there are
3582  // multiple, the last one is used.
3583  bool fHaveWitness = false;
3584  if (nHeight >= consensusParams.SegwitHeight) {
3585  int commitpos = GetWitnessCommitmentIndex(block);
3586  if (commitpos != NO_WITNESS_COMMITMENT) {
3587  bool malleated = false;
3588  uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
3589  // The malleation check is ignored; as the transaction tree itself
3590  // already does not permit it, it is impossible to trigger in the
3591  // witness tree.
3592  if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3593  return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-nonce-size", strprintf("%s : invalid witness reserved value size", __func__));
3594  }
3595  CHash256().Write(hashWitness).Write(block.vtx[0]->vin[0].scriptWitness.stack[0]).Finalize(hashWitness);
3596  if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3597  return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-merkle-match", strprintf("%s : witness merkle commitment mismatch", __func__));
3598  }
3599  fHaveWitness = true;
3600  }
3601  }
3602 
3603  // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3604  if (!fHaveWitness) {
3605  for (const auto& tx : block.vtx) {
3606  if (tx->HasWitness()) {
3607  return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "unexpected-witness", strprintf("%s : unexpected witness data found", __func__));
3608  }
3609  }
3610  }
3611 
3612  // After the coinbase witness reserved value and commitment are verified,
3613  // we can check if the block weight passes (before we've checked the
3614  // coinbase witness, it would be possible for the weight to be too
3615  // large by filling up the coinbase witness, which doesn't change
3616  // the block hash, so we couldn't mark the block as permanently
3617  // failed).
3618  if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3619  return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-weight", strprintf("%s : weight limit failed", __func__));
3620  }
3621 
3622  return true;
3623 }
3624 
3625 bool BlockManager::AcceptBlockHeader(const CBlockHeader& block, BlockValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3626 {
3627  AssertLockHeld(cs_main);
3628  // Check for duplicate
3629  uint256 hash = block.GetHash();
3630  BlockMap::iterator miSelf = m_block_index.find(hash);
3631  CBlockIndex *pindex = nullptr;
3632  if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3633  if (miSelf != m_block_index.end()) {
3634  // Block header is already known.
3635  pindex = miSelf->second;
3636  if (ppindex)
3637  *ppindex = pindex;
3638  if (pindex->nStatus & BLOCK_FAILED_MASK) {
3639  LogPrintf("ERROR: %s: block %s is marked invalid\n", __func__, hash.ToString());
3640  return state.Invalid(BlockValidationResult::BLOCK_CACHED_INVALID, "duplicate");
3641  }
3642  return true;
3643  }
3644 
3645  if (!CheckBlockHeader(block, state, chainparams.GetConsensus())) {
3646  LogPrint(BCLog::VALIDATION, "%s: Consensus::CheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
3647  return false;
3648  }
3649 
3650  // Get prev block index
3651  CBlockIndex* pindexPrev = nullptr;
3652  BlockMap::iterator mi = m_block_index.find(block.hashPrevBlock);
3653  if (mi == m_block_index.end()) {
3654  LogPrintf("ERROR: %s: prev block not found\n", __func__);
3655  return state.Invalid(BlockValidationResult::BLOCK_MISSING_PREV, "prev-blk-not-found");
3656  }
3657  pindexPrev = (*mi).second;
3658  if (pindexPrev->nStatus & BLOCK_FAILED_MASK) {
3659  LogPrintf("ERROR: %s: prev block invalid\n", __func__);
3660  return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
3661  }
3662  if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3663  return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), state.ToString());
3664 
3665  /* Determine if this block descends from any block which has been found
3666  * invalid (m_failed_blocks), then mark pindexPrev and any blocks between
3667  * them as failed. For example:
3668  *
3669  * D3
3670  * /
3671  * B2 - C2
3672  * / \
3673  * A D2 - E2 - F2
3674  * \
3675  * B1 - C1 - D1 - E1
3676  *
3677  * In the case that we attempted to reorg from E1 to F2, only to find
3678  * C2 to be invalid, we would mark D2, E2, and F2 as BLOCK_FAILED_CHILD
3679  * but NOT D3 (it was not in any of our candidate sets at the time).
3680  *
3681  * In any case D3 will also be marked as BLOCK_FAILED_CHILD at restart
3682  * in LoadBlockIndex.
3683  */
3684  if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
3685  // The above does not mean "invalid": it checks if the previous block
3686  // hasn't been validated up to BLOCK_VALID_SCRIPTS. This is a performance
3687  // optimization, in the common case of adding a new block to the tip,
3688  // we don't need to iterate over the failed blocks list.
3689  for (const CBlockIndex* failedit : m_failed_blocks) {
3690  if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
3691  assert(failedit->nStatus & BLOCK_FAILED_VALID);
3692  CBlockIndex* invalid_walk = pindexPrev;
3693  while (invalid_walk != failedit) {
3694  invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
3695  setDirtyBlockIndex.insert(invalid_walk);
3696  invalid_walk = invalid_walk->pprev;
3697  }
3698  LogPrintf("ERROR: %s: prev block invalid\n", __func__);
3699  return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
3700  }
3701  }
3702  }
3703  }
3704  if (pindex == nullptr)
3705  pindex = AddToBlockIndex(block);
3706 
3707  if (ppindex)
3708  *ppindex = pindex;
3709 
3710  return true;
3711 }
3712 
3713 // Exposed wrapper for AcceptBlockHeader
3714 bool ChainstateManager::ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, BlockValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
3715 {
3716  AssertLockNotHeld(cs_main);
3717  {
3718  LOCK(cs_main);
3719  for (const CBlockHeader& header : headers) {
3720  CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3721  bool accepted = m_blockman.AcceptBlockHeader(
3722  header, state, chainparams, &pindex);
3724 
3725  if (!accepted) {
3726  return false;
3727  }
3728  if (ppindex) {
3729  *ppindex = pindex;
3730  }
3731  }
3732  }
3733  if (NotifyHeaderTip()) {
3734  if (::ChainstateActive().IsInitialBlockDownload() && ppindex && *ppindex) {
3735  LogPrintf("Synchronizing blockheaders, height: %d (~%.2f%%)\n", (*ppindex)->nHeight, 100.0/((*ppindex)->nHeight+(GetAdjustedTime() - (*ppindex)->GetBlockTime()) / Params().GetConsensus().nPowTargetSpacing) * (*ppindex)->nHeight);
3736  }
3737  }
3738  return true;
3739 }
3740 
3742 static FlatFilePos SaveBlockToDisk(const CBlock& block, int nHeight, const CChainParams& chainparams, const FlatFilePos* dbp) {
3743  unsigned int nBlockSize = ::GetSerializeSize(block, CLIENT_VERSION);
3744  FlatFilePos blockPos;
3745  if (dbp != nullptr)
3746  blockPos = *dbp;
3747  if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr)) {
3748  error("%s: FindBlockPos failed", __func__);
3749  return FlatFilePos();
3750  }
3751  if (dbp == nullptr) {
3752  if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) {
3753  AbortNode("Failed to write block");
3754  return FlatFilePos();
3755  }
3756  }
3757  return blockPos;
3758 }
3759 
3761 bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock)
3762 {
3763  const CBlock& block = *pblock;
3764 
3765  if (fNewBlock) *fNewBlock = false;
3766  AssertLockHeld(cs_main);
3767 
3768  CBlockIndex *pindexDummy = nullptr;
3769  CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3770 
3771  bool accepted_header = m_blockman.AcceptBlockHeader(block, state, chainparams, &pindex);
3772  CheckBlockIndex(chainparams.GetConsensus());
3773 
3774  if (!accepted_header)
3775  return false;
3776 
3777  // Try to process all requested blocks that we don't have, but only
3778  // process an unrequested block if it's new and has enough work to
3779  // advance our tip, and isn't too many blocks ahead.
3780  bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3781  bool fHasMoreOrSameWork = (m_chain.Tip() ? pindex->nChainWork >= m_chain.Tip()->nChainWork : true);
3782  // Blocks that are too out-of-order needlessly limit the effectiveness of
3783  // pruning, because pruning will not delete block files that contain any
3784  // blocks which are too close in height to the tip. Apply this test
3785  // regardless of whether pruning is enabled; it should generally be safe to
3786  // not process unrequested blocks.
3787  bool fTooFarAhead = (pindex->nHeight > int(m_chain.Height() + MIN_BLOCKS_TO_KEEP));
3788 
3789  // TODO: Decouple this function from the block download logic by removing fRequested
3790  // This requires some new chain data structure to efficiently look up if a
3791  // block is in a chain leading to a candidate for best tip, despite not
3792  // being such a candidate itself.
3793 
3794  // TODO: deal better with return value and error conditions for duplicate
3795  // and unrequested blocks.
3796  if (fAlreadyHave) return true;
3797  if (!fRequested) { // If we didn't ask for it:
3798  if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3799  if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
3800  if (fTooFarAhead) return true; // Block height is too high
3801 
3802  // Protect against DoS attacks from low-work chains.
3803  // If our tip is behind, a peer could try to send us
3804  // low-work blocks on a fake chain that we would never
3805  // request; don't process these.
3806  if (pindex->nChainWork < nMinimumChainWork) return true;
3807  }
3808 
3809  if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3810  !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3811  if (state.IsInvalid() && state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
3812  pindex->nStatus |= BLOCK_FAILED_VALID;
3813  setDirtyBlockIndex.insert(pindex);
3814  }
3815  return error("%s: %s", __func__, state.ToString());
3816  }
3817 
3818  // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3819  // (but if it does not build on our best tip, let the SendMessages loop relay it)
3820  if (!IsInitialBlockDownload() && m_chain.Tip() == pindex->pprev)
3821  GetMainSignals().NewPoWValidBlock(pindex, pblock);
3822 
3823  // Write block to history file
3824  if (fNewBlock) *fNewBlock = true;
3825  try {
3826  FlatFilePos blockPos = SaveBlockToDisk(block, pindex->nHeight, chainparams, dbp);
3827  if (blockPos.IsNull()) {
3828  state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
3829  return false;
3830  }
3831  ReceivedBlockTransactions(block, pindex, blockPos, chainparams.GetConsensus());
3832  } catch (const std::runtime_error& e) {
3833  return AbortNode(state, std::string("System error: ") + e.what());
3834  }
3835 
3836  FlushStateToDisk(chainparams, state, FlushStateMode::NONE);
3837 
3838  CheckBlockIndex(chainparams.GetConsensus());
3839 
3840  return true;
3841 }
3842 
3843 bool ChainstateManager::ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool* fNewBlock)
3844 {
3845  AssertLockNotHeld(cs_main);
3846 
3847  {
3848  CBlockIndex *pindex = nullptr;
3849  if (fNewBlock) *fNewBlock = false;
3850  BlockValidationState state;
3851 
3852  // CheckBlock() does not support multi-threaded block validation because CBlock::fChecked can cause data race.
3853  // Therefore, the following critical section must include the CheckBlock() call as well.
3854  LOCK(cs_main);
3855 
3856  // Ensure that CheckBlock() passes before calling AcceptBlock, as
3857  // belt-and-suspenders.
3858  bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3859  if (ret) {
3860  // Store to disk
3861  ret = ::ChainstateActive().AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
3862  }
3863  if (!ret) {
3864  GetMainSignals().BlockChecked(*pblock, state);
3865  return error("%s: AcceptBlock FAILED (%s)", __func__, state.ToString());
3866  }
3867  }
3868 
3869  NotifyHeaderTip();
3870 
3871  BlockValidationState state; // Only used to report errors, not invalidity - ignore it
3872  if (!::ChainstateActive().ActivateBestChain(state, chainparams, pblock))
3873  return error("%s: ActivateBestChain failed (%s)", __func__, state.ToString());
3874 
3875  return true;
3876 }
3877 
3878 bool TestBlockValidity(BlockValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3879 {
3880  AssertLockHeld(cs_main);
3881  assert(pindexPrev && pindexPrev == ::ChainActive().Tip());
3882  CCoinsViewCache viewNew(&::ChainstateActive().CoinsTip());
3883  uint256 block_hash(block.GetHash());
3884  CBlockIndex indexDummy(block);
3885  indexDummy.pprev = pindexPrev;
3886  indexDummy.nHeight = pindexPrev->nHeight + 1;
3887  indexDummy.phashBlock = &block_hash;
3888 
3889  // NOTE: CheckBlockHeader is called by CheckBlock
3890  if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3891  return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, state.ToString());
3892  if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3893  return error("%s: Consensus::CheckBlock: %s", __func__, state.ToString());
3894  if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3895  return error("%s: Consensus::ContextualCheckBlock: %s", __func__, state.ToString());
3896  if (!::ChainstateActive().ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3897  return false;
3898  assert(state.IsValid());
3899 
3900  return true;
3901 }
3902 
3907 /* Calculate the amount of disk space the block & undo files currently use */
3909 {
3910  LOCK(cs_LastBlockFile);
3911 
3912  uint64_t retval = 0;
3913  for (const CBlockFileInfo &file : vinfoBlockFile) {
3914  retval += file.nSize + file.nUndoSize;
3915  }
3916  return retval;
3917 }
3918 
3919 void BlockManager::PruneOneBlockFile(const int fileNumber)
3920 {
3921  AssertLockHeld(cs_main);
3922  LOCK(cs_LastBlockFile);
3923 
3924  for (const auto& entry : m_block_index) {
3925  CBlockIndex* pindex = entry.second;
3926  if (pindex->nFile == fileNumber) {
3927  pindex->nStatus &= ~BLOCK_HAVE_DATA;
3928  pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3929  pindex->nFile = 0;
3930  pindex->nDataPos = 0;
3931  pindex->nUndoPos = 0;
3932  setDirtyBlockIndex.insert(pindex);
3933 
3934  // Prune from m_blocks_unlinked -- any block we prune would have
3935  // to be downloaded again in order to consider its chain, at which
3936  // point it would be considered as a candidate for
3937  // m_blocks_unlinked or setBlockIndexCandidates.
3938  auto range = m_blocks_unlinked.equal_range(pindex->pprev);
3939  while (range.first != range.second) {
3940  std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3941  range.first++;
3942  if (_it->second == pindex) {
3943  m_blocks_unlinked.erase(_it);
3944  }
3945  }
3946  }
3947  }
3948 
3949  vinfoBlockFile[fileNumber].SetNull();
3950  setDirtyFileInfo.insert(fileNumber);
3951 }
3952 
3953 
3954 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3955 {
3956  for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3957  FlatFilePos pos(*it, 0);
3958  fs::remove(BlockFileSeq().FileName(pos));
3959  fs::remove(UndoFileSeq().FileName(pos));
3960  LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3961  }
3962 }
3963 
3964 void BlockManager::FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
3965 {
3966  assert(fPruneMode && nManualPruneHeight > 0);
3967 
3968  LOCK2(cs_main, cs_LastBlockFile);
3969  if (chain_tip_height < 0) {
3970  return;
3971  }
3972 
3973  // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3974  unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chain_tip_height - MIN_BLOCKS_TO_KEEP);
3975  int count = 0;
3976  for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3977  if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) {
3978  continue;
3979  }
3980  PruneOneBlockFile(fileNumber);
3981  setFilesToPrune.insert(fileNumber);
3982  count++;
3983  }
3984  LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3985 }
3986 
3987 /* This function is called from the RPC code for pruneblockchain */
3988 void PruneBlockFilesManual(int nManualPruneHeight)
3989 {
3990  BlockValidationState state;
3991  const CChainParams& chainparams = Params();
3992  if (!::ChainstateActive().FlushStateToDisk(
3993  chainparams, state, FlushStateMode::NONE, nManualPruneHeight)) {
3994  LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
3995  }
3996 }
3997 
3998 void BlockManager::FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, bool is_ibd)
3999 {
4000  LOCK2(cs_main, cs_LastBlockFile);
4001  if (chain_tip_height < 0 || nPruneTarget == 0) {
4002  return;
4003  }
4004  if ((uint64_t)chain_tip_height <= nPruneAfterHeight) {
4005  return;
4006  }
4007 
4008  unsigned int nLastBlockWeCanPrune = chain_tip_height - MIN_BLOCKS_TO_KEEP;
4009  uint64_t nCurrentUsage = CalculateCurrentUsage();
4010  // We don't check to prune until after we've allocated new space for files
4011  // So we should leave a buffer under our target to account for another allocation
4012  // before the next pruning.
4013  uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
4014  uint64_t nBytesToPrune;
4015  int count = 0;
4016 
4017  if (nCurrentUsage + nBuffer >= nPruneTarget) {
4018  // On a prune event, the chainstate DB is flushed.
4019  // To avoid excessive prune events negating the benefit of high dbcache
4020  // values, we should not prune too rapidly.
4021  // So when pruning in IBD, increase the buffer a bit to avoid a re-prune too soon.
4022  if (is_ibd) {
4023  // Since this is only relevant during IBD, we use a fixed 10%
4024  nBuffer += nPruneTarget / 10;
4025  }
4026 
4027  for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
4028  nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
4029 
4030  if (vinfoBlockFile[fileNumber].nSize == 0) {
4031  continue;
4032  }
4033 
4034  if (nCurrentUsage + nBuffer < nPruneTarget) { // are we below our target?
4035  break;
4036  }
4037 
4038  // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
4039  if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) {
4040  continue;
4041  }
4042 
4043  PruneOneBlockFile(fileNumber);
4044  // Queue up the files for removal
4045  setFilesToPrune.insert(fileNumber);
4046  nCurrentUsage -= nBytesToPrune;
4047  count++;
4048  }
4049  }
4050 
4051  LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
4052  nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
4053  ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
4054  nLastBlockWeCanPrune, count);
4055 }
4056 
4058 {
4059  return FlatFileSeq(GetBlocksDir(), "blk", BLOCKFILE_CHUNK_SIZE);
4060 }
4061 
4063 {
4064  return FlatFileSeq(GetBlocksDir(), "rev", UNDOFILE_CHUNK_SIZE);
4065 }
4066 
4067 FILE* OpenBlockFile(const FlatFilePos &pos, bool fReadOnly) {
4068  return BlockFileSeq().Open(pos, fReadOnly);
4069 }
4070 
4072 static FILE* OpenUndoFile(const FlatFilePos &pos, bool fReadOnly) {
4073  return UndoFileSeq().Open(pos, fReadOnly);
4074 }
4075 
4076 fs::path GetBlockPosFilename(const FlatFilePos &pos)
4077 {
4078  return BlockFileSeq().FileName(pos);
4079 }
4080 
4082 {
4083  AssertLockHeld(cs_main);
4084 
4085  if (hash.IsNull())
4086  return nullptr;
4087 
4088  // Return existing
4089  BlockMap::iterator mi = m_block_index.find(hash);
4090  if (mi != m_block_index.end())
4091  return (*mi).second;
4092 
4093  // Create new
4094  CBlockIndex* pindexNew = new CBlockIndex();
4095  mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
4096  pindexNew->phashBlock = &((*mi).first);
4097 
4098  return pindexNew;
4099 }
4100 
4102  const Consensus::Params& consensus_params,
4103  CBlockTreeDB& blocktree,
4104  std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
4105 {
4106  if (!blocktree.LoadBlockIndexGuts(consensus_params, [this](const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return this->InsertBlockIndex(hash); }))
4107  return false;
4108 
4109  // Calculate nChainWork
4110  std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
4111  vSortedByHeight.reserve(m_block_index.size());
4112  for (const std::pair<const uint256, CBlockIndex*>& item : m_block_index)
4113  {
4114  CBlockIndex* pindex = item.second;
4115  vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
4116  }
4117  sort(vSortedByHeight.begin(), vSortedByHeight.end());
4118  for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
4119  {
4120  if (ShutdownRequested()) return false;
4121  CBlockIndex* pindex = item.second;
4122  pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
4123  pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
4124  // We can link the chain of blocks for which we've received transactions at some point.
4125  // Pruned nodes may have deleted the block.
4126  if (pindex->nTx > 0) {
4127  if (pindex->pprev) {
4128  if (pindex->pprev->HaveTxsDownloaded()) {
4129  pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
4130  } else {
4131  pindex->nChainTx = 0;
4132  m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
4133  }
4134  } else {
4135  pindex->nChainTx = pindex->nTx;
4136  }
4137  }
4138  if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
4139  pindex->nStatus |= BLOCK_FAILED_CHILD;
4140  setDirtyBlockIndex.insert(pindex);
4141  }
4142  if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->HaveTxsDownloaded() || pindex->pprev == nullptr)) {
4143  block_index_candidates.insert(pindex);
4144  }
4145  if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
4146  pindexBestInvalid = pindex;
4147  if (pindex->pprev)
4148  pindex->BuildSkip();
4149  if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
4150  pindexBestHeader = pindex;
4151  }
4152 
4153  return true;
4154 }
4155 
4157  m_failed_blocks.clear();
4158  m_blocks_unlinked.clear();
4159 
4160  for (const BlockMap::value_type& entry : m_block_index) {
4161  delete entry.second;
4162  }
4163 
4164  m_block_index.clear();
4165 }
4166 
4167 bool static LoadBlockIndexDB(ChainstateManager& chainman, const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
4168 {
4169  if (!chainman.m_blockman.LoadBlockIndex(
4170  chainparams.GetConsensus(), *pblocktree,
4172  return false;
4173  }
4174 
4175  // Load block file info
4176  pblocktree->ReadLastBlockFile(nLastBlockFile);
4177  vinfoBlockFile.resize(nLastBlockFile + 1);
4178  LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
4179  for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
4180  pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
4181  }
4182  LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
4183  for (int nFile = nLastBlockFile + 1; true; nFile++) {
4184  CBlockFileInfo info;
4185  if (pblocktree->ReadBlockFileInfo(nFile, info)) {
4186  vinfoBlockFile.push_back(info);
4187  } else {
4188  break;
4189  }
4190  }
4191 
4192  // Check presence of blk files
4193  LogPrintf("Checking all blk files are present...\n");
4194  std::set<int> setBlkDataFiles;
4195  for (const std::pair<const uint256, CBlockIndex*>& item : chainman.BlockIndex()) {
4196  CBlockIndex* pindex = item.second;
4197  if (pindex->nStatus & BLOCK_HAVE_DATA) {
4198  setBlkDataFiles.insert(pindex->nFile);
4199  }
4200  }
4201  for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
4202  {
4203  FlatFilePos pos(*it, 0);
4204  if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
4205  return false;
4206  }
4207  }
4208 
4209  // Check whether we have ever pruned block & undo files
4210  pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
4211  if (fHavePruned)
4212  LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
4213 
4214  // Check whether we need to continue reindexing
4215  bool fReindexing = false;
4216  pblocktree->ReadReindexing(fReindexing);
4217  if(fReindexing) fReindex = true;
4218 
4219  return true;
4220 }
4221 
4223 {
4224  if (args.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
4226  }
4228 }
4229 
4230 bool CChainState::LoadChainTip(const CChainParams& chainparams)
4231 {
4232  AssertLockHeld(cs_main);
4233  const CCoinsViewCache& coins_cache = CoinsTip();
4234  assert(!coins_cache.GetBestBlock().IsNull()); // Never called when the coins view is empty
4235  const CBlockIndex* tip = m_chain.Tip();
4236 
4237  if (tip && tip->GetBlockHash() == coins_cache.GetBestBlock()) {
4238  return true;
4239  }
4240 
4241  // Load pointer to end of best chain
4242  CBlockIndex* pindex = LookupBlockIndex(coins_cache.GetBestBlock());
4243  if (!pindex) {
4244  return false;
4245  }
4246  m_chain.SetTip(pindex);
4248 
4249  tip = m_chain.Tip();
4250  LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
4251  tip->GetBlockHash().ToString(),
4252  m_chain.Height(),
4253  FormatISO8601DateTime(tip->GetBlockTime()),
4254  GuessVerificationProgress(chainparams.TxData(), tip));
4255  return true;
4256 }
4257 
4259 {
4260  uiInterface.ShowProgress(_("Verifying blocks...").translated, 0, false);
4261 }
4262 
4264 {
4265  uiInterface.ShowProgress("", 100, false);
4266 }
4267 
4268 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
4269 {
4270  LOCK(cs_main);
4271  if (::ChainActive().Tip() == nullptr || ::ChainActive().Tip()->pprev == nullptr)
4272  return true;
4273 
4274  // Verify blocks in the best chain
4276  nCheckDepth = ::ChainActive().Height();
4277  nCheckLevel = std::max(0, std::min(4, nCheckLevel));
4278  LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
4279  CCoinsViewCache coins(coinsview);
4280  CBlockIndex* pindex;
4281  CBlockIndex* pindexFailure = nullptr;
4282  int nGoodTransactions = 0;
4283  BlockValidationState state;
4284  int reportDone = 0;
4285  LogPrintf("[0%%]..."); /* Continued */
4286  for (pindex = ::ChainActive().Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
4287  const int percentageDone = std::max(1, std::min(99, (int)(((double)(::ChainActive().Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
4288  if (reportDone < percentageDone/10) {
4289  // report every 10% step
4290  LogPrintf("[%d%%]...", percentageDone); /* Continued */
4291  reportDone = percentageDone/10;
4292  }
4293  uiInterface.ShowProgress(_("Verifying blocks...").translated, percentageDone, false);
4294  if (pindex->nHeight <= ::ChainActive().Height()-nCheckDepth)
4295  break;
4296  if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
4297  // If pruning, only go back as far as we have data.
4298  LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
4299  break;
4300  }
4301  CBlock block;
4302  // check level 0: read from disk
4303  if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
4304  return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4305  // check level 1: verify block validity
4306  if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
4307  return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
4308  pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
4309  // check level 2: verify undo validity
4310  if (nCheckLevel >= 2 && pindex) {
4311  CBlockUndo undo;
4312  if (!pindex->GetUndoPos().IsNull()) {
4313  if (!UndoReadFromDisk(undo, pindex)) {
4314  return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4315  }
4316  }
4317  }
4318  // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
4320  assert(coins.GetBestBlock() == pindex->GetBlockHash());
4321  DisconnectResult res = ::ChainstateActive().DisconnectBlock(block, pindex, coins);
4322  if (res == DISCONNECT_FAILED) {
4323  return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4324  }
4325  if (res == DISCONNECT_UNCLEAN) {
4326  nGoodTransactions = 0;
4327  pindexFailure = pindex;
4328  } else {
4329  nGoodTransactions += block.vtx.size();
4330  }
4331  }
4332  if (ShutdownRequested()) return true;
4333  }
4334  if (pindexFailure)
4335  return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", ::ChainActive().Height() - pindexFailure->nHeight + 1, nGoodTransactions);
4336 
4337  // store block count as we move pindex at check level >= 4
4338  int block_count = ::ChainActive().Height() - pindex->nHeight;
4339 
4340  // check level 4: try reconnecting blocks
4341  if (nCheckLevel >= 4) {
4342  while (pindex != ::ChainActive().Tip()) {
4343  const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(::ChainActive().Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
4344  if (reportDone < percentageDone/10) {
4345  // report every 10% step
4346  LogPrintf("[%d%%]...", percentageDone); /* Continued */
4347  reportDone = percentageDone/10;
4348  }
4349  uiInterface.ShowProgress(_("Verifying blocks...").translated, percentageDone, false);
4350  pindex = ::ChainActive().Next(pindex);
4351  CBlock block;
4352  if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
4353  return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4354  if (!::ChainstateActive().ConnectBlock(block, state, pindex, coins, chainparams))
4355  return error("VerifyDB(): *** found unconnectable block at %d, hash=%s (%s)", pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
4356  if (ShutdownRequested()) return true;
4357  }
4358  }
4359 
4360  LogPrintf("[DONE].\n");
4361  LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", block_count, nGoodTransactions);
4362 
4363  return true;
4364 }
4365 
4367 bool CChainState::RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
4368 {
4369  // TODO: merge with ConnectBlock
4370  CBlock block;
4371  if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
4372  return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4373  }
4374 
4375  for (const CTransactionRef& tx : block.vtx) {
4376  if (!tx->IsCoinBase()) {
4377  for (const CTxIn &txin : tx->vin) {
4378  inputs.SpendCoin(txin.prevout);
4379  }
4380  }
4381  // Pass check = true as every addition may be an overwrite.
4382  AddCoins(inputs, *tx, pindex->nHeight, true);
4383  }
4384  return true;
4385 }
4386 
4388 {
4389  LOCK(cs_main);
4390 
4391  CCoinsView& db = this->CoinsDB();
4392  CCoinsViewCache cache(&db);
4393 
4394  std::vector<uint256> hashHeads = db.GetHeadBlocks();
4395  if (hashHeads.empty()) return true; // We're already in a consistent state.
4396  if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
4397 
4398  uiInterface.ShowProgress(_("Replaying blocks...").translated, 0, false);
4399  LogPrintf("Replaying blocks\n");
4400 
4401  const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
4402  const CBlockIndex* pindexNew; // New tip during the interrupted flush.
4403  const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
4404 
4405  if (m_blockman.m_block_index.count(hashHeads[0]) == 0) {
4406  return error("ReplayBlocks(): reorganization to unknown block requested");
4407  }
4408  pindexNew = m_blockman.m_block_index[hashHeads[0]];
4409 
4410  if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
4411  if (m_blockman.m_block_index.count(hashHeads[1]) == 0) {
4412  return error("ReplayBlocks(): reorganization from unknown block requested");
4413  }
4414  pindexOld = m_blockman.m_block_index[hashHeads[1]];
4415  pindexFork = LastCommonAncestor(pindexOld, pindexNew);
4416  assert(pindexFork != nullptr);
4417  }
4418 
4419  // Rollback along the old branch.
4420  while (pindexOld != pindexFork) {
4421  if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
4422  CBlock block;
4423  if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
4424  return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4425  }
4426  LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
4427  DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
4428  if (res == DISCONNECT_FAILED) {
4429  return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4430  }
4431  // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
4432  // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
4433  // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
4434  // the result is still a version of the UTXO set with the effects of that block undone.
4435  }
4436  pindexOld = pindexOld->pprev;
4437  }
4438 
4439  // Roll forward from the forking point to the new tip.
4440  int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
4441  for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
4442  const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
4443  LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
4444  uiInterface.ShowProgress(_("Replaying blocks...").translated, (int) ((nHeight - nForkHeight) * 100.0 / (pindexNew->nHeight - nForkHeight)) , false);
4445  if (!RollforwardBlock(pindex, cache, params)) return false;
4446  }
4447 
4448  cache.SetBestBlock(pindexNew->GetBlockHash());
4449  cache.Flush();
4450  uiInterface.ShowProgress("", 100, false);
4451  return true;
4452 }
4453 
4456 {
4457  AssertLockHeld(cs_main);
4458  assert(!m_chain.Contains(index)); // Make sure this block isn't active
4459 
4460  // Reduce validity
4461  index->nStatus = std::min<unsigned int>(index->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (index->nStatus & ~BLOCK_VALID_MASK);
4462  // Remove have-data flags.
4463  index->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
4464  // Remove storage location.
4465  index->nFile = 0;
4466  index->nDataPos = 0;
4467  index->nUndoPos = 0;
4468  // Remove various other things
4469  index->nTx = 0;
4470  index->nChainTx = 0;
4471  index->nSequenceId = 0;
4472  // Make sure it gets written.
4473  setDirtyBlockIndex.insert(index);
4474  // Update indexes
4475  setBlockIndexCandidates.erase(index);
4476  auto ret = m_blockman.m_blocks_unlinked.equal_range(index->pprev);
4477  while (ret.first != ret.second) {
4478  if (ret.first->second == index) {
4479  m_blockman.m_blocks_unlinked.erase(ret.first++);
4480  } else {
4481  ++ret.first;
4482  }
4483  }
4484  // Mark parent as eligible for main chain again
4485  if (index->pprev && index->pprev->IsValid(BLOCK_VALID_TRANSACTIONS) && index->pprev->HaveTxsDownloaded()) {
4486  setBlockIndexCandidates.insert(index->pprev);
4487  }
4488 }
4489 
4491 {
4492  // Note that during -reindex-chainstate we are called with an empty m_chain!
4493 
4494  // First erase all post-segwit blocks without witness not in the main chain,
4495  // as this can we done without costly DisconnectTip calls. Active
4496  // blocks will be dealt with below (releasing cs_main in between).
4497  {
4498  LOCK(cs_main);
4499  for (const auto& entry : m_blockman.m_block_index) {
4500  if (IsWitnessEnabled(entry.second->pprev, params.GetConsensus()) && !(entry.second->nStatus & BLOCK_OPT_WITNESS) && !m_chain.Contains(entry.second)) {
4501  EraseBlockData(entry.second);
4502  }
4503  }
4504  }
4505 
4506  // Find what height we need to reorganize to.
4507  CBlockIndex *tip;
4508  int nHeight = 1;
4509  {
4510  LOCK(cs_main);
4511  while (nHeight <= m_chain.Height()) {
4512  // Although SCRIPT_VERIFY_WITNESS is now generally enforced on all
4513  // blocks in ConnectBlock, we don't need to go back and
4514  // re-download/re-verify blocks from before segwit actually activated.
4515  if (IsWitnessEnabled(m_chain[nHeight - 1], params.GetConsensus()) && !(m_chain[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
4516  break;
4517  }
4518  nHeight++;
4519  }
4520 
4521  tip = m_chain.Tip();
4522  }
4523  // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
4524 
4525  BlockValidationState state;
4526  // Loop until the tip is below nHeight, or we reach a pruned block.
4527  while (!ShutdownRequested()) {
4528  {
4529  LOCK(cs_main);
4530  LOCK(m_mempool.cs);
4531  // Make sure nothing changed from under us (this won't happen because RewindBlockIndex runs before importing/network are active)
4532  assert(tip == m_chain.Tip());
4533  if (tip == nullptr || tip->nHeight < nHeight) break;
4534  if (fPruneMode && !(tip->nStatus & BLOCK_HAVE_DATA)) {
4535  // If pruning, don't try rewinding past the HAVE_DATA point;
4536  // since older blocks can't be served anyway, there's
4537  // no need to walk further, and trying to DisconnectTip()
4538  // will fail (and require a needless reindex/redownload
4539  // of the blockchain).
4540  break;
4541  }
4542 
4543  // Disconnect block
4544  if (!DisconnectTip(state, params, nullptr)) {
4545  return error("RewindBlockIndex: unable to disconnect block at height %i (%s)", tip->nHeight, state.ToString());
4546  }
4547 
4548  // Reduce validity flag and have-data flags.
4549  // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
4550  // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
4551  // Note: If we encounter an insufficiently validated block that
4552  // is on m_chain, it must be because we are a pruning node, and
4553  // this block or some successor doesn't HAVE_DATA, so we were unable to
4554  // rewind all the way. Blocks remaining on m_chain at this point
4555  // must not have their validity reduced.
4556  EraseBlockData(tip);
4557 
4558  tip = tip->pprev;
4559  }
4560  // Make sure the queue of validation callbacks doesn't grow unboundedly.
4562 
4563  // Occasionally flush state to disk.
4564  if (!FlushStateToDisk(params, state, FlushStateMode::PERIODIC)) {
4565  LogPrintf("RewindBlockIndex: unable to flush state to disk (%s)\n", state.ToString());
4566  return false;
4567  }
4568  }
4569 
4570  {
4571  LOCK(cs_main);
4572  if (m_chain.Tip() != nullptr) {
4573  // We can't prune block index candidates based on our tip if we have
4574  // no tip due to m_chain being empty!
4576 
4577  CheckBlockIndex(params.GetConsensus());
4578 
4579  // FlushStateToDisk can possibly read ::ChainActive(). Be conservative
4580  // and skip it here, we're about to -reindex-chainstate anyway, so
4581  // it'll get called a bunch real soon.
4582  BlockValidationState state;
4583  if (!FlushStateToDisk(params, state, FlushStateMode::ALWAYS)) {
4584  LogPrintf("RewindBlockIndex: unable to flush state to disk (%s)\n", state.ToString());
4585  return false;
4586  }
4587  }
4588  }
4589 
4590  return true;
4591 }
4592 
4594  nBlockSequenceId = 1;
4595  setBlockIndexCandidates.clear();
4596 }
4597 
4598 // May NOT be used after any connections are up as much
4599 // of the peer-processing logic assumes a consistent
4600 // block index state
4602 {
4603  LOCK(cs_main);
4604  chainman.Unload();
4605  pindexBestInvalid = nullptr;
4606  pindexBestHeader = nullptr;
4607  if (mempool) mempool->clear();
4608  vinfoBlockFile.clear();
4609  nLastBlockFile = 0;
4610  setDirtyBlockIndex.clear();
4611  setDirtyFileInfo.clear();
4613  for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
4614  warningcache[b].clear();
4615  }
4616  fHavePruned = false;
4617 }
4618 
4620 {
4621  AssertLockHeld(cs_main);
4622  // Load block index from databases
4623  bool needs_init = fReindex;
4624  if (!fReindex) {
4625  bool ret = LoadBlockIndexDB(*this, chainparams);
4626  if (!ret) return false;
4627  needs_init = m_blockman.m_block_index.empty();
4628  }
4629 
4630  if (needs_init) {
4631  // Everything here is for *new* reindex/DBs. Thus, though
4632  // LoadBlockIndexDB may have set fReindex if we shut down
4633  // mid-reindex previously, we don't check fReindex and
4634  // instead only check it prior to LoadBlockIndexDB to set
4635  // needs_init.
4636 
4637  LogPrintf("Initializing databases...\n");
4638  }
4639  return true;
4640 }
4641 
4643 {
4644  LOCK(cs_main);
4645 
4646  // Check whether we're already initialized by checking for genesis in
4647  // m_blockman.m_block_index. Note that we can't use m_chain here, since it is
4648  // set based on the coins db, not the block index db, which is the only
4649  // thing loaded at this point.
4650  if (m_blockman.m_block_index.count(chainparams.GenesisBlock().GetHash()))
4651  return true;
4652 
4653  try {
4654  const CBlock& block = chainparams.GenesisBlock();
4655  FlatFilePos blockPos = SaveBlockToDisk(block, 0, chainparams, nullptr);
4656  if (blockPos.IsNull())
4657  return error("%s: writing genesis block to disk failed", __func__);
4658  CBlockIndex *pindex = m_blockman.AddToBlockIndex(block);
4659  ReceivedBlockTransactions(block, pindex, blockPos, chainparams.GetConsensus());
4660  } catch (const std::runtime_error& e) {
4661  return error("%s: failed to write genesis block: %s", __func__, e.what());
4662  }
4663 
4664  return true;
4665 }
4666 
4667 bool LoadGenesisBlock(const CChainParams& chainparams)
4668 {
4670 }
4671 
4672 void LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, FlatFilePos* dbp)
4673 {
4674  // Map of disk positions for blocks with unknown parent (only used for reindex)
4675  static std::multimap<uint256, FlatFilePos> mapBlocksUnknownParent;
4676  int64_t nStart = GetTimeMillis();
4677 
4678  int nLoaded = 0;
4679  try {
4680  // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4682  uint64_t nRewind = blkdat.GetPos();
4683  while (!blkdat.eof()) {
4684  if (ShutdownRequested()) return;
4685 
4686  blkdat.SetPos(nRewind);
4687  nRewind++; // start one byte further next time, in case of failure
4688  blkdat.SetLimit(); // remove former limit
4689  unsigned int nSize = 0;
4690  try {
4691  // locate a header
4692  unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
4693  blkdat.FindByte(chainparams.MessageStart()[0]);
4694  nRewind = blkdat.GetPos()+1;
4695  blkdat >> buf;
4696  if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
4697  continue;
4698  // read size
4699  blkdat >> nSize;
4700  if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
4701  continue;
4702  } catch (const std::exception&) {
4703  // no valid block header found; don't complain
4704  break;
4705  }
4706  try {
4707  // read block
4708  uint64_t nBlockPos = blkdat.GetPos();
4709  if (dbp)
4710  dbp->nPos = nBlockPos;
4711  blkdat.SetLimit(nBlockPos + nSize);
4712  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4713  CBlock& block = *pblock;
4714  blkdat >> block;
4715  nRewind = blkdat.GetPos();
4716 
4717  uint256 hash = block.GetHash();
4718  {
4719  LOCK(cs_main);
4720  // detect out of order blocks, and store them for later
4721  if (hash != chainparams.GetConsensus().hashGenesisBlock && !LookupBlockIndex(block.hashPrevBlock)) {
4722  LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4723  block.hashPrevBlock.ToString());
4724  if (dbp)
4725  mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4726  continue;
4727  }
4728 
4729  // process in case the block isn't known yet
4730  CBlockIndex* pindex = LookupBlockIndex(hash);
4731  if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) {
4732  BlockValidationState state;
4733  if (::ChainstateActive().AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr)) {
4734  nLoaded++;
4735  }
4736  if (state.IsError()) {
4737  break;
4738  }
4739  } else if (hash != chainparams.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
4740  LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
4741  }
4742  }
4743 
4744  // Activate the genesis block so normal node progress can continue
4745  if (hash == chainparams.GetConsensus().hashGenesisBlock) {
4746  BlockValidationState state;
4747  if (!ActivateBestChain(state, chainparams, nullptr)) {
4748  break;
4749  }
4750  }
4751 
4752  NotifyHeaderTip();
4753 
4754  // Recursively process earlier encountered successors of this block
4755  std::deque<uint256> queue;
4756  queue.push_back(hash);
4757  while (!queue.empty()) {
4758  uint256 head = queue.front();
4759  queue.pop_front();
4760  std::pair<std::multimap<uint256, FlatFilePos>::iterator, std::multimap<uint256, FlatFilePos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4761  while (range.first != range.second) {
4762  std::multimap<uint256, FlatFilePos>::iterator it = range.first;
4763  std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4764  if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
4765  {
4766  LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4767  head.ToString());
4768  LOCK(cs_main);
4769  BlockValidationState dummy;
4770  if (::ChainstateActive().AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
4771  {
4772  nLoaded++;
4773  queue.push_back(pblockrecursive->GetHash());
4774  }
4775  }
4776  range.first++;
4777  mapBlocksUnknownParent.erase(it);
4778  NotifyHeaderTip();
4779  }
4780  }
4781  } catch (const std::exception& e) {
4782  LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4783  }
4784  }
4785  } catch (const std::runtime_error& e) {
4786  AbortNode(std::string("System error: ") + e.what());
4787  }
4788  LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4789 }
4790 
4792 {
4793  if (!fCheckBlockIndex) {
4794  return;
4795  }
4796 
4797  LOCK(cs_main);
4798 
4799  // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4800  // so we have the genesis block in m_blockman.m_block_index but no active chain. (A few of the
4801  // tests when iterating the block tree require that m_chain has been initialized.)
4802  if (m_chain.Height() < 0) {
4803  assert(m_blockman.m_block_index.size() <= 1);
4804  return;
4805  }
4806 
4807  // Build forward-pointing map of the entire block tree.
4808  std::multimap<CBlockIndex*,CBlockIndex*> forward;
4809  for (const std::pair<const uint256, CBlockIndex*>& entry : m_blockman.m_block_index) {
4810  forward.insert(std::make_pair(entry.second->pprev, entry.second));
4811  }
4812 
4813  assert(forward.size() == m_blockman.m_block_index.size());
4814 
4815  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4816  CBlockIndex *pindex = rangeGenesis.first->second;
4817  rangeGenesis.first++;
4818  assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4819 
4820  // Iterate over the entire block tree, using depth-first search.
4821  // Along the way, remember whether there are blocks on the path from genesis
4822  // block being explored which are the first to have certain properties.
4823  size_t nNodes = 0;
4824  int nHeight = 0;
4825  CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4826  CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4827  CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4828  CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4829  CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4830  CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4831  CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4832  while (pindex != nullptr) {
4833  nNodes++;
4834  if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4835  if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4836  if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4837  if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4838  if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4839  if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4840  if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4841 
4842  // Begin: actual consistency checks.
4843  if (pindex->pprev == nullptr) {
4844  // Genesis block checks.
4845  assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4846  assert(pindex == m_chain.Genesis()); // The current active chain's genesis block must be this block.
4847  }
4848  if (!pindex->HaveTxsDownloaded()) assert(pindex->nSequenceId <= 0); // nSequenceId can't be set positive for blocks that aren't linked (negative is used for preciousblock)
4849  // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4850  // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4851  if (!fHavePruned) {
4852  // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4853  assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4854  assert(pindexFirstMissing == pindexFirstNeverProcessed);
4855  } else {
4856  // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4857  if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4858  }
4859  if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4860  assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4861  // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to HaveTxsDownloaded().
4862  assert((pindexFirstNeverProcessed == nullptr) == pindex->HaveTxsDownloaded());
4863  assert((pindexFirstNotTransactionsValid == nullptr) == pindex->HaveTxsDownloaded());
4864  assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4865  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.
4866  assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4867  assert(pindexFirstNotTreeValid == nullptr); // All m_blockman.m_block_index entries must at least be TREE valid
4868  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4869  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4870  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4871  if (pindexFirstInvalid == nullptr) {
4872  // Checks for not-invalid blocks.
4873  assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4874  }
4875  if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && pindexFirstNeverProcessed == nullptr) {
4876  if (pindexFirstInvalid == nullptr) {
4877  // If this block sorts at least as good as the current tip and
4878  // is valid and we have all data for its parents, it must be in
4879  // setBlockIndexCandidates. m_chain.Tip() must also be there
4880  // even if some data has been pruned.
4881  if (pindexFirstMissing == nullptr || pindex == m_chain.Tip()) {
4882  assert(setBlockIndexCandidates.count(pindex));
4883  }
4884  // If some parent is missing, then it could be that this block was in
4885  // setBlockIndexCandidates but had to be removed because of the missing data.
4886  // In this case it must be in m_blocks_unlinked -- see test below.
4887  }
4888  } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4889  assert(setBlockIndexCandidates.count(pindex) == 0);
4890  }
4891  // Check whether this block is in m_blocks_unlinked.
4892  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = m_blockman.m_blocks_unlinked.equal_range(pindex->pprev);
4893  bool foundInUnlinked = false;
4894  while (rangeUnlinked.first != rangeUnlinked.second) {
4895  assert(rangeUnlinked.first->first == pindex->pprev);
4896  if (rangeUnlinked.first->second == pindex) {
4897  foundInUnlinked = true;
4898  break;
4899  }
4900  rangeUnlinked.first++;
4901  }
4902  if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4903  // If this block has block data available, some parent was never received, and has no invalid parents, it must be in m_blocks_unlinked.
4904  assert(foundInUnlinked);
4905  }
4906  if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in m_blocks_unlinked if we don't HAVE_DATA
4907  if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in m_blocks_unlinked.
4908  if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4909  // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4910  assert(fHavePruned); // We must have pruned.
4911  // This block may have entered m_blocks_unlinked if:
4912  // - it has a descendant that at some point had more work than the
4913  // tip, and
4914  // - we tried switching to that descendant but were missing
4915  // data for some intermediate block between m_chain and the
4916  // tip.
4917  // So if this block is itself better than m_chain.Tip() and it wasn't in
4918  // setBlockIndexCandidates, then it must be in m_blocks_unlinked.
4919  if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4920  if (pindexFirstInvalid == nullptr) {
4921  assert(foundInUnlinked);
4922  }
4923  }
4924  }
4925  // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4926  // End: actual consistency checks.
4927 
4928  // Try descending into the first subnode.
4929  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4930  if (range.first != range.second) {
4931  // A subnode was found.
4932  pindex = range.first->second;
4933  nHeight++;
4934  continue;
4935  }
4936  // This is a leaf node.
4937  // Move upwards until we reach a node of which we have not yet visited the last child.
4938  while (pindex) {
4939  // We are going to either move to a parent or a sibling of pindex.
4940  // If pindex was the first with a certain property, unset the corresponding variable.
4941  if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4942  if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4943  if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4944  if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4945  if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4946  if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4947  if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4948  // Find our parent.
4949  CBlockIndex* pindexPar = pindex->pprev;
4950  // Find which child we just visited.
4951  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4952  while (rangePar.first->second != pindex) {
4953  assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4954  rangePar.first++;
4955  }
4956  // Proceed to the next one.
4957  rangePar.first++;
4958  if (rangePar.first != rangePar.second) {
4959  // Move to the sibling.
4960  pindex = rangePar.first->second;
4961  break;
4962  } else {
4963  // Move up further.
4964  pindex = pindexPar;
4965  nHeight--;
4966  continue;
4967  }
4968  }
4969  }
4970 
4971  // Check that we actually traversed the entire map.
4972  assert(nNodes == forward.size());
4973 }
4974 
4975 std::string CChainState::ToString()
4976 {
4977  CBlockIndex* tip = m_chain.Tip();
4978  return strprintf("Chainstate [%s] @ height %d (%s)",
4979  m_from_snapshot_blockhash.IsNull() ? "ibd" : "snapshot",
4980  tip ? tip->nHeight : -1, tip ? tip->GetBlockHash().ToString() : "null");
4981 }
4982 
4983 bool CChainState::ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
4984 {
4985  if (coinstip_size == m_coinstip_cache_size_bytes &&
4986  coinsdb_size == m_coinsdb_cache_size_bytes) {
4987  // Cache sizes are unchanged, no need to continue.
4988  return true;
4989  }
4990  size_t old_coinstip_size = m_coinstip_cache_size_bytes;
4991  m_coinstip_cache_size_bytes = coinstip_size;
4992  m_coinsdb_cache_size_bytes = coinsdb_size;
4993  CoinsDB().ResizeCache(coinsdb_size);
4994 
4995  LogPrintf("[%s] resized coinsdb cache to %.1f MiB\n",
4996  this->ToString(), coinsdb_size * (1.0 / 1024 / 1024));
4997  LogPrintf("[%s] resized coinstip cache to %.1f MiB\n",
4998  this->ToString(), coinstip_size * (1.0 / 1024 / 1024));
4999 
5000  BlockValidationState state;
5001  const CChainParams& chainparams = Params();
5002 
5003  bool ret;
5004 
5005  if (coinstip_size > old_coinstip_size) {
5006  // Likely no need to flush if cache sizes have grown.
5007  ret = FlushStateToDisk(chainparams, state, FlushStateMode::IF_NEEDED);
5008  } else {
5009  // Otherwise, flush state to disk and deallocate the in-memory coins map.
5010  ret = FlushStateToDisk(chainparams, state, FlushStateMode::ALWAYS);
5012  }
5013  return ret;
5014 }
5015 
5016 std::string CBlockFileInfo::ToString() const
5017 {
5018  return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, FormatISO8601Date(nTimeFirst), FormatISO8601Date(nTimeLast));
5019 }
5020 
5022 {
5023  LOCK(cs_LastBlockFile);
5024 
5025  return &vinfoBlockFile.at(n);
5026 }
5027 
5029 {
5030  LOCK(cs_main);
5031  return VersionBitsState(::ChainActive().Tip(), params, pos, versionbitscache);
5032 }
5033 
5035 {
5036  LOCK(cs_main);
5037  return VersionBitsStatistics(::ChainActive().Tip(), params, pos);
5038 }
5039 
5041 {
5042  LOCK(cs_main);
5043  return VersionBitsStateSinceHeight(::ChainActive().Tip(), params, pos, versionbitscache);
5044 }
5045 
5046 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
5047 
5049 {
5050  const CChainParams& chainparams = Params();
5051  int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
5052  FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
5053  CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
5054  if (file.IsNull()) {
5055  LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
5056  return false;
5057  }
5058 
5059  int64_t count = 0;
5060  int64_t expired = 0;
5061  int64_t failed = 0;
5062  int64_t already_there = 0;
5063  int64_t unbroadcast = 0;
5064  int64_t nNow = GetTime();
5065 
5066  try {
5067  uint64_t version;
5068  file >> version;
5069  if (version != MEMPOOL_DUMP_VERSION) {
5070  return false;
5071  }
5072  uint64_t num;
5073  file >> num;
5074  while (num--) {
5075  CTransactionRef tx;
5076  int64_t nTime;
5077  int64_t nFeeDelta;
5078  file >> tx;
5079  file >> nTime;
5080  file >> nFeeDelta;
5081 
5082  CAmount amountdelta = nFeeDelta;
5083  if (amountdelta) {
5084  pool.PrioritiseTransaction(tx->GetHash(), amountdelta);
5085  }
5086  TxValidationState state;
5087  if (nTime > nNow - nExpiryTimeout) {
5088  LOCK(cs_main);
5089  AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, nTime,
5090  nullptr /* plTxnReplaced */, false /* bypass_limits */,
5091  false /* test_accept */);
5092  if (state.IsValid()) {
5093  ++count;
5094  } else {
5095  // mempool may contain the transaction already, e.g. from
5096  // wallet(s) having loaded it while we were processing
5097  // mempool transactions; consider these as valid, instead of
5098  // failed, but mark them as 'already there'
5099  if (pool.exists(tx->GetHash())) {
5100  ++already_there;
5101  } else {
5102  ++failed;
5103  }
5104  }
5105  } else {
5106  ++expired;
5107  }
5108  if (ShutdownRequested())
5109  return false;
5110  }
5111  std::map<uint256, CAmount> mapDeltas;
5112  file >> mapDeltas;
5113 
5114  for (const auto& i : mapDeltas) {
5115  pool.PrioritiseTransaction(i.first, i.second);
5116  }
5117 
5118  // TODO: remove this try except in v0.22
5119  std::set<uint256> unbroadcast_txids;
5120  try {
5121  file >> unbroadcast_txids;
5122  unbroadcast = unbroadcast_txids.size();
5123  } catch (const std::exception&) {
5124  // mempool.dat files created prior to v0.21 will not have an
5125  // unbroadcast set. No need to log a failure if parsing fails here.
5126  }
5127  for (const auto& txid : unbroadcast_txids) {
5128  // Ensure transactions were accepted to mempool then add to
5129  // unbroadcast set.
5130  if (pool.get(txid) != nullptr) pool.AddUnbroadcastTx(txid);
5131  }
5132  } catch (const std::exception& e) {
5133  LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
5134  return false;
5135  }
5136 
5137  LogPrintf("Imported mempool transactions from disk: %i succeeded, %i failed, %i expired, %i already there, %i waiting for initial broadcast\n", count, failed, expired, already_there, unbroadcast);
5138  return true;
5139 }
5140 
5141 bool DumpMempool(const CTxMemPool& pool)
5142 {
5143  int64_t start = GetTimeMicros();
5144 
5145  std::map<uint256, CAmount> mapDeltas;
5146  std::vector<TxMempoolInfo> vinfo;
5147  std::set<uint256> unbroadcast_txids;
5148 
5149  static Mutex dump_mutex;
5150  LOCK(dump_mutex);
5151 
5152  {
5153  LOCK(pool.cs);
5154  for (const auto &i : pool.mapDeltas) {
5155  mapDeltas[i.first] = i.second;
5156  }
5157  vinfo = pool.infoAll();
5158  unbroadcast_txids = pool.GetUnbroadcastTxs();
5159  }
5160 
5161  int64_t mid = GetTimeMicros();
5162 
5163  try {
5164  FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
5165  if (!filestr) {
5166  return false;
5167  }
5168 
5169  CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
5170 
5171  uint64_t version = MEMPOOL_DUMP_VERSION;
5172  file << version;
5173 
5174  file << (uint64_t)vinfo.size();
5175  for (const auto& i : vinfo) {
5176  file << *(i.tx);
5177  file << int64_t{count_seconds(i.m_time)};
5178  file << int64_t{i.nFeeDelta};
5179  mapDeltas.erase(i.tx->GetHash());
5180  }
5181 
5182  file << mapDeltas;
5183 
5184  LogPrintf("Writing %d unbroadcast transactions to disk.\n", unbroadcast_txids.size());
5185  file << unbroadcast_txids;
5186 
5187  if (!FileCommit(file.Get()))
5188  throw std::runtime_error("FileCommit failed");
5189  file.fclose();
5190  RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
5191  int64_t last = GetTimeMicros();
5192  LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
5193  } catch (const std::exception& e) {
5194  LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
5195  return false;
5196  }
5197  return true;
5198 }
5199 
5202 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex *pindex) {
5203  if (pindex == nullptr)
5204  return 0.0;
5205 
5206  int64_t nNow = time(nullptr);
5207 
5208  double fTxTotal;
5209 
5210  if (pindex->nChainTx <= data.nTxCount) {
5211  fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
5212  } else {
5213  fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
5214  }
5215 
5216  return std::min<double>(pindex->nChainTx / fTxTotal, 1.0);
5217 }
5218 
5220  if (m_active_chainstate != nullptr) {
5221  // If a snapshot chainstate exists, it will always be our active.
5223  }
5224  return {};
5225 }
5226 
5227 std::vector<CChainState*> ChainstateManager::GetAll()
5228 {
5229  std::vector<CChainState*> out;
5230 
5232  out.push_back(m_ibd_chainstate.get());
5233  }
5234 
5235  if (m_snapshot_chainstate) {
5236  out.push_back(m_snapshot_chainstate.get());
5237  }
5238 
5239  return out;
5240 }
5241 
5242 CChainState& ChainstateManager::InitializeChainstate(CTxMemPool& mempool, const uint256& snapshot_blockhash)
5243 {
5244  bool is_snapshot = !snapshot_blockhash.IsNull();
5245  std::unique_ptr<CChainState>& to_modify =
5246  is_snapshot ? m_snapshot_chainstate : m_ibd_chainstate;
5247 
5248  if (to_modify) {
5249  throw std::logic_error("should not be overwriting a chainstate");
5250  }
5251  to_modify.reset(new CChainState(mempool, m_blockman, snapshot_blockhash));
5252 
5253  // Snapshot chainstates and initial IBD chaintates always become active.
5254  if (is_snapshot || (!is_snapshot && !m_active_chainstate)) {
5255  LogPrintf("Switching active chainstate to %s\n", to_modify->ToString());
5256  m_active_chainstate = to_modify.get();
5257  } else {
5258  throw std::logic_error("unexpected chainstate activation");
5259  }
5260 
5261  return *to_modify;
5262 }
5263 
5265 {
5266  assert(m_active_chainstate);
5267  return *m_active_chainstate;
5268 }
5269 
5271 {
5273 }
5274 
5276 {
5278  return *m_snapshot_chainstate.get();
5279  }
5280  assert(m_ibd_chainstate);
5281  return *m_ibd_chainstate.get();
5282 }
5283 
5285 {
5286  return (m_snapshot_chainstate && chainstate == m_ibd_chainstate.get());
5287 }
5288 
5289 void ChainstateManager::Unload()
5290 {
5291  for (CChainState* chainstate : this->GetAll()) {
5292  chainstate->m_chain.SetTip(nullptr);
5293  chainstate->UnloadBlockIndex();
5294  }
5295 
5296  m_blockman.Unload();
5297 }
5298 
5299 void ChainstateManager::Reset()
5300 {
5301  m_ibd_chainstate.reset();
5302  m_snapshot_chainstate.reset();
5303  m_active_chainstate = nullptr;
5304  m_snapshot_validated = false;
5305 }
5306 
5307 void ChainstateManager::MaybeRebalanceCaches()
5308 {
5310  LogPrintf("[snapshot] allocating all cache to the IBD chainstate\n");
5311  // Allocate everything to the IBD chainstate.
5313  }
5314  else if (m_snapshot_chainstate && !m_ibd_chainstate) {
5315  LogPrintf("[snapshot] allocating all cache to the snapshot chainstate\n");
5316  // Allocate everything to the snapshot chainstate.
5318  }
5320  // If both chainstates exist, determine who needs more cache based on IBD status.
5321  //
5322  // Note: shrink caches first so that we don't inadvertently overwhelm available memory.
5323  if (m_snapshot_chainstate->IsInitialBlockDownload()) {
5324  m_ibd_chainstate->ResizeCoinsCaches(
5326  m_snapshot_chainstate->ResizeCoinsCaches(
5328  } else {
5329  m_snapshot_chainstate->ResizeCoinsCaches(
5331  m_ibd_chainstate->ResizeCoinsCaches(
5333  }
5334  }
5335 }
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:395
void UpdatedBlockTip(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:162
CAmount nValue
Definition: transaction.h:131
const Coin & AccessByTxid(const CCoinsViewCache &view, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:259
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block) ...
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:637
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:60
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition: validation.h:616
Display status of an in-progress BIP9 softfork.
Definition: versionbits.h:39
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 'checklevel'.
Definition: validation.cpp:77
std::vector< Coin > vprevout
Definition: undo.h:57
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:76
bool ShutdownRequested()
Definition: shutdown.cpp:20
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:184
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise pro...
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: validation.h:68
static const unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Definition: validation.cpp:68
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:23
CBlockIndex * FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Return the tip of the chain with the most work in it, that isn't known to be invalid (it's however fa...
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:159
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:62
bool PreciousBlock(BlockValidationState &state, const CChainParams &params, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
bool fPruneMode
True if we're running in -prune mode.
Definition: validation.cpp:139
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:147
bool FileCommit(FILE *file)
Definition: system.cpp:1038
bool LoadBlockIndex(const Consensus::Params &consensus_params, CBlockTreeDB &blocktree, std::set< CBlockIndex *, CBlockIndexWorkComparator > &block_index_candidates) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
static void FlushUndoFile(int block_file, bool finalize=false)
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
std::condition_variable g_best_block_cv
Definition: validation.cpp:133
uint256 BIP34Hash
Definition: params.h:63
static const uint32_t MAX_BIP125_RBF_SEQUENCE
Definition: rbf.h:12
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:145
bool Error(const std::string &reject_reason)
Definition: validation.h:112
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:106
CChainState * m_active_chainstate
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
Definition: validation.h:827
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
void Finalize(Span< unsigned char > output)
Definition: hash.h:30
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:573
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
#define LogPrint(category,...)
Definition: logging.h:182
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:579
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:24
int Threshold(const Consensus::Params &params) const override
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:114
double dTxRate
estimated number of transactions per second after that timestamp
Definition: chainparams.h:42
CScript scriptPubKey
Definition: transaction.h:132
descends from failed block
Definition: chain.h:126
std::string FormatISO8601Date(int64_t nTime)
Definition: time.cpp:94
bool IsError() const
Definition: validation.h:121
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:144
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
ThresholdState GetStateFor(const CBlockIndex *pindexPrev, const Consensus::Params &params, ThresholdConditionCache &cache) const
Returns the state for pindex A based on parent pindexPrev B.
Definition: versionbits.cpp:8
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:174
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:216
std::map< int, uint256 > MapCheckpoints
Definition: chainparams.h:22
static int64_t nTimeConnectTotal
void CheckBlockIndex(const Consensus::Params &consensusParams)
Make various assertions about the state of the block index.
void BlockDisconnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
void swap(CScriptCheck &check)
Definition: validation.h:270
A UTXO entry.
Definition: coins.h:30
Bilingual messages:
Definition: translation.h:16
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: validation.h:355
Definition: block.h:62
We don't have the previous block the checked one is built on.
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:60
static CBlockIndex * pindexBestForkBase
int64_t BeginTime(const Consensus::Params &params) const override
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
Definition: validation.cpp:113
The cache is at >= 90% capacity.
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE
Definition: sigcache.h:17
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:32
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
Definition: validation.cpp:70
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:781
bool IsValid() const
Definition: validation.h:119
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
bool LoadMempool(CTxMemPool &pool)
Load the mempool from disk.
std::string GetRejectReason() const
Definition: validation.h:123
static const uint64_t MEMPOOL_DUMP_VERSION
An in-memory indexed chain of blocks.
Definition: chain.h:379
bool VerifyDB(const CChainParams &chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
static void AlertNotify(const std::string &strMessage)
static const unsigned int MIN_STANDARD_TX_NONWITNESS_SIZE
The minimum non-witness size for transactions we're willing to relay/mine (1 segwit input + 1 P2WPKH ...
Definition: policy.h:26
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: txmempool.cpp:913
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:16
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:138
unsigned int nFlags
Definition: validation.h:258
static FILE * OpenUndoFile(const FlatFilePos &pos, bool fReadOnly=false)
Open an undo file (rev?????.dat)
std::atomic_bool fReindex(false)
reverse_range< T > reverse_iterate(T &x)
void SetMiscWarning(const bilingual_str &warning)
Definition: warnings.cpp:20
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:73
bool IsNull() const
Definition: flatfile.h:37
bool ReadRawBlockFromDisk(std::vector< uint8_t > &block, const FlatFilePos &pos, const CMessageHeader::MessageStartChars &message_start)
uint256 GetRandHash() noexcept
Definition: random.cpp:602
static void LogPrintf(const char *fmt, const Args &...args)
Definition: logging.h:166
int Period(const Consensus::Params &params) const override
invalid proof of work or time too old
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
std::vector< CTxIn > vin
Definition: transaction.h:355
bool Condition(const CBlockIndex *pindex, const Consensus::Params &params) const override
static const CAmount COIN
Definition: amount.h:14
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:102
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:40
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:129
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ChainActive().Tip() will not be pr...
Definition: validation.h:84
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:58
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:156
DisconnectResult
Definition: validation.h:326
transaction was missing some of its inputs
static CSHA256 g_scriptExecutionCacheHasher
unsigned int nHeight
int height
Definition: txmempool.h:42
static int64_t nTimeForks
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:101
bool exists(const GenTxid &gtxid) const
Definition: txmempool.h:736
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:26
bool DisconnectTip(BlockValidationState &state, const CChainParams &chainparams, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain's tip.
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:65
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:396
CTxOut out
unspent transaction output
Definition: coins.h:34
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name...
Definition: threadnames.cpp:57
std::string ToString() const
Definition: chain.h:273
#define expect(bit)
cache implements a cache with properties similar to a cuckoo-set.
Definition: cuckoocache.h:158
stage after last reached validness failed
Definition: chain.h:125
void clear()
Definition: txmempool.cpp:605
bool HasWitness() const
Definition: transaction.h:341
static constexpr size_t MINIMUM_WITNESS_COMMITMENT
Minimum size of a witness commitment structure.
Definition: validation.h:19
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:37
The coins cache is in immediate need of a flush.
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid...
Definition: chain.h:108
#define LOG_TIME_SECONDS(end_msg)
Definition: timer.h:98
CChainState stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:506
void ResizeCache(size_t new_cache_size) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Dynamically alter the underlying leveldb cache size.
Definition: txdb.cpp:48
static FlatFileSeq UndoFileSeq()
CBlockIndex * pindex
int BIP66Height
Block height at which BIP66 becomes active.
Definition: params.h:67
Optional< uint256 > SnapshotBlockhash() const
BIP9Stats VersionBitsTipStatistics(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the numerical statistics for the BIP9 state for a given deployment at the current tip...
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:814
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:232
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:147
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network) ...
bool IsSpent() const
Definition: coins.h:76
uint256 BlockWitnessMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:75
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:248
std::vector< CTxOut > m_spent_outputs
Definition: interpreter.h:163
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:582
bool empty() const
Definition: translation.h:27
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:81
static constexpr unsigned int STANDARD_NOT_MANDATORY_VERIFY_FLAGS
For convenience, standard but not mandatory verify flags.
Definition: policy.h:80
void addTransaction(const CTransactionRef &tx)
Definition: txmempool.h:958
static void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ActivateBestChainStep(BlockValidationState &state, const CChainParams &chainparams, 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.
FlatFilePos GetUndoPos() const
Definition: chain.h:211
ScriptError GetScriptError() const
Definition: validation.h:280
const fs::path & GetBlocksDir()
Definition: system.cpp:694
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:52
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:929
violated mempool's fee/size/descendant/RBF/etc limits
bool ConnectTip(BlockValidationState &state, const CChainParams &chainparams, 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.
uint32_t nTime
Definition: chain.h:179
ScriptError error
Definition: validation.h:260
inputs (covered by txid) failed policy rules
undo data available in rev*.dat
Definition: chain.h:122
bool eof() const
check whether we're at the end of the source file
Definition: streams.h:772
A hasher class for Bitcoin'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:25
uint32_t VersionBitsMask(const Consensus::Params &params, Consensus::DeploymentPos pos)
int nFile
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:153
FlatFilePos GetBlockPos() const
Definition: chain.h:202
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:477
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:12
transaction spends a coinbase too early, or violates locktime/sequence locks
static bool LoadBlockIndexDB(ChainstateManager &chainman, const CChainParams &chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
static constexpr int NO_WITNESS_COMMITMENT
Index marker for when no witness commitment is present in a coinbase transaction. ...
Definition: validation.h:16
int nFile
Definition: flatfile.h:16
std::atomic< bool > m_cached_finished_ibd
Whether this chainstate is undergoing initial block download.
Definition: validation.h:533
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Determine what nVersion a new block should use.
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: system.cpp:137
CChainState(CTxMemPool &mempool, BlockManager &blockman, uint256 from_snapshot_blockhash=uint256())
bool cacheStore
Definition: validation.h:259
int64_t nTime
UNIX timestamp of last known number of transactions.
Definition: chainparams.h:40
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 CheckSequenceLocks(const CTxMemPool &pool, const CTransaction &tx, int flags, LockPoints *lp, bool useExistingLockPoints)
Definition: validation.cpp:256
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
Definition: validation.cpp:143
bool IsCoinBase() const
Definition: coins.h:55
bool ConnectBlock(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, const CChainParams &chainparams, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of this block (with given index) on the UTXO set represented by coins...
unsigned char * begin()
Definition: uint256.h:58
static CBlockIndex * pindexBestForkTip
static constexpr unsigned int STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:58
int CSVHeight
Block height at which CSV (BIP68, BIP112 and BIP113) becomes active.
Definition: params.h:69
static void UpdateMempoolForReorg(CTxMemPool &mempool, DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
void ThreadScriptCheck(int worker_num)
Run an instance of the script checking thread.
unsigned int nHeightLast
highest height of block in file
Definition: chain.h:47
bool DumpMempool(const CTxMemPool &pool)
Dump the mempool to disk.
Reads data from an underlying stream, while hashing the read data.
Definition: hash.h:157
bool CheckInputScripts(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData &txdata, std::vector< CScriptCheck > *pvChecks=nullptr)
Check whether all of this transaction's input scripts succeed.
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block. ...
Definition: chain.h:171
CTxOut m_tx_out
Definition: validation.h:255
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:113
const std::vector< CTxIn > vin
Definition: transaction.h:276
ThresholdState VersionBitsTipState(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment at the current tip.
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size...
Definition: policy.cpp:195
FILE * Open(const FlatFilePos &pos, bool read_only=false)
Open a handle to the file at the given position.
Definition: flatfile.cpp:33
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:800
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1116
void TransactionAddedToMempool(const CTransactionRef &, uint64_t mempool_sequence)
uint256 g_best_block
Definition: validation.cpp:134
static bool WriteBlockToDisk(const CBlock &block, FlatFilePos &pos, const CMessageHeader::MessageStartChars &messageStart)
bool ActivateBestChain(BlockValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock) LOCKS_EXCLUDED(cs_main)
Make the best chain active, in multiple steps.
std::vector< COutPoint > vNoSpendsRemaining
Definition: validation.cpp:339
std::string GetDebugMessage() const
Definition: validation.h:124
std::string ToString() const
Definition: uint256.cpp:64
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:78
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
static feebumper::Result CheckFeeRate(const CWallet &wallet, const CWalletTx &wtx, const CFeeRate &newFeerate, const int64_t maxTxSize, std::vector< bilingual_str > &errors)
Check if the user provided a valid feeRate.
Definition: feebumper.cpp:61
int nSubsidyHalvingInterval
Definition: params.h:58
void LoadMempool(const ArgsManager &args)
Load the persisted mempool from disk.
bool RewindBlockIndex(const CChainParams &params) LOCKS_EXCLUDED(cs_main)
int64_t nTxCount
total number of transactions between genesis and that timestamp
Definition: chainparams.h:41
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:156
static bool ContextualCheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, const CChainParams &params, const CBlockIndex *pindexPrev, int64_t nAdjustedTime) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Context-dependent validity checks.
bool AcceptBlockHeader(const CBlockHeader &block, BlockValidationState &state, const CChainParams &chainparams, CBlockIndex **ppindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
If a block header hasn't already been seen, call CheckBlockHeader on it, ensure that it doesn't desce...
std::vector< uint256 > vHashUpdate
Definition: validation.cpp:374
static CuckooCache::cache< uint256, SignatureCacheHasher > g_scriptExecutionCache
void PruneAndFlush()
Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned...
bool AcceptToMemoryPool(CTxMemPool &pool, TxValidationState &state, const CTransactionRef &tx, std::list< CTransactionRef > *plTxnReplaced, bool bypass_limits, bool test_accept, CAmount *fee_out)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
Utility function to add all of a transaction's outputs to a cache.
Definition: coins.cpp:102
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:949
void fclose()
Definition: streams.h:625
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:151
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:14
RecursiveMutex m_cs_chainstate
the ChainState CriticalSection A lock that must be held when modifying this ChainState - held in Acti...
Definition: validation.h:525
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:35
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:71
CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:390
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:78
#define LOCK2(cs1, cs2)
Definition: sync.h:231
void SetfLargeWorkInvalidChainFound(bool flag)
Definition: warnings.cpp:38
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends...
Definition: chain.h:112
bool fCheckpointsEnabled
Definition: validation.cpp:142
int Height() const
Return the maximal height in the chain.
Definition: chain.h:415
bool error(const char *fmt, const Args &...args)
Definition: system.h:52
VersionBitsCache versionbitscache GUARDED_BY(cs_main)
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: chain.h:187
bool LoadBlockIndex(const CChainParams &chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex...
bool IsSnapshotValidated() const
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:879
static CBlockIndex * GetLastCheckpoint(const CCheckpointData &data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Returns last CBlockIndex* that is a checkpoint.
bool m_snapshot_validated
If true, the assumed-valid chainstate has been fully validated by the background validation chainstat...
Definition: validation.h:831
BIP 9 allows multiple softforks to be deployed in parallel.
Definition: versionbits.h:76
uint64_t PruneAfterHeight() const
Definition: chainparams.h:78
void AddUnbroadcastTx(const uint256 &txid)
Adds a transaction to the unbroadcast set.
Definition: txmempool.h:759
uint64_t nTimeFirst
earliest time of block in file
Definition: chain.h:48
bool CheckFinalTx(const CTransaction &tx, int flags)
Transaction validation functions.
Definition: validation.cpp:206
void ResetBlockFailureFlags(CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
static const 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: validation.cpp:64
double getdouble() const
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:407
bool Invalid(Result result, const std::string &reject_reason="", const std::string &debug_message="")
Definition: validation.h:102
int GetSpendHeight(const CCoinsViewCache &inputs)
Return the spend height, which is one more than the inputs.GetBestBlock().
int64_t count_seconds(std::chrono::seconds t)
Helper to count the seconds of a duration.
Definition: time.h:25
fs::path GetBlockPosFilename(const FlatFilePos &pos)
Translation to a filesystem path.
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:597
Access to the block database (blocks/index/)
Definition: txdb.h:96
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:115
Transaction might have a witness prior to SegWit activation, or witness may have been malleated (whic...
uint256 hashMerkleRoot
Definition: block.h:26
static int64_t nTimeChainState
Abstract view on the open txout dataset.
Definition: coins.h:180
static void LimitMempoolSize(CTxMemPool &pool, size_t limit, std::chrono::seconds age) EXCLUSIVE_LOCKS_REQUIRED(pool.cs
static int64_t nTimeTotal
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:149
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.cpp:131
unsigned int nDataPos
Byte offset within blk?????.dat where this block's data is stored.
Definition: chain.h:156
int64_t GetBlockTime() const
Definition: block.h:55
DeploymentPos
Definition: params.h:14
this block was cached as being invalid and we didn't store the reason why
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs, bool taproot_active)
Check transaction inputs to mitigate two potential denial-of-service attacks:
Definition: policy.cpp:158
void removeForBlock(const std::vector< CTransactionRef > &vtx)
Definition: txmempool.h:965
static constexpr unsigned int LOCKTIME_MEDIAN_TIME_PAST
Use GetMedianTimePast() instead of nTime for end point timestamp.
Definition: consensus.h:30
An input of a transaction.
Definition: transaction.h:65
CBlockIndex * InsertBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Create a new block index entry for a given block hash.
bool LoadGenesisBlock(const CChainParams &chainparams)
bool IsNull() const
Definition: uint256.h:31
int VersionBitsStateSinceHeight(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache)
#define LOCK(cs)
Definition: sync.h:230
The BlockPolicyEstimator is used for estimating the feerate needed for a transaction to be included i...
Definition: fees.h:124
static bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:17
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params &params)
Definition: pow.cpp:13
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:57
static CCheckQueue< CScriptCheck > scriptcheckqueue(128)
the block failed to meet one of our checkpoints
CChainState & ActiveChainstate() const
The most-work chain.
int BIP34Height
Block height and hash at which BIP34 becomes active.
Definition: params.h:62
size_t DynamicMemoryUsage() const
Definition: txmempool.h:954
AssertLockHeld(mempool.cs)
FlushStateMode
Definition: validation.h:336
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
uint256 uint256S(const char *str)
Definition: uint256.h:137
std::map< uint256, CAmount > mapDeltas
Definition: txmempool.h:601
int64_t nPowTargetSpacing
Definition: params.h:89
std::string ScriptErrorString(const ScriptError serror)
Abstract class that implements BIP9-style threshold logic, and caches results.
Definition: versionbits.h:55
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:720
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:56
uint256 hashPrevBlock
Definition: block.h:25
bool ActivateBestChain(BlockValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Find the best known block, and make it the tip of the block chain.
static bool CheckInputsFromMempoolAndCache(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const CTxMemPool &pool, unsigned int flags, PrecomputedTransactionData &txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:412
uint32_t n
Definition: transaction.h:30
Holds various statistics on transactions within a chain.
Definition: chainparams.h:39
static int64_t nTimeIndex
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha256.cpp:663
const std::vector< CTxOut > vout
Definition: transaction.h:277
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: validation.h:64
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:131
bool signet_blocks
If true, witness commitments contain a payload equal to a Bitcoin Script solution to the signet chall...
Definition: params.h:101
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:66
const ChainTxData & TxData() const
Definition: chainparams.h:93
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:82
CBlockIndex * AddToBlockIndex(const CBlockHeader &block) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool contains(const Element &e, const bool erase) const
contains iterates through the hash locations for a given element and checks to see if it is present...
Definition: cuckoocache.h:469
static void UpdateTip(CTxMemPool &mempool, const CBlockIndex *pindexNew, const CChainParams &chainParams) EXCLUSIVE_LOCKS_REQUIRED(
Check warning conditions and do some notifications on new chain tip set.
std::shared_ptr< const CBlock > pblock
constexpr auto AbortError
Definition: ui_interface.h:117
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
Definition: tx_verify.cpp:92
const uint256 m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from. ...
Definition: validation.h:580
static void LimitValidationInterfaceQueue() LOCKS_EXCLUDED(cs_main)
CMainSignals & GetMainSignals()
bool IsInvalid() const
Definition: validation.h:120
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:65
unsigned int nHeightFirst
lowest height of block in file
Definition: chain.h:46
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:116
int VersionBitsTipStateSinceHeight(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the block height at which the BIP9 deployment switched into the state for the block building on t...
bool TestLockPointValidity(const LockPoints *lp)
Test whether the LockPoints height and time are still valid on the current chain. ...
Definition: validation.cpp:238
bool operator()()
CChainState & ValidatedChainstate() const
Return the most-work chainstate that has been fully validated.
ChainstateManager g_chainman
Definition: validation.cpp:104
const CMessageHeader::MessageStartChars & MessageStart() const
Definition: chainparams.h:66
An output of a transaction.
Definition: transaction.h:128
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:51
static bool NotifyHeaderTip() LOCKS_EXCLUDED(cs_main)
void read(char *pch, size_t nSize)
Definition: streams.h:655
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:544
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:116
uint32_t nMinerConfirmationWindow
Definition: params.h:83
bool SetPos(uint64_t nPos)
rewind to a given reading position
Definition: streams.h:802
Queue for verifications that have to be performed.
Definition: checkqueue.h:30
Parameters that influence chain consensus.
Definition: params.h:56
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:74
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
const uint256 & GetWitnessHash() const
Definition: transaction.h:312
arith_uint256 nLastPreciousChainwork
chainwork for the last block that preciousblock has been applied to.
Definition: validation.h:519
std::pair< int, int64_t > CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector< int > &prevHeights, const CBlockIndex &block)
Calculates the block height and previous block's median time past at which the transaction will be co...
Definition: tx_verify.cpp:30
Mutex g_best_block_mutex
Definition: validation.cpp:132
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:144
256-bit unsigned big integer.
block data in blk*.data was received with a witness-enforcing client
Definition: chain.h:129
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:68
static int64_t nTimeCallbacks
CFeeRate incrementalRelayFee
Definition: settings.cpp:12
static int64_t nTimeCheck
void BlockConnected(CBlockIndex *pindex, std::shared_ptr< const CBlock > pblock)
static FlatFilePos SaveBlockToDisk(const CBlock &block, int nHeight, const CChainParams &chainparams, const FlatFilePos *dbp)
Store block on disk.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:146
unsigned char MessageStartChars[MESSAGE_START_SIZE]
Definition: protocol.h:38
static int64_t nTimeConnect
size_t Allocate(const FlatFilePos &pos, size_t add_size, bool &out_of_space)
Allocate additional space in a file after the given starting position.
Definition: flatfile.cpp:55
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:844
std::map< const CBlockIndex *, ThresholdState > ThresholdConditionCache
Definition: versionbits.h:36
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:647
Check if transaction will be BIP 68 final in the next block to be created.
Definition: validation.h:252
void insert(Element e)
insert loops at most depth_limit times trying to insert a hash at various locations in the table via ...
Definition: cuckoocache.h:392
int BIP65Height
Block height at which BIP65 becomes active.
Definition: params.h:65
static int64_t nTimeReadFromDisk
static bool CheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW=true)
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:401
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:31
void UnloadBlockIndex()
uint32_t setup_bytes(size_t bytes)
setup_bytes is a convenience function which accounts for internal memory usage when deciding how many...
Definition: cuckoocache.h:366
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:150
unsigned int nUndoPos
Byte offset within rev?????.dat where this block's undo data is stored.
Definition: chain.h:159
Transaction is missing a witness.
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:68
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, BlockValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:1008
static bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown=false)
int32_t nBlockSequenceId
Blocks loaded from disk are assigned id 0, so start the counter at 1.
Definition: validation.h:515
int flags
Definition: bitcoin-tx.cpp:506
int GetVersion() const
Definition: streams.h:653
void LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, FlatFilePos *dbp)
Import blocks from an external file.
static void DoWarning(const bilingual_str &warning)
uint256 GetHash()
Compute the double-SHA256 hash of all data written to this object.
Definition: hash.h:122
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:385
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:21
CBlockIndex * LookupBlockIndex(const uint256 &hash)
Definition: validation.cpp:173
int32_t nVersion
block header
Definition: chain.h:177
256-bit opaque blob.
Definition: uint256.h:124
bool fCheckBlockIndex
Definition: validation.cpp:141
invalid by consensus rules (excluding any below reasons)
CoinsCacheSizeState
Definition: validation.h:483
const CTransaction * ptxTo
Definition: validation.h:256
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
Definition: validation.cpp:135
DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view)
Undo the effects of this block (with given index) on the UTXO set represented by coins.
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
Definition: validation.cpp:106
static void FlushBlockFile(bool fFinalize=false, bool finalize_undo=false)
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:74
fs::path FileName(const FlatFilePos &pos) const
Get the name of the file at the given position.
Definition: flatfile.cpp:28
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
std::vector< CTransactionRef > vtx
Definition: block.h:66
void SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
Definition: chain.cpp:11
uint256 GetHash() const
Definition: block.cpp:11
bool IsBackgroundIBD(CChainState *chainstate) const
the block's data didn't match the data committed to by the PoW
Result GetResult() const
Definition: validation.h:122
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:488
void check(const CCoinsViewCache *pcoins) const
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
Definition: txmempool.cpp:620
bool fRequireStandard
Definition: validation.cpp:140
static const int64_t MAX_MAX_SIG_CACHE_SIZE
Definition: sigcache.h:19
int32_t nBlockReverseSequenceId
Decreasing counter (used by subsequent preciousblock calls).
Definition: validation.h:517
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition: validation.h:613
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
std::string original
Definition: translation.h:17
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
Definition: tx_verify.cpp:107
void FindByte(char ch)
search for a given byte in the stream, and remain positioned on it
Definition: streams.h:835
void SetNull()
Definition: block.h:88
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:137
const CBlock & GenesisBlock() const
Definition: chainparams.h:69
const CChainParams & Params()
Return the currently selected parameters.
static const int32_t VERSIONBITS_LAST_OLD_BLOCK_VERSION
What block version to use for new blocks (pre versionbits)
Definition: versionbits.h:12
Undo information for a CBlock.
Definition: undo.h:63
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
friend CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
Definition: validation.cpp:106
std::unique_ptr< CChainState > m_snapshot_chainstate
A chainstate initialized on the basis of a UTXO snapshot.
Definition: validation.h:814
uint32_t nSequence
Definition: transaction.h:70
Undo information for a CTransaction.
Definition: undo.h:53
std::atomic_bool fImporting(false)
void * memcpy(void *a, const void *b, size_t c)
std::vector< PerBlockConnectTrace > blocksConnected
std::vector< unsigned char > GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks...
bool GetfLargeWorkForkFound()
Definition: warnings.cpp:32
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
#define MILLI
Definition: validation.cpp:57
static void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:643
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:467
void InitScriptExecutionCache()
Initializes the script-execution cache.
static const int32_t VERSIONBITS_TOP_BITS
What bits to set in version for versionbits blocks.
Definition: versionbits.h:14
static bool IsScriptWitnessEnabled(const Consensus::Params &params)
bool m_spent_outputs_ready
Whether m_spent_outputs is initialized.
Definition: interpreter.h:165
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:223
A block this one builds on is invalid.
std::unique_ptr< CChainState > m_ibd_chainstate
The chainstate used under normal operation (i.e.
Definition: validation.h:801
static bool ContextualCheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
NOTE: This function is not currently invoked by ConnectBlock(), so we should consider upgrade issues ...
bool InvalidateBlock(BlockValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex)
Mark a block as invalid.
void PruneBlockFilesManual(int nManualPruneHeight)
Prune block files up to a given height.
std::set< uint256 > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
Definition: txmempool.h:771
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:180
int64_t GetAdjustedTime()
Definition: timedata.cpp:34
static void AppendWarning(bilingual_str &res, const bilingual_str &warn)
Private helper function that concatenates warning messages.
void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Clear all data members.
static FlatFileSeq BlockFileSeq()
static constexpr std::chrono::hours DATABASE_WRITE_INTERVAL
Time to wait between writing blocks/block index to disk.
Definition: validation.cpp:72
CChainState &InitializeChainstate(CTxMemPool &mempool, const uint256 &snapshot_blockhash=uint256()) EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * > GetAll()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
Definition: validation.h:861
void EraseBlockData(CBlockIndex *index) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as not having block data.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:402
bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const
Definition: validation.cpp:86
std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and a...
Definition: validation.h:587
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
static int64_t nTimeVerify
ArgsManager gArgs
Definition: system.cpp:77
static int64_t nTimePostConnect
std::string ToString() const
Definition: flatfile.cpp:23
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
unsigned int nBlocks
number of blocks stored in file
Definition: chain.h:43
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances...
Definition: validation.h:538
static constexpr uint64_t MAX_SIZE
The maximum size of a serialized object in bytes or number of elements (for eg vectors) when the size...
Definition: serialize.h:31
#define AssertLockNotHeld(cs)
Definition: sync.h:80
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:199
static const unsigned int MAX_STANDARD_TX_SIGOPS_COST
The maximum number of sigops we're willing to relay/mine in a single tx.
Definition: policy.h:30
std::string ToString() const
Definition: validation.h:125
static int count
Definition: tests.c:35
std::string ToString() const
bool RaiseValidity(enum BlockStatus nUpTo)
Raise the validity level of this block index entry.
Definition: chain.h:292
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:282
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Check whether witness commitments are required for a block, and whether to enforce NULLDUMMY (BIP 147...
bool InvalidateBlock(BlockValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
bool LoadBlockIndexGuts(const Consensus::Params &consensusParams, std::function< CBlockIndex *(const uint256 &)> insertBlockIndex)
Definition: txdb.cpp:246
void StartShutdown()
Definition: shutdown.cpp:12
int MinBIP9WarningHeight
Don't warn about unknown BIP 9 activations below this height.
Definition: params.h:76
static for(const COutPoint &removed:vNoSpendsRemaining) bool IsCurrentForFeeEstimation() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:345
bool IsCoinBase() const
Definition: transaction.h:324
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:590
A mutable version of CTransaction.
Definition: transaction.h:353
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:100
int64_t time
Definition: txmempool.h:43
CTxMemPool & m_mempool
mempool that is kept in sync with the chain
Definition: validation.h:541
uint32_t nRuleChangeActivationThreshold
Minimum blocks including miner confirmation of the total of 2016 blocks in a retargeting period...
Definition: params.h:82
const uint256 & GetHash() const
Definition: transaction.h:311
unsigned int nIn
Definition: validation.h:257
block timestamp was > 2 hours in the future (or our clock is bad)
bool IsSnapshotActive() const
static bool WriteUndoDataForBlock(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex *pindex, const CChainParams &chainparams)
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
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: validation.h:407
All validity bits.
Definition: chain.h:118
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
uint64_t nTimeLast
latest time of block in file
Definition: chain.h:49
int SegwitHeight
Block height at which Segwit (BIP141, BIP143 and BIP147) becomes active.
Definition: params.h:73
void Add(std::vector< T > &vChecks)
Definition: checkqueue.h:197
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:122
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
static bool AbortNode(const std::string &strMessage, bilingual_str user_message=bilingual_str())
Abort with a message.
static constexpr int64_t MAX_FUTURE_BLOCK_TIME
Maximum amount of time that a block timestamp is allowed to exceed the current network-adjusted time ...
Definition: chain.h:22
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip). ...
Definition: chain.cpp:23
CClientUIInterface uiInterface
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:259
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:150
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
WarningBitsConditionChecker(int bitIn)
bool SetLimit(uint64_t nPos=std::numeric_limits< uint64_t >::max())
prevent reading beyond a certain position no argument removes the limit
Definition: streams.h:820
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:848
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
Definition: checkqueue.h:17
#define MICRO
Definition: validation.cpp:56
BIP9Stats VersionBitsStatistics(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos)
static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE
Maximum kilobytes for transactions to store for processing during reorg.
Definition: validation.cpp:66
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:236
std::vector< PerBlockConnectTrace > & GetBlocksConnected()
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:111
bool fChecked
Definition: block.h:69
full block available in blk*.dat
Definition: chain.h:121
bool IsStandardTx(const CTransaction &tx, bool permit_bare_multisig, const CFeeRate &dust_relay_fee, std::string &reason)
Check for standard transaction types.
Definition: policy.cpp:76
#define LOG_TIME_MILLIS_WITH_CATEGORY(end_msg, log_category)
Definition: timer.h:96
void Init(const T &tx, std::vector< CTxOut > &&spent_outputs)
bool ReplayBlocks(const CChainParams &params)
Replay blocks that aren't fully applied to the database.
Non-refcounted RAII wrapper around a FILE* that implements a ring buffer to deserialize from...
Definition: streams.h:711
int64_t GetBlockTime() const
Definition: chain.h:247
int GetWitnessCommitmentIndex(const CBlock &block)
Compute at which vout of the block's coinbase transaction the witness commitment occurs, or -1 if not found.
Definition: validation.h:161
A hasher class for SHA-256.
Definition: sha256.h:13
uint64_t CalculateCurrentUsage()
BLOCK PRUNING CODE.
bool LoadChainTip(const CChainParams &chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update the chain tip based on database information, i.e.
void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew, const FlatFilePos &pos, const Consensus::Params &consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:25
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned (modify associated database entries)
auto it
Definition: validation.cpp:381
std::vector< CTxUndo > vtxundo
Definition: undo.h:66
static bool AcceptToMemoryPoolWithTime(const CChainParams &chainparams, CTxMemPool &pool, TxValidationState &state, const CTransactionRef &tx, int64_t nAcceptTime, std::list< CTransactionRef > *plTxnReplaced, bool bypass_limits, bool test_accept, CAmount *fee_out=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
(try to) add transaction to memory pool with a specified acceptance time
static SynchronizationState GetSynchronizationState(bool init)
void SetIsLoaded(bool loaded)
Sets the current loaded state.
Definition: txmempool.cpp:1113
static int64_t GetBlockWeight(const CBlock &block)
Definition: validation.h:150
COutPoint prevout
Definition: transaction.h:68
void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe, std::string leveldb_name="chainstate")
Initialize the CoinsViews UTXO set database management data structures.
bool PreciousBlock(BlockValidationState &state, const CChainParams &params, CBlockIndex *pindex)
Mark a block as precious and reorganize.
FlatFileSeq represents a sequence of numbered files storing raw data.
Definition: flatfile.h:46
ThresholdState VersionBitsState(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache)
void SetfLargeWorkForkFound(bool flag)
Definition: warnings.cpp:26
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:83
static const int32_t VERSIONBITS_NUM_BITS
Total bits available for versionbits.
Definition: versionbits.h:18
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
Definition: tx_check.cpp:10
CBlockIndex * maxInputBlock
Definition: txmempool.h:47
unsigned int nPos
Definition: flatfile.h:17
VersionBitsCache versionbitscache
int64_t GetMedianTimePast() const
Definition: chain.h:259
static int64_t nBlocksTotal
static bool UndoWriteToDisk(const CBlockUndo &blockundo, FlatFilePos &pos, const uint256 &hashBlock, const CMessageHeader::MessageStartChars &messageStart)
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:893
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, int flags)
Compute total signature operation cost of a transaction.
Definition: tx_verify.cpp:138
Tx already in mempool or conflicts with a tx in the chain (if it conflicts with another tx in mempool...
CTransactionRef GetTransaction(const CBlockIndex *const block_index, const CTxMemPool *const mempool, const uint256 &hash, const Consensus::Params &consensusParams, uint256 &hashBlock)
Return transaction from the block at block_index.
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs)
Called when a block is connected.
Definition: txmempool.cpp:564
void NewPoWValidBlock(const CBlockIndex *, const std::shared_ptr< const CBlock > &)
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
static int64_t nTimeFlush
void BlockChecked(const CBlock &, const BlockValidationState &)
static unsigned int GetBlockScriptFlags(const CBlockIndex *pindex, const Consensus::Params &chainparams)
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:834
CHash256 & Write(Span< const unsigned char > input)
Definition: hash.h:37
otherwise didn't meet our local policy rules
RecursiveMutex cs_nBlockSequenceId
Every received block is assigned a unique and increasing identifier, so we know which one to give pri...
Definition: validation.h:513
void removeEntry(indexed_disconnected_transactions::index< insertion_order >::type::iterator entry)
Definition: txmempool.h:981
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:166
bool AcceptBlock(const std::shared_ptr< const CBlock > &pblock, BlockValidationState &state, const CChainParams &chainparams, CBlockIndex **ppindex, bool fRequested, const FlatFilePos *dbp, bool *fNewBlock) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Store block on disk.
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
void BlockConnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
uint256 hashGenesisBlock
Definition: params.h:57
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness reserved value). ...
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:602
static constexpr std::chrono::hours DATABASE_FLUSH_INTERVAL
Time to wait between flushing chainstate to disk.
Definition: validation.cpp:74
void FindFilesToPrune(std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, bool is_ibd)
Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a us...
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
Definition: txmempool.h:576
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
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:137
uint256 GetBlockHash() const
Definition: chain.h:233
uint32_t nBits
Definition: block.h:28
static void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs, const CChainParams &params) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of a block on the utxo cache, ignoring that it may already have been applied...
LockPoints lp
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:38
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
bool CheckSignetBlockSolution(const CBlock &block, const Consensus::Params &consensusParams)
Extract signature and check whether a block has a valid solution.
Definition: signet.cpp:124
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:140
uint256 hash
Definition: transaction.h:29
uint64_t GetPos() const
return the current reading position
Definition: streams.h:797
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:141
bool HaveTxsDownloaded() const
Check whether this block's and all previous blocks' transactions have been downloaded (and stored to ...
Definition: chain.h:245
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:869
Threshold condition checker that triggers when unknown versionbits are seen on the network...