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