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