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