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