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