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