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