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