[tests] Add -blocknotify functional test
[bitcoinplatinum.git] / src / validation.cpp
blobe098de5d3daef8e680519b878ec35910ac7d1622
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "validation.h"
8 #include "arith_uint256.h"
9 #include "chain.h"
10 #include "chainparams.h"
11 #include "checkpoints.h"
12 #include "checkqueue.h"
13 #include "consensus/consensus.h"
14 #include "consensus/merkle.h"
15 #include "consensus/tx_verify.h"
16 #include "consensus/validation.h"
17 #include "cuckoocache.h"
18 #include "fs.h"
19 #include "hash.h"
20 #include "init.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 "timedata.h"
33 #include "tinyformat.h"
34 #include "txdb.h"
35 #include "txmempool.h"
36 #include "ui_interface.h"
37 #include "undo.h"
38 #include "util.h"
39 #include "utilmoneystr.h"
40 #include "utilstrencodings.h"
41 #include "validationinterface.h"
42 #include "versionbits.h"
43 #include "warnings.h"
45 #include <atomic>
46 #include <sstream>
48 #include <boost/algorithm/string/replace.hpp>
49 #include <boost/algorithm/string/join.hpp>
50 #include <boost/thread.hpp>
52 #if defined(NDEBUG)
53 # error "Bitcoin cannot be compiled without assertions."
54 #endif
56 #define MICRO 0.000001
57 #define MILLI 0.001
59 /**
60 * Global state
63 CCriticalSection cs_main;
65 BlockMap mapBlockIndex;
66 CChain chainActive;
67 CBlockIndex *pindexBestHeader = nullptr;
68 CWaitableCriticalSection csBestBlock;
69 CConditionVariable cvBlockChange;
70 int nScriptCheckThreads = 0;
71 std::atomic_bool fImporting(false);
72 std::atomic_bool fReindex(false);
73 bool fTxIndex = false;
74 bool fHavePruned = false;
75 bool fPruneMode = false;
76 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
77 bool fRequireStandard = true;
78 bool fCheckBlockIndex = false;
79 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
80 size_t nCoinCacheUsage = 5000 * 300;
81 uint64_t nPruneTarget = 0;
82 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
83 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
85 uint256 hashAssumeValid;
86 arith_uint256 nMinimumChainWork;
88 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
89 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
91 CBlockPolicyEstimator feeEstimator;
92 CTxMemPool mempool(&feeEstimator);
94 static void CheckBlockIndex(const Consensus::Params& consensusParams);
96 /** Constant stuff for coinbase transactions we create: */
97 CScript COINBASE_FLAGS;
99 const std::string strMessageMagic = "Bitcoin Signed Message:\n";
101 // Internal stuff
102 namespace {
104 struct CBlockIndexWorkComparator
106 bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
107 // First sort by most total work, ...
108 if (pa->nChainWork > pb->nChainWork) return false;
109 if (pa->nChainWork < pb->nChainWork) return true;
111 // ... then by earliest time received, ...
112 if (pa->nSequenceId < pb->nSequenceId) return false;
113 if (pa->nSequenceId > pb->nSequenceId) return true;
115 // Use pointer address as tie breaker (should only happen with blocks
116 // loaded from disk, as those all have id 0).
117 if (pa < pb) return false;
118 if (pa > pb) return true;
120 // Identical blocks.
121 return false;
125 CBlockIndex *pindexBestInvalid;
128 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
129 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
130 * missing the data for the block.
132 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
133 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
134 * Pruned nodes may have entries where B is missing data.
136 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
138 CCriticalSection cs_LastBlockFile;
139 std::vector<CBlockFileInfo> vinfoBlockFile;
140 int nLastBlockFile = 0;
141 /** Global flag to indicate we should check to see if there are
142 * block/undo files that should be deleted. Set on startup
143 * or if we allocate more file space when we're in prune mode
145 bool fCheckForPruning = false;
148 * Every received block is assigned a unique and increasing identifier, so we
149 * know which one to give priority in case of a fork.
151 CCriticalSection cs_nBlockSequenceId;
152 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
153 int32_t nBlockSequenceId = 1;
154 /** Decreasing counter (used by subsequent preciousblock calls). */
155 int32_t nBlockReverseSequenceId = -1;
156 /** chainwork for the last block that preciousblock has been applied to. */
157 arith_uint256 nLastPreciousChainwork = 0;
159 /** Dirty block index entries. */
160 std::set<CBlockIndex*> setDirtyBlockIndex;
162 /** Dirty block file entries. */
163 std::set<int> setDirtyFileInfo;
164 } // anon namespace
166 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
168 // Find the first block the caller has in the main chain
169 for (const uint256& hash : locator.vHave) {
170 BlockMap::iterator mi = mapBlockIndex.find(hash);
171 if (mi != mapBlockIndex.end())
173 CBlockIndex* pindex = (*mi).second;
174 if (chain.Contains(pindex))
175 return pindex;
176 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
177 return chain.Tip();
181 return chain.Genesis();
184 CCoinsViewDB *pcoinsdbview = nullptr;
185 CCoinsViewCache *pcoinsTip = nullptr;
186 CBlockTreeDB *pblocktree = nullptr;
188 enum FlushStateMode {
189 FLUSH_STATE_NONE,
190 FLUSH_STATE_IF_NEEDED,
191 FLUSH_STATE_PERIODIC,
192 FLUSH_STATE_ALWAYS
195 // See definition for documentation
196 static bool FlushStateToDisk(const CChainParams& chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
197 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
198 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
199 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);
200 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
202 bool CheckFinalTx(const CTransaction &tx, int flags)
204 AssertLockHeld(cs_main);
206 // By convention a negative value for flags indicates that the
207 // current network-enforced consensus rules should be used. In
208 // a future soft-fork scenario that would mean checking which
209 // rules would be enforced for the next block and setting the
210 // appropriate flags. At the present time no soft-forks are
211 // scheduled, so no flags are set.
212 flags = std::max(flags, 0);
214 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
215 // nLockTime because when IsFinalTx() is called within
216 // CBlock::AcceptBlock(), the height of the block *being*
217 // evaluated is what is used. Thus if we want to know if a
218 // transaction can be part of the *next* block, we need to call
219 // IsFinalTx() with one more than chainActive.Height().
220 const int nBlockHeight = chainActive.Height() + 1;
222 // BIP113 requires that time-locked transactions have nLockTime set to
223 // less than the median time of the previous block they're contained in.
224 // When the next block is created its previous block will be the current
225 // chain tip, so we use that to calculate the median time passed to
226 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
227 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
228 ? chainActive.Tip()->GetMedianTimePast()
229 : GetAdjustedTime();
231 return IsFinalTx(tx, nBlockHeight, nBlockTime);
234 bool TestLockPointValidity(const LockPoints* lp)
236 AssertLockHeld(cs_main);
237 assert(lp);
238 // If there are relative lock times then the maxInputBlock will be set
239 // If there are no relative lock times, the LockPoints don't depend on the chain
240 if (lp->maxInputBlock) {
241 // Check whether chainActive is an extension of the block at which the LockPoints
242 // calculation was valid. If not LockPoints are no longer valid
243 if (!chainActive.Contains(lp->maxInputBlock)) {
244 return false;
248 // LockPoints still valid
249 return true;
252 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
254 AssertLockHeld(cs_main);
255 AssertLockHeld(mempool.cs);
257 CBlockIndex* tip = chainActive.Tip();
258 assert(tip != nullptr);
260 CBlockIndex index;
261 index.pprev = tip;
262 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
263 // height based locks because when SequenceLocks() is called within
264 // ConnectBlock(), the height of the block *being*
265 // evaluated is what is used.
266 // Thus if we want to know if a transaction can be part of the
267 // *next* block, we need to use one more than chainActive.Height()
268 index.nHeight = tip->nHeight + 1;
270 std::pair<int, int64_t> lockPair;
271 if (useExistingLockPoints) {
272 assert(lp);
273 lockPair.first = lp->height;
274 lockPair.second = lp->time;
276 else {
277 // pcoinsTip contains the UTXO set for chainActive.Tip()
278 CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
279 std::vector<int> prevheights;
280 prevheights.resize(tx.vin.size());
281 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
282 const CTxIn& txin = tx.vin[txinIndex];
283 Coin coin;
284 if (!viewMemPool.GetCoin(txin.prevout, coin)) {
285 return error("%s: Missing input", __func__);
287 if (coin.nHeight == MEMPOOL_HEIGHT) {
288 // Assume all mempool transaction confirm in the next block
289 prevheights[txinIndex] = tip->nHeight + 1;
290 } else {
291 prevheights[txinIndex] = coin.nHeight;
294 lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
295 if (lp) {
296 lp->height = lockPair.first;
297 lp->time = lockPair.second;
298 // Also store the hash of the block with the highest height of
299 // all the blocks which have sequence locked prevouts.
300 // This hash needs to still be on the chain
301 // for these LockPoint calculations to be valid
302 // Note: It is impossible to correctly calculate a maxInputBlock
303 // if any of the sequence locked inputs depend on unconfirmed txs,
304 // except in the special case where the relative lock time/height
305 // is 0, which is equivalent to no sequence lock. Since we assume
306 // input height of tip+1 for mempool txs and test the resulting
307 // lockPair from CalculateSequenceLocks against tip+1. We know
308 // EvaluateSequenceLocks will fail if there was a non-zero sequence
309 // lock on a mempool input, so we can use the return value of
310 // CheckSequenceLocks to indicate the LockPoints validity
311 int maxInputHeight = 0;
312 for (int height : prevheights) {
313 // Can ignore mempool inputs since we'll fail if they had non-zero locks
314 if (height != tip->nHeight+1) {
315 maxInputHeight = std::max(maxInputHeight, height);
318 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
321 return EvaluateSequenceLocks(index, lockPair);
324 // Returns the script flags which should be checked for a given block
325 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
327 static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
328 int expired = pool.Expire(GetTime() - age);
329 if (expired != 0) {
330 LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
333 std::vector<COutPoint> vNoSpendsRemaining;
334 pool.TrimToSize(limit, &vNoSpendsRemaining);
335 for (const COutPoint& removed : vNoSpendsRemaining)
336 pcoinsTip->Uncache(removed);
339 /** Convert CValidationState to a human-readable message for logging */
340 std::string FormatStateMessage(const CValidationState &state)
342 return strprintf("%s%s (code %i)",
343 state.GetRejectReason(),
344 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
345 state.GetRejectCode());
348 static bool IsCurrentForFeeEstimation()
350 AssertLockHeld(cs_main);
351 if (IsInitialBlockDownload())
352 return false;
353 if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
354 return false;
355 if (chainActive.Height() < pindexBestHeader->nHeight - 1)
356 return false;
357 return true;
360 /* Make mempool consistent after a reorg, by re-adding or recursively erasing
361 * disconnected block transactions from the mempool, and also removing any
362 * other transactions from the mempool that are no longer valid given the new
363 * tip/height.
365 * Note: we assume that disconnectpool only contains transactions that are NOT
366 * confirmed in the current chain nor already in the mempool (otherwise,
367 * in-mempool descendants of such transactions would be removed).
369 * Passing fAddToMempool=false will skip trying to add the transactions back,
370 * and instead just erase from the mempool as needed.
373 void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
375 AssertLockHeld(cs_main);
376 std::vector<uint256> vHashUpdate;
377 // disconnectpool's insertion_order index sorts the entries from
378 // oldest to newest, but the oldest entry will be the last tx from the
379 // latest mined block that was disconnected.
380 // Iterate disconnectpool in reverse, so that we add transactions
381 // back to the mempool starting with the earliest transaction that had
382 // been previously seen in a block.
383 auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
384 while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
385 // ignore validation errors in resurrected transactions
386 CValidationState stateDummy;
387 if (!fAddToMempool || (*it)->IsCoinBase() ||
388 !AcceptToMemoryPool(mempool, stateDummy, *it, nullptr /* pfMissingInputs */,
389 nullptr /* plTxnReplaced */, true /* bypass_limits */, 0 /* nAbsurdFee */)) {
390 // If the transaction doesn't make it in to the mempool, remove any
391 // transactions that depend on it (which would now be orphans).
392 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
393 } else if (mempool.exists((*it)->GetHash())) {
394 vHashUpdate.push_back((*it)->GetHash());
396 ++it;
398 disconnectpool.queuedTx.clear();
399 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
400 // no in-mempool children, which is generally not true when adding
401 // previously-confirmed transactions back to the mempool.
402 // UpdateTransactionsFromBlock finds descendants of any transactions in
403 // the disconnectpool that were added back and cleans up the mempool state.
404 mempool.UpdateTransactionsFromBlock(vHashUpdate);
406 // We also need to remove any now-immature transactions
407 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
408 // Re-limit mempool size, in case we added any transactions
409 LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
412 // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
413 // were somehow broken and returning the wrong scriptPubKeys
414 static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool& pool,
415 unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) {
416 AssertLockHeld(cs_main);
418 // pool.cs should be locked already, but go ahead and re-take the lock here
419 // to enforce that mempool doesn't change between when we check the view
420 // and when we actually call through to CheckInputs
421 LOCK(pool.cs);
423 assert(!tx.IsCoinBase());
424 for (const CTxIn& txin : tx.vin) {
425 const Coin& coin = view.AccessCoin(txin.prevout);
427 // At this point we haven't actually checked if the coins are all
428 // available (or shouldn't assume we have, since CheckInputs does).
429 // So we just return failure if the inputs are not available here,
430 // and then only have to check equivalence for available inputs.
431 if (coin.IsSpent()) return false;
433 const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
434 if (txFrom) {
435 assert(txFrom->GetHash() == txin.prevout.hash);
436 assert(txFrom->vout.size() > txin.prevout.n);
437 assert(txFrom->vout[txin.prevout.n] == coin.out);
438 } else {
439 const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout);
440 assert(!coinFromDisk.IsSpent());
441 assert(coinFromDisk.out == coin.out);
445 return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata);
448 static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx,
449 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
450 bool bypass_limits, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache)
452 const CTransaction& tx = *ptx;
453 const uint256 hash = tx.GetHash();
454 AssertLockHeld(cs_main);
455 if (pfMissingInputs)
456 *pfMissingInputs = false;
458 if (!CheckTransaction(tx, state))
459 return false; // state filled in by CheckTransaction
461 // Coinbase is only valid in a block, not as a loose transaction
462 if (tx.IsCoinBase())
463 return state.DoS(100, false, REJECT_INVALID, "coinbase");
465 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
466 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), chainparams.GetConsensus());
467 if (!gArgs.GetBoolArg("-prematurewitness", false) && tx.HasWitness() && !witnessEnabled) {
468 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
471 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
472 std::string reason;
473 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
474 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
476 // Only accept nLockTime-using transactions that can be mined in the next
477 // block; we don't want our mempool filled up with transactions that can't
478 // be mined yet.
479 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
480 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
482 // is it already in the memory pool?
483 if (pool.exists(hash)) {
484 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool");
487 // Check for conflicts with in-memory transactions
488 std::set<uint256> setConflicts;
490 LOCK(pool.cs); // protect pool.mapNextTx
491 for (const CTxIn &txin : tx.vin)
493 auto itConflicting = pool.mapNextTx.find(txin.prevout);
494 if (itConflicting != pool.mapNextTx.end())
496 const CTransaction *ptxConflicting = itConflicting->second;
497 if (!setConflicts.count(ptxConflicting->GetHash()))
499 // Allow opt-out of transaction replacement by setting
500 // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
502 // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
503 // non-replaceable transactions. All inputs rather than just one
504 // is for the sake of multi-party protocols, where we don't
505 // want a single party to be able to disable replacement.
507 // The opt-out ignores descendants as anyone relying on
508 // first-seen mempool behavior should be checking all
509 // unconfirmed ancestors anyway; doing otherwise is hopelessly
510 // insecure.
511 bool fReplacementOptOut = true;
512 if (fEnableReplacement)
514 for (const CTxIn &_txin : ptxConflicting->vin)
516 if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
518 fReplacementOptOut = false;
519 break;
523 if (fReplacementOptOut) {
524 return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict");
527 setConflicts.insert(ptxConflicting->GetHash());
534 CCoinsView dummy;
535 CCoinsViewCache view(&dummy);
537 CAmount nValueIn = 0;
538 LockPoints lp;
540 LOCK(pool.cs);
541 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
542 view.SetBackend(viewMemPool);
544 // do all inputs exist?
545 for (const CTxIn txin : tx.vin) {
546 if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
547 coins_to_uncache.push_back(txin.prevout);
549 if (!view.HaveCoin(txin.prevout)) {
550 // Are inputs missing because we already have the tx?
551 for (size_t out = 0; out < tx.vout.size(); out++) {
552 // Optimistically just do efficient check of cache for outputs
553 if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
554 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
557 // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
558 if (pfMissingInputs) {
559 *pfMissingInputs = true;
561 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
565 // Bring the best block into scope
566 view.GetBestBlock();
568 nValueIn = view.GetValueIn(tx);
570 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
571 view.SetBackend(dummy);
573 // Only accept BIP68 sequence locked transactions that can be mined in the next
574 // block; we don't want our mempool filled up with transactions that can't
575 // be mined yet.
576 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
577 // CoinsViewCache instead of create its own
578 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
579 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
582 // Check for non-standard pay-to-script-hash in inputs
583 if (fRequireStandard && !AreInputsStandard(tx, view))
584 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
586 // Check for non-standard witness in P2WSH
587 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
588 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
590 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
592 CAmount nValueOut = tx.GetValueOut();
593 CAmount nFees = nValueIn-nValueOut;
594 // nModifiedFees includes any fee deltas from PrioritiseTransaction
595 CAmount nModifiedFees = nFees;
596 pool.ApplyDelta(hash, nModifiedFees);
598 // Keep track of transactions that spend a coinbase, which we re-scan
599 // during reorgs to ensure COINBASE_MATURITY is still met.
600 bool fSpendsCoinbase = false;
601 for (const CTxIn &txin : tx.vin) {
602 const Coin &coin = view.AccessCoin(txin.prevout);
603 if (coin.IsCoinBase()) {
604 fSpendsCoinbase = true;
605 break;
609 CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
610 fSpendsCoinbase, nSigOpsCost, lp);
611 unsigned int nSize = entry.GetTxSize();
613 // Check that the transaction doesn't have an excessive number of
614 // sigops, making it impossible to mine. Since the coinbase transaction
615 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
616 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
617 // merely non-standard transaction.
618 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
619 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
620 strprintf("%d", nSigOpsCost));
622 CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
623 if (!bypass_limits && mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
624 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
627 // No transactions are allowed below minRelayTxFee except from disconnected blocks
628 if (!bypass_limits && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
629 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
632 if (nAbsurdFee && nFees > nAbsurdFee)
633 return state.Invalid(false,
634 REJECT_HIGHFEE, "absurdly-high-fee",
635 strprintf("%d > %d", nFees, nAbsurdFee));
637 // Calculate in-mempool ancestors, up to a limit.
638 CTxMemPool::setEntries setAncestors;
639 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
640 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
641 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
642 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
643 std::string errString;
644 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
645 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
648 // A transaction that spends outputs that would be replaced by it is invalid. Now
649 // that we have the set of all ancestors we can detect this
650 // pathological case by making sure setConflicts and setAncestors don't
651 // intersect.
652 for (CTxMemPool::txiter ancestorIt : setAncestors)
654 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
655 if (setConflicts.count(hashAncestor))
657 return state.DoS(10, false,
658 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
659 strprintf("%s spends conflicting transaction %s",
660 hash.ToString(),
661 hashAncestor.ToString()));
665 // Check if it's economically rational to mine this transaction rather
666 // than the ones it replaces.
667 CAmount nConflictingFees = 0;
668 size_t nConflictingSize = 0;
669 uint64_t nConflictingCount = 0;
670 CTxMemPool::setEntries allConflicting;
672 // If we don't hold the lock allConflicting might be incomplete; the
673 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
674 // mempool consistency for us.
675 LOCK(pool.cs);
676 const bool fReplacementTransaction = setConflicts.size();
677 if (fReplacementTransaction)
679 CFeeRate newFeeRate(nModifiedFees, nSize);
680 std::set<uint256> setConflictsParents;
681 const int maxDescendantsToVisit = 100;
682 CTxMemPool::setEntries setIterConflicting;
683 for (const uint256 &hashConflicting : setConflicts)
685 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
686 if (mi == pool.mapTx.end())
687 continue;
689 // Save these to avoid repeated lookups
690 setIterConflicting.insert(mi);
692 // Don't allow the replacement to reduce the feerate of the
693 // mempool.
695 // We usually don't want to accept replacements with lower
696 // feerates than what they replaced as that would lower the
697 // feerate of the next block. Requiring that the feerate always
698 // be increased is also an easy-to-reason about way to prevent
699 // DoS attacks via replacements.
701 // The mining code doesn't (currently) take children into
702 // account (CPFP) so we only consider the feerates of
703 // transactions being directly replaced, not their indirect
704 // descendants. While that does mean high feerate children are
705 // ignored when deciding whether or not to replace, we do
706 // require the replacement to pay more overall fees too,
707 // mitigating most cases.
708 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
709 if (newFeeRate <= oldFeeRate)
711 return state.DoS(0, false,
712 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
713 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
714 hash.ToString(),
715 newFeeRate.ToString(),
716 oldFeeRate.ToString()));
719 for (const CTxIn &txin : mi->GetTx().vin)
721 setConflictsParents.insert(txin.prevout.hash);
724 nConflictingCount += mi->GetCountWithDescendants();
726 // This potentially overestimates the number of actual descendants
727 // but we just want to be conservative to avoid doing too much
728 // work.
729 if (nConflictingCount <= maxDescendantsToVisit) {
730 // If not too many to replace, then calculate the set of
731 // transactions that would have to be evicted
732 for (CTxMemPool::txiter it : setIterConflicting) {
733 pool.CalculateDescendants(it, allConflicting);
735 for (CTxMemPool::txiter it : allConflicting) {
736 nConflictingFees += it->GetModifiedFee();
737 nConflictingSize += it->GetTxSize();
739 } else {
740 return state.DoS(0, false,
741 REJECT_NONSTANDARD, "too many potential replacements", false,
742 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
743 hash.ToString(),
744 nConflictingCount,
745 maxDescendantsToVisit));
748 for (unsigned int j = 0; j < tx.vin.size(); j++)
750 // We don't want to accept replacements that require low
751 // feerate junk to be mined first. Ideally we'd keep track of
752 // the ancestor feerates and make the decision based on that,
753 // but for now requiring all new inputs to be confirmed works.
754 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
756 // Rather than check the UTXO set - potentially expensive -
757 // it's cheaper to just check if the new input refers to a
758 // tx that's in the mempool.
759 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
760 return state.DoS(0, false,
761 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
762 strprintf("replacement %s adds unconfirmed input, idx %d",
763 hash.ToString(), j));
767 // The replacement must pay greater fees than the transactions it
768 // replaces - if we did the bandwidth used by those conflicting
769 // transactions would not be paid for.
770 if (nModifiedFees < nConflictingFees)
772 return state.DoS(0, false,
773 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
774 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
775 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
778 // Finally in addition to paying more fees than the conflicts the
779 // new transaction must pay for its own bandwidth.
780 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
781 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
783 return state.DoS(0, false,
784 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
785 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
786 hash.ToString(),
787 FormatMoney(nDeltaFees),
788 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
792 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
793 if (!chainparams.RequireStandard()) {
794 scriptVerifyFlags = gArgs.GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
797 // Check against previous transactions
798 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
799 PrecomputedTransactionData txdata(tx);
800 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, txdata)) {
801 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
802 // need to turn both off, and compare against just turning off CLEANSTACK
803 // to see if the failure is specifically due to witness validation.
804 CValidationState stateDummy; // Want reported failures to be from first CheckInputs
805 if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
806 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
807 // Only the witness is missing, so the transaction itself may be fine.
808 state.SetCorruptionPossible();
810 return false; // state filled in by CheckInputs
813 // Check again against the current block tip's script verification
814 // flags to cache our script execution flags. This is, of course,
815 // useless if the next block has different script flags from the
816 // previous one, but because the cache tracks script flags for us it
817 // will auto-invalidate and we'll just have a few blocks of extra
818 // misses on soft-fork activation.
820 // This is also useful in case of bugs in the standard flags that cause
821 // transactions to pass as valid when they're actually invalid. For
822 // instance the STRICTENC flag was incorrectly allowing certain
823 // CHECKSIG NOT scripts to pass, even though they were invalid.
825 // There is a similar check in CreateNewBlock() to prevent creating
826 // invalid blocks (using TestBlockValidity), however allowing such
827 // transactions into the mempool can be exploited as a DoS attack.
828 unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus());
829 if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata))
831 // If we're using promiscuousmempoolflags, we may hit this normally
832 // Check if current block has some flags that scriptVerifyFlags
833 // does not before printing an ominous warning
834 if (!(~scriptVerifyFlags & currentBlockScriptVerifyFlags)) {
835 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against latest-block but not STANDARD flags %s, %s",
836 __func__, hash.ToString(), FormatStateMessage(state));
837 } else {
838 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, false, txdata)) {
839 return error("%s: ConnectInputs failed against MANDATORY but not STANDARD flags due to promiscuous mempool %s, %s",
840 __func__, hash.ToString(), FormatStateMessage(state));
841 } else {
842 LogPrintf("Warning: -promiscuousmempool flags set to not include currently enforced soft forks, this may break mining or otherwise cause instability!\n");
847 // Remove conflicting transactions from the mempool
848 for (const CTxMemPool::txiter it : allConflicting)
850 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
851 it->GetTx().GetHash().ToString(),
852 hash.ToString(),
853 FormatMoney(nModifiedFees - nConflictingFees),
854 (int)nSize - (int)nConflictingSize);
855 if (plTxnReplaced)
856 plTxnReplaced->push_back(it->GetSharedTx());
858 pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
860 // This transaction should only count for fee estimation if:
861 // - it isn't a BIP 125 replacement transaction (may not be widely supported)
862 // - it's not being readded during a reorg which bypasses typical mempool fee limits
863 // - the node is not behind
864 // - the transaction is not dependent on any other transactions in the mempool
865 bool validForFeeEstimation = !fReplacementTransaction && !bypass_limits && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
867 // Store transaction in memory
868 pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
870 // trim mempool and check if tx was trimmed
871 if (!bypass_limits) {
872 LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
873 if (!pool.exists(hash))
874 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
878 GetMainSignals().TransactionAddedToMempool(ptx);
880 return true;
883 /** (try to) add transaction to memory pool with a specified acceptance time **/
884 static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
885 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
886 bool bypass_limits, const CAmount nAbsurdFee)
888 std::vector<COutPoint> coins_to_uncache;
889 bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, pfMissingInputs, nAcceptTime, plTxnReplaced, bypass_limits, nAbsurdFee, coins_to_uncache);
890 if (!res) {
891 for (const COutPoint& hashTx : coins_to_uncache)
892 pcoinsTip->Uncache(hashTx);
894 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
895 CValidationState stateDummy;
896 FlushStateToDisk(chainparams, stateDummy, FLUSH_STATE_PERIODIC);
897 return res;
900 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
901 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
902 bool bypass_limits, const CAmount nAbsurdFee)
904 const CChainParams& chainparams = Params();
905 return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, pfMissingInputs, GetTime(), plTxnReplaced, bypass_limits, nAbsurdFee);
908 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
909 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
911 CBlockIndex *pindexSlow = nullptr;
913 LOCK(cs_main);
915 CTransactionRef ptx = mempool.get(hash);
916 if (ptx)
918 txOut = ptx;
919 return true;
922 if (fTxIndex) {
923 CDiskTxPos postx;
924 if (pblocktree->ReadTxIndex(hash, postx)) {
925 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
926 if (file.IsNull())
927 return error("%s: OpenBlockFile failed", __func__);
928 CBlockHeader header;
929 try {
930 file >> header;
931 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
932 file >> txOut;
933 } catch (const std::exception& e) {
934 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
936 hashBlock = header.GetHash();
937 if (txOut->GetHash() != hash)
938 return error("%s: txid mismatch", __func__);
939 return true;
943 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
944 const Coin& coin = AccessByTxid(*pcoinsTip, hash);
945 if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
948 if (pindexSlow) {
949 CBlock block;
950 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
951 for (const auto& tx : block.vtx) {
952 if (tx->GetHash() == hash) {
953 txOut = tx;
954 hashBlock = pindexSlow->GetBlockHash();
955 return true;
961 return false;
969 //////////////////////////////////////////////////////////////////////////////
971 // CBlock and CBlockIndex
974 static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
976 // Open history file to append
977 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
978 if (fileout.IsNull())
979 return error("WriteBlockToDisk: OpenBlockFile failed");
981 // Write index header
982 unsigned int nSize = GetSerializeSize(fileout, block);
983 fileout << FLATDATA(messageStart) << nSize;
985 // Write block
986 long fileOutPos = ftell(fileout.Get());
987 if (fileOutPos < 0)
988 return error("WriteBlockToDisk: ftell failed");
989 pos.nPos = (unsigned int)fileOutPos;
990 fileout << block;
992 return true;
995 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
997 block.SetNull();
999 // Open history file to read
1000 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1001 if (filein.IsNull())
1002 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1004 // Read block
1005 try {
1006 filein >> block;
1008 catch (const std::exception& e) {
1009 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1012 // Check the header
1013 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1014 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1016 return true;
1019 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1021 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1022 return false;
1023 if (block.GetHash() != pindex->GetBlockHash())
1024 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1025 pindex->ToString(), pindex->GetBlockPos().ToString());
1026 return true;
1029 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1031 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1032 // Force block reward to zero when right shift is undefined.
1033 if (halvings >= 64)
1034 return 0;
1036 CAmount nSubsidy = 50 * COIN;
1037 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1038 nSubsidy >>= halvings;
1039 return nSubsidy;
1042 bool IsInitialBlockDownload()
1044 // Once this function has returned false, it must remain false.
1045 static std::atomic<bool> latchToFalse{false};
1046 // Optimization: pre-test latch before taking the lock.
1047 if (latchToFalse.load(std::memory_order_relaxed))
1048 return false;
1050 LOCK(cs_main);
1051 if (latchToFalse.load(std::memory_order_relaxed))
1052 return false;
1053 if (fImporting || fReindex)
1054 return true;
1055 if (chainActive.Tip() == nullptr)
1056 return true;
1057 if (chainActive.Tip()->nChainWork < nMinimumChainWork)
1058 return true;
1059 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1060 return true;
1061 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1062 latchToFalse.store(true, std::memory_order_relaxed);
1063 return false;
1066 CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
1068 static void AlertNotify(const std::string& strMessage)
1070 uiInterface.NotifyAlertChanged();
1071 std::string strCmd = gArgs.GetArg("-alertnotify", "");
1072 if (strCmd.empty()) return;
1074 // Alert text should be plain ascii coming from a trusted source, but to
1075 // be safe we first strip anything not in safeChars, then add single quotes around
1076 // the whole string before passing it to the shell:
1077 std::string singleQuote("'");
1078 std::string safeStatus = SanitizeString(strMessage);
1079 safeStatus = singleQuote+safeStatus+singleQuote;
1080 boost::replace_all(strCmd, "%s", safeStatus);
1082 boost::thread t(runCommand, strCmd); // thread runs free
1085 static void CheckForkWarningConditions()
1087 AssertLockHeld(cs_main);
1088 // Before we get past initial download, we cannot reliably alert about forks
1089 // (we assume we don't get stuck on a fork before finishing our initial sync)
1090 if (IsInitialBlockDownload())
1091 return;
1093 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1094 // of our head, drop it
1095 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1096 pindexBestForkTip = nullptr;
1098 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1100 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
1102 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1103 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1104 AlertNotify(warning);
1106 if (pindexBestForkTip && pindexBestForkBase)
1108 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__,
1109 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1110 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1111 SetfLargeWorkForkFound(true);
1113 else
1115 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1116 SetfLargeWorkInvalidChainFound(true);
1119 else
1121 SetfLargeWorkForkFound(false);
1122 SetfLargeWorkInvalidChainFound(false);
1126 static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1128 AssertLockHeld(cs_main);
1129 // If we are on a fork that is sufficiently large, set a warning flag
1130 CBlockIndex* pfork = pindexNewForkTip;
1131 CBlockIndex* plonger = chainActive.Tip();
1132 while (pfork && pfork != plonger)
1134 while (plonger && plonger->nHeight > pfork->nHeight)
1135 plonger = plonger->pprev;
1136 if (pfork == plonger)
1137 break;
1138 pfork = pfork->pprev;
1141 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1142 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1143 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1144 // hash rate operating on the fork.
1145 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1146 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1147 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1148 if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
1149 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1150 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1152 pindexBestForkTip = pindexNewForkTip;
1153 pindexBestForkBase = pfork;
1156 CheckForkWarningConditions();
1159 void static InvalidChainFound(CBlockIndex* pindexNew)
1161 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1162 pindexBestInvalid = pindexNew;
1164 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1165 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1166 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1167 pindexNew->GetBlockTime()));
1168 CBlockIndex *tip = chainActive.Tip();
1169 assert (tip);
1170 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1171 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1172 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1173 CheckForkWarningConditions();
1176 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1177 if (!state.CorruptionPossible()) {
1178 pindex->nStatus |= BLOCK_FAILED_VALID;
1179 setDirtyBlockIndex.insert(pindex);
1180 setBlockIndexCandidates.erase(pindex);
1181 InvalidChainFound(pindex);
1185 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1187 // mark inputs spent
1188 if (!tx.IsCoinBase()) {
1189 txundo.vprevout.reserve(tx.vin.size());
1190 for (const CTxIn &txin : tx.vin) {
1191 txundo.vprevout.emplace_back();
1192 bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1193 assert(is_spent);
1196 // add outputs
1197 AddCoins(inputs, tx, nHeight);
1200 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1202 CTxUndo txundo;
1203 UpdateCoins(tx, inputs, txundo, nHeight);
1206 bool CScriptCheck::operator()() {
1207 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1208 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1209 return VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *txdata), &error);
1212 int GetSpendHeight(const CCoinsViewCache& inputs)
1214 LOCK(cs_main);
1215 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1216 return pindexPrev->nHeight + 1;
1220 static CuckooCache::cache<uint256, SignatureCacheHasher> scriptExecutionCache;
1221 static uint256 scriptExecutionCacheNonce(GetRandHash());
1223 void InitScriptExecutionCache() {
1224 // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1225 // setup_bytes creates the minimum possible cache (2 elements).
1226 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);
1227 size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
1228 LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1229 (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1233 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
1234 * This does not modify the UTXO set.
1236 * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
1237 * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
1238 * not pushed onto pvChecks/run.
1240 * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
1241 * which are matched. This is useful for checking blocks where we will likely never need the cache
1242 * entry again.
1244 * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
1246 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)
1248 if (!tx.IsCoinBase())
1250 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1251 return false;
1253 if (pvChecks)
1254 pvChecks->reserve(tx.vin.size());
1256 // The first loop above does all the inexpensive checks.
1257 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1258 // Helps prevent CPU exhaustion attacks.
1260 // Skip script verification when connecting blocks under the
1261 // assumevalid block. Assuming the assumevalid block is valid this
1262 // is safe because block merkle hashes are still computed and checked,
1263 // Of course, if an assumed valid block is invalid due to false scriptSigs
1264 // this optimization would allow an invalid chain to be accepted.
1265 if (fScriptChecks) {
1266 // First check if script executions have been cached with the same
1267 // flags. Note that this assumes that the inputs provided are
1268 // correct (ie that the transaction hash which is in tx's prevouts
1269 // properly commits to the scriptPubKey in the inputs view of that
1270 // transaction).
1271 uint256 hashCacheEntry;
1272 // We only use the first 19 bytes of nonce to avoid a second SHA
1273 // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
1274 static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
1275 CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1276 AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1277 if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1278 return true;
1281 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1282 const COutPoint &prevout = tx.vin[i].prevout;
1283 const Coin& coin = inputs.AccessCoin(prevout);
1284 assert(!coin.IsSpent());
1286 // We very carefully only pass in things to CScriptCheck which
1287 // are clearly committed to by tx' witness hash. This provides
1288 // a sanity check that our caching is not introducing consensus
1289 // failures through additional data in, eg, the coins being
1290 // spent being checked as a part of CScriptCheck.
1292 // Verify signature
1293 CScriptCheck check(coin.out, tx, i, flags, cacheSigStore, &txdata);
1294 if (pvChecks) {
1295 pvChecks->push_back(CScriptCheck());
1296 check.swap(pvChecks->back());
1297 } else if (!check()) {
1298 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1299 // Check whether the failure was caused by a
1300 // non-mandatory script verification check, such as
1301 // non-standard DER encodings or non-null dummy
1302 // arguments; if so, don't trigger DoS protection to
1303 // avoid splitting the network between upgraded and
1304 // non-upgraded nodes.
1305 CScriptCheck check2(coin.out, tx, i,
1306 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1307 if (check2())
1308 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1310 // Failures of other flags indicate a transaction that is
1311 // invalid in new blocks, e.g. an invalid P2SH. We DoS ban
1312 // such nodes as they are not following the protocol. That
1313 // said during an upgrade careful thought should be taken
1314 // as to the correct behavior - we may want to continue
1315 // peering with non-upgraded nodes even after soft-fork
1316 // super-majority signaling has occurred.
1317 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1321 if (cacheFullScriptStore && !pvChecks) {
1322 // We executed all of the provided scripts, and were told to
1323 // cache the result. Do so now.
1324 scriptExecutionCache.insert(hashCacheEntry);
1329 return true;
1332 namespace {
1334 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1336 // Open history file to append
1337 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1338 if (fileout.IsNull())
1339 return error("%s: OpenUndoFile failed", __func__);
1341 // Write index header
1342 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1343 fileout << FLATDATA(messageStart) << nSize;
1345 // Write undo data
1346 long fileOutPos = ftell(fileout.Get());
1347 if (fileOutPos < 0)
1348 return error("%s: ftell failed", __func__);
1349 pos.nPos = (unsigned int)fileOutPos;
1350 fileout << blockundo;
1352 // calculate & write checksum
1353 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1354 hasher << hashBlock;
1355 hasher << blockundo;
1356 fileout << hasher.GetHash();
1358 return true;
1361 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1363 // Open history file to read
1364 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1365 if (filein.IsNull())
1366 return error("%s: OpenUndoFile failed", __func__);
1368 // Read block
1369 uint256 hashChecksum;
1370 CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1371 try {
1372 verifier << hashBlock;
1373 verifier >> blockundo;
1374 filein >> hashChecksum;
1376 catch (const std::exception& e) {
1377 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1380 // Verify checksum
1381 if (hashChecksum != verifier.GetHash())
1382 return error("%s: Checksum mismatch", __func__);
1384 return true;
1387 /** Abort with a message */
1388 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1390 SetMiscWarning(strMessage);
1391 LogPrintf("*** %s\n", strMessage);
1392 uiInterface.ThreadSafeMessageBox(
1393 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1394 "", CClientUIInterface::MSG_ERROR);
1395 StartShutdown();
1396 return false;
1399 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1401 AbortNode(strMessage, userMessage);
1402 return state.Error(strMessage);
1405 } // namespace
1407 enum DisconnectResult
1409 DISCONNECT_OK, // All good.
1410 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
1411 DISCONNECT_FAILED // Something else went wrong.
1415 * Restore the UTXO in a Coin at a given COutPoint
1416 * @param undo The Coin to be restored.
1417 * @param view The coins view to which to apply the changes.
1418 * @param out The out point that corresponds to the tx input.
1419 * @return A DisconnectResult as an int
1421 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1423 bool fClean = true;
1425 if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1427 if (undo.nHeight == 0) {
1428 // Missing undo metadata (height and coinbase). Older versions included this
1429 // information only in undo records for the last spend of a transactions'
1430 // outputs. This implies that it must be present for some other output of the same tx.
1431 const Coin& alternate = AccessByTxid(view, out.hash);
1432 if (!alternate.IsSpent()) {
1433 undo.nHeight = alternate.nHeight;
1434 undo.fCoinBase = alternate.fCoinBase;
1435 } else {
1436 return DISCONNECT_FAILED; // adding output for transaction without known metadata
1439 // The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
1440 // sure that the coin did not already exist in the cache. As we have queried for that above
1441 // using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
1442 // it is an overwrite.
1443 view.AddCoin(out, std::move(undo), !fClean);
1445 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1448 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1449 * When FAILED is returned, view is left in an indeterminate state. */
1450 static DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1452 bool fClean = true;
1454 CBlockUndo blockUndo;
1455 CDiskBlockPos pos = pindex->GetUndoPos();
1456 if (pos.IsNull()) {
1457 error("DisconnectBlock(): no undo data available");
1458 return DISCONNECT_FAILED;
1460 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) {
1461 error("DisconnectBlock(): failure reading undo data");
1462 return DISCONNECT_FAILED;
1465 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1466 error("DisconnectBlock(): block and undo data inconsistent");
1467 return DISCONNECT_FAILED;
1470 // undo transactions in reverse order
1471 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1472 const CTransaction &tx = *(block.vtx[i]);
1473 uint256 hash = tx.GetHash();
1474 bool is_coinbase = tx.IsCoinBase();
1476 // Check that all outputs are available and match the outputs in the block itself
1477 // exactly.
1478 for (size_t o = 0; o < tx.vout.size(); o++) {
1479 if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1480 COutPoint out(hash, o);
1481 Coin coin;
1482 bool is_spent = view.SpendCoin(out, &coin);
1483 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1484 fClean = false; // transaction output mismatch
1489 // restore inputs
1490 if (i > 0) { // not coinbases
1491 CTxUndo &txundo = blockUndo.vtxundo[i-1];
1492 if (txundo.vprevout.size() != tx.vin.size()) {
1493 error("DisconnectBlock(): transaction and undo data inconsistent");
1494 return DISCONNECT_FAILED;
1496 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1497 const COutPoint &out = tx.vin[j].prevout;
1498 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1499 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1500 fClean = fClean && res != DISCONNECT_UNCLEAN;
1502 // At this point, all of txundo.vprevout should have been moved out.
1506 // move best block pointer to prevout block
1507 view.SetBestBlock(pindex->pprev->GetBlockHash());
1509 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1512 void static FlushBlockFile(bool fFinalize = false)
1514 LOCK(cs_LastBlockFile);
1516 CDiskBlockPos posOld(nLastBlockFile, 0);
1518 FILE *fileOld = OpenBlockFile(posOld);
1519 if (fileOld) {
1520 if (fFinalize)
1521 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1522 FileCommit(fileOld);
1523 fclose(fileOld);
1526 fileOld = OpenUndoFile(posOld);
1527 if (fileOld) {
1528 if (fFinalize)
1529 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1530 FileCommit(fileOld);
1531 fclose(fileOld);
1535 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1537 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1539 void ThreadScriptCheck() {
1540 RenameThread("bitcoin-scriptch");
1541 scriptcheckqueue.Thread();
1544 // Protected by cs_main
1545 VersionBitsCache versionbitscache;
1547 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1549 LOCK(cs_main);
1550 int32_t nVersion = VERSIONBITS_TOP_BITS;
1552 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1553 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1554 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1555 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1559 return nVersion;
1563 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1565 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1567 private:
1568 int bit;
1570 public:
1571 explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1573 int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1574 int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1575 int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1576 int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1578 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1580 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1581 ((pindex->nVersion >> bit) & 1) != 0 &&
1582 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1586 // Protected by cs_main
1587 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1589 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) {
1590 AssertLockHeld(cs_main);
1592 // BIP16 didn't become active until Apr 1 2012
1593 int64_t nBIP16SwitchTime = 1333238400;
1594 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1596 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1598 // Start enforcing the DERSIG (BIP66) rule
1599 if (pindex->nHeight >= consensusparams.BIP66Height) {
1600 flags |= SCRIPT_VERIFY_DERSIG;
1603 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1604 if (pindex->nHeight >= consensusparams.BIP65Height) {
1605 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1608 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1609 if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1610 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1613 // Start enforcing WITNESS rules using versionbits logic.
1614 if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
1615 flags |= SCRIPT_VERIFY_WITNESS;
1616 flags |= SCRIPT_VERIFY_NULLDUMMY;
1619 return flags;
1624 static int64_t nTimeCheck = 0;
1625 static int64_t nTimeForks = 0;
1626 static int64_t nTimeVerify = 0;
1627 static int64_t nTimeConnect = 0;
1628 static int64_t nTimeIndex = 0;
1629 static int64_t nTimeCallbacks = 0;
1630 static int64_t nTimeTotal = 0;
1631 static int64_t nBlocksTotal = 0;
1633 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1634 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1635 * can fail if those validity checks fail (among other reasons). */
1636 static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1637 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false)
1639 AssertLockHeld(cs_main);
1640 assert(pindex);
1641 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1642 assert((pindex->phashBlock == nullptr) ||
1643 (*pindex->phashBlock == block.GetHash()));
1644 int64_t nTimeStart = GetTimeMicros();
1646 // Check it again in case a previous version let a bad block in
1647 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1648 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1650 // verify that the view's current state corresponds to the previous block
1651 uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
1652 assert(hashPrevBlock == view.GetBestBlock());
1654 // Special case for the genesis block, skipping connection of its transactions
1655 // (its coinbase is unspendable)
1656 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1657 if (!fJustCheck)
1658 view.SetBestBlock(pindex->GetBlockHash());
1659 return true;
1662 nBlocksTotal++;
1664 bool fScriptChecks = true;
1665 if (!hashAssumeValid.IsNull()) {
1666 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1667 // A suitable default value is included with the software and updated from time to time. Because validity
1668 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1669 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1670 // effectively caching the result of part of the verification.
1671 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1672 if (it != mapBlockIndex.end()) {
1673 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1674 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1675 pindexBestHeader->nChainWork >= nMinimumChainWork) {
1676 // This block is a member of the assumed verified chain and an ancestor of the best header.
1677 // The equivalent time check discourages hash power from extorting the network via DOS attack
1678 // into accepting an invalid block through telling users they must manually set assumevalid.
1679 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1680 // it hard to hide the implication of the demand. This also avoids having release candidates
1681 // that are hardly doing any signature verification at all in testing without having to
1682 // artificially set the default assumed verified block further back.
1683 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1684 // least as good as the expected chain.
1685 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1690 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1691 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
1693 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1694 // unless those are already completely spent.
1695 // If such overwrites are allowed, coinbases and transactions depending upon those
1696 // can be duplicated to remove the ability to spend the first instance -- even after
1697 // being sent to another address.
1698 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1699 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1700 // already refuses previously-known transaction ids entirely.
1701 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1702 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1703 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1704 // initial block download.
1705 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1706 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1707 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1709 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1710 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1711 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1712 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1713 // duplicate transactions descending from the known pairs either.
1714 // If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
1715 assert(pindex->pprev);
1716 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1717 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1718 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1720 if (fEnforceBIP30) {
1721 for (const auto& tx : block.vtx) {
1722 for (size_t o = 0; o < tx->vout.size(); o++) {
1723 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
1724 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1725 REJECT_INVALID, "bad-txns-BIP30");
1731 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1732 int nLockTimeFlags = 0;
1733 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1734 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1737 // Get the script flags for this block
1738 unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
1740 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1741 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
1743 CBlockUndo blockundo;
1745 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
1747 std::vector<int> prevheights;
1748 CAmount nFees = 0;
1749 int nInputs = 0;
1750 int64_t nSigOpsCost = 0;
1751 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1752 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1753 vPos.reserve(block.vtx.size());
1754 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1755 std::vector<PrecomputedTransactionData> txdata;
1756 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1757 for (unsigned int i = 0; i < block.vtx.size(); i++)
1759 const CTransaction &tx = *(block.vtx[i]);
1761 nInputs += tx.vin.size();
1763 if (!tx.IsCoinBase())
1765 if (!view.HaveInputs(tx))
1766 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1767 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1769 // Check that transaction is BIP68 final
1770 // BIP68 lock checks (as opposed to nLockTime checks) must
1771 // be in ConnectBlock because they require the UTXO set
1772 prevheights.resize(tx.vin.size());
1773 for (size_t j = 0; j < tx.vin.size(); j++) {
1774 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
1777 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1778 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1779 REJECT_INVALID, "bad-txns-nonfinal");
1783 // GetTransactionSigOpCost counts 3 types of sigops:
1784 // * legacy (always)
1785 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1786 // * witness (when witness enabled in flags and excludes coinbase)
1787 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1788 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1789 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1790 REJECT_INVALID, "bad-blk-sigops");
1792 txdata.emplace_back(tx);
1793 if (!tx.IsCoinBase())
1795 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1797 std::vector<CScriptCheck> vChecks;
1798 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1799 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr))
1800 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1801 tx.GetHash().ToString(), FormatStateMessage(state));
1802 control.Add(vChecks);
1805 CTxUndo undoDummy;
1806 if (i > 0) {
1807 blockundo.vtxundo.push_back(CTxUndo());
1809 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1811 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1812 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1814 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1815 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);
1817 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1818 if (block.vtx[0]->GetValueOut() > blockReward)
1819 return state.DoS(100,
1820 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1821 block.vtx[0]->GetValueOut(), blockReward),
1822 REJECT_INVALID, "bad-cb-amount");
1824 if (!control.Wait())
1825 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1826 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1827 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);
1829 if (fJustCheck)
1830 return true;
1832 // Write undo information to disk
1833 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1835 if (pindex->GetUndoPos().IsNull()) {
1836 CDiskBlockPos _pos;
1837 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1838 return error("ConnectBlock(): FindUndoPos failed");
1839 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1840 return AbortNode(state, "Failed to write undo data");
1842 // update nUndoPos in block index
1843 pindex->nUndoPos = _pos.nPos;
1844 pindex->nStatus |= BLOCK_HAVE_UNDO;
1847 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1848 setDirtyBlockIndex.insert(pindex);
1851 if (fTxIndex)
1852 if (!pblocktree->WriteTxIndex(vPos))
1853 return AbortNode(state, "Failed to write transaction index");
1855 assert(pindex->phashBlock);
1856 // add this block to the view's block chain
1857 view.SetBestBlock(pindex->GetBlockHash());
1859 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1860 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
1862 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1863 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
1865 return true;
1869 * Update the on-disk chain state.
1870 * The caches and indexes are flushed depending on the mode we're called with
1871 * if they're too large, if it's been a while since the last write,
1872 * or always and in all cases if we're in prune mode and are deleting files.
1874 bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
1875 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
1876 LOCK(cs_main);
1877 static int64_t nLastWrite = 0;
1878 static int64_t nLastFlush = 0;
1879 static int64_t nLastSetChain = 0;
1880 std::set<int> setFilesToPrune;
1881 bool fFlushForPrune = false;
1882 bool fDoFullFlush = false;
1883 int64_t nNow = 0;
1884 try {
1886 LOCK(cs_LastBlockFile);
1887 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1888 if (nManualPruneHeight > 0) {
1889 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
1890 } else {
1891 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1892 fCheckForPruning = false;
1894 if (!setFilesToPrune.empty()) {
1895 fFlushForPrune = true;
1896 if (!fHavePruned) {
1897 pblocktree->WriteFlag("prunedblockfiles", true);
1898 fHavePruned = true;
1902 nNow = GetTimeMicros();
1903 // Avoid writing/flushing immediately after startup.
1904 if (nLastWrite == 0) {
1905 nLastWrite = nNow;
1907 if (nLastFlush == 0) {
1908 nLastFlush = nNow;
1910 if (nLastSetChain == 0) {
1911 nLastSetChain = nNow;
1913 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1914 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1915 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
1916 // 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).
1917 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
1918 // The cache is over the limit, we have to write now.
1919 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
1920 // 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.
1921 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1922 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1923 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1924 // Combine all conditions that result in a full cache flush.
1925 fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1926 // Write blocks and block index to disk.
1927 if (fDoFullFlush || fPeriodicWrite) {
1928 // Depend on nMinDiskSpace to ensure we can write block index
1929 if (!CheckDiskSpace(0))
1930 return state.Error("out of disk space");
1931 // First make sure all block and undo data is flushed to disk.
1932 FlushBlockFile();
1933 // Then update all block file information (which may refer to block and undo files).
1935 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1936 vFiles.reserve(setDirtyFileInfo.size());
1937 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1938 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
1939 setDirtyFileInfo.erase(it++);
1941 std::vector<const CBlockIndex*> vBlocks;
1942 vBlocks.reserve(setDirtyBlockIndex.size());
1943 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1944 vBlocks.push_back(*it);
1945 setDirtyBlockIndex.erase(it++);
1947 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1948 return AbortNode(state, "Failed to write to block index database");
1951 // Finally remove any pruned files
1952 if (fFlushForPrune)
1953 UnlinkPrunedFiles(setFilesToPrune);
1954 nLastWrite = nNow;
1956 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1957 if (fDoFullFlush) {
1958 // Typical Coin structures on disk are around 48 bytes in size.
1959 // Pushing a new one to the database can cause it to be written
1960 // twice (once in the log, and once in the tables). This is already
1961 // an overestimation, as most will delete an existing entry or
1962 // overwrite one. Still, use a conservative safety factor of 2.
1963 if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
1964 return state.Error("out of disk space");
1965 // Flush the chainstate (which may refer to block index entries).
1966 if (!pcoinsTip->Flush())
1967 return AbortNode(state, "Failed to write to coin database");
1968 nLastFlush = nNow;
1971 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
1972 // Update best block in wallet (so we can detect restored wallets).
1973 GetMainSignals().SetBestChain(chainActive.GetLocator());
1974 nLastSetChain = nNow;
1976 } catch (const std::runtime_error& e) {
1977 return AbortNode(state, std::string("System error while flushing: ") + e.what());
1979 return true;
1982 void FlushStateToDisk() {
1983 CValidationState state;
1984 const CChainParams& chainparams = Params();
1985 FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
1988 void PruneAndFlush() {
1989 CValidationState state;
1990 fCheckForPruning = true;
1991 const CChainParams& chainparams = Params();
1992 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
1995 static void DoWarning(const std::string& strWarning)
1997 static bool fWarned = false;
1998 SetMiscWarning(strWarning);
1999 if (!fWarned) {
2000 AlertNotify(strWarning);
2001 fWarned = true;
2005 /** Update chainActive and related internal data structures. */
2006 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
2007 chainActive.SetTip(pindexNew);
2009 // New best block
2010 mempool.AddTransactionsUpdated(1);
2012 cvBlockChange.notify_all();
2014 std::vector<std::string> warningMessages;
2015 if (!IsInitialBlockDownload())
2017 int nUpgraded = 0;
2018 const CBlockIndex* pindex = chainActive.Tip();
2019 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2020 WarningBitsConditionChecker checker(bit);
2021 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2022 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2023 const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2024 if (state == THRESHOLD_ACTIVE) {
2025 DoWarning(strWarning);
2026 } else {
2027 warningMessages.push_back(strWarning);
2031 // Check the version of the last 100 blocks to see if we need to upgrade:
2032 for (int i = 0; i < 100 && pindex != nullptr; i++)
2034 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2035 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2036 ++nUpgraded;
2037 pindex = pindex->pprev;
2039 if (nUpgraded > 0)
2040 warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
2041 if (nUpgraded > 100/2)
2043 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2044 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2045 DoWarning(strWarning);
2048 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
2049 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
2050 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2051 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2052 GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2053 if (!warningMessages.empty())
2054 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2055 LogPrintf("\n");
2059 /** Disconnect chainActive's tip.
2060 * After calling, the mempool will be in an inconsistent state, with
2061 * transactions from disconnected blocks being added to disconnectpool. You
2062 * should make the mempool consistent again by calling UpdateMempoolForReorg.
2063 * with cs_main held.
2065 * If disconnectpool is nullptr, then no disconnected transactions are added to
2066 * disconnectpool (note that the caller is responsible for mempool consistency
2067 * in any case).
2069 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
2071 CBlockIndex *pindexDelete = chainActive.Tip();
2072 assert(pindexDelete);
2073 // Read block from disk.
2074 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2075 CBlock& block = *pblock;
2076 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2077 return AbortNode(state, "Failed to read block");
2078 // Apply the block atomically to the chain state.
2079 int64_t nStart = GetTimeMicros();
2081 CCoinsViewCache view(pcoinsTip);
2082 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2083 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2084 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2085 bool flushed = view.Flush();
2086 assert(flushed);
2088 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
2089 // Write the chain state to disk, if necessary.
2090 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2091 return false;
2093 if (disconnectpool) {
2094 // Save transactions to re-add to mempool at end of reorg
2095 for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2096 disconnectpool->addTransaction(*it);
2098 while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2099 // Drop the earliest entry, and remove its children from the mempool.
2100 auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2101 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
2102 disconnectpool->removeEntry(it);
2106 // Update chainActive and related variables.
2107 UpdateTip(pindexDelete->pprev, chainparams);
2108 // Let wallets know transactions went from 1-confirmed to
2109 // 0-confirmed or conflicted:
2110 GetMainSignals().BlockDisconnected(pblock);
2111 return true;
2114 static int64_t nTimeReadFromDisk = 0;
2115 static int64_t nTimeConnectTotal = 0;
2116 static int64_t nTimeFlush = 0;
2117 static int64_t nTimeChainState = 0;
2118 static int64_t nTimePostConnect = 0;
2120 struct PerBlockConnectTrace {
2121 CBlockIndex* pindex = nullptr;
2122 std::shared_ptr<const CBlock> pblock;
2123 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
2124 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
2127 * Used to track blocks whose transactions were applied to the UTXO state as a
2128 * part of a single ActivateBestChainStep call.
2130 * This class also tracks transactions that are removed from the mempool as
2131 * conflicts (per block) and can be used to pass all those transactions
2132 * through SyncTransaction.
2134 * This class assumes (and asserts) that the conflicted transactions for a given
2135 * block are added via mempool callbacks prior to the BlockConnected() associated
2136 * with those transactions. If any transactions are marked conflicted, it is
2137 * assumed that an associated block will always be added.
2139 * This class is single-use, once you call GetBlocksConnected() you have to throw
2140 * it away and make a new one.
2142 class ConnectTrace {
2143 private:
2144 std::vector<PerBlockConnectTrace> blocksConnected;
2145 CTxMemPool &pool;
2147 public:
2148 explicit ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
2149 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2152 ~ConnectTrace() {
2153 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2156 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2157 assert(!blocksConnected.back().pindex);
2158 assert(pindex);
2159 assert(pblock);
2160 blocksConnected.back().pindex = pindex;
2161 blocksConnected.back().pblock = std::move(pblock);
2162 blocksConnected.emplace_back();
2165 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2166 // We always keep one extra block at the end of our list because
2167 // blocks are added after all the conflicted transactions have
2168 // been filled in. Thus, the last entry should always be an empty
2169 // one waiting for the transactions from the next block. We pop
2170 // the last entry here to make sure the list we return is sane.
2171 assert(!blocksConnected.back().pindex);
2172 assert(blocksConnected.back().conflictedTxs->empty());
2173 blocksConnected.pop_back();
2174 return blocksConnected;
2177 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
2178 assert(!blocksConnected.back().pindex);
2179 if (reason == MemPoolRemovalReason::CONFLICT) {
2180 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2186 * Connect a new block to chainActive. pblock is either nullptr or a pointer to a CBlock
2187 * corresponding to pindexNew, to bypass loading it again from disk.
2189 * The block is added to connectTrace if connection succeeds.
2191 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
2193 assert(pindexNew->pprev == chainActive.Tip());
2194 // Read block from disk.
2195 int64_t nTime1 = GetTimeMicros();
2196 std::shared_ptr<const CBlock> pthisBlock;
2197 if (!pblock) {
2198 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2199 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2200 return AbortNode(state, "Failed to read block");
2201 pthisBlock = pblockNew;
2202 } else {
2203 pthisBlock = pblock;
2205 const CBlock& blockConnecting = *pthisBlock;
2206 // Apply the block atomically to the chain state.
2207 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2208 int64_t nTime3;
2209 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
2211 CCoinsViewCache view(pcoinsTip);
2212 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2213 GetMainSignals().BlockChecked(blockConnecting, state);
2214 if (!rv) {
2215 if (state.IsInvalid())
2216 InvalidBlockFound(pindexNew, state);
2217 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2219 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2220 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
2221 bool flushed = view.Flush();
2222 assert(flushed);
2224 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2225 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
2226 // Write the chain state to disk, if necessary.
2227 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2228 return false;
2229 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2230 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
2231 // Remove conflicting transactions from the mempool.;
2232 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2233 disconnectpool.removeForBlock(blockConnecting.vtx);
2234 // Update chainActive & related variables.
2235 UpdateTip(pindexNew, chainparams);
2237 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2238 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
2239 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
2241 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2242 return true;
2246 * Return the tip of the chain with the most work in it, that isn't
2247 * known to be invalid (it's however far from certain to be valid).
2249 static CBlockIndex* FindMostWorkChain() {
2250 do {
2251 CBlockIndex *pindexNew = nullptr;
2253 // Find the best candidate header.
2255 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2256 if (it == setBlockIndexCandidates.rend())
2257 return nullptr;
2258 pindexNew = *it;
2261 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2262 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2263 CBlockIndex *pindexTest = pindexNew;
2264 bool fInvalidAncestor = false;
2265 while (pindexTest && !chainActive.Contains(pindexTest)) {
2266 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2268 // Pruned nodes may have entries in setBlockIndexCandidates for
2269 // which block files have been deleted. Remove those as candidates
2270 // for the most work chain if we come across them; we can't switch
2271 // to a chain unless we have all the non-active-chain parent blocks.
2272 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2273 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2274 if (fFailedChain || fMissingData) {
2275 // Candidate chain is not usable (either invalid or missing data)
2276 if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2277 pindexBestInvalid = pindexNew;
2278 CBlockIndex *pindexFailed = pindexNew;
2279 // Remove the entire chain from the set.
2280 while (pindexTest != pindexFailed) {
2281 if (fFailedChain) {
2282 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2283 } else if (fMissingData) {
2284 // If we're missing data, then add back to mapBlocksUnlinked,
2285 // so that if the block arrives in the future we can try adding
2286 // to setBlockIndexCandidates again.
2287 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2289 setBlockIndexCandidates.erase(pindexFailed);
2290 pindexFailed = pindexFailed->pprev;
2292 setBlockIndexCandidates.erase(pindexTest);
2293 fInvalidAncestor = true;
2294 break;
2296 pindexTest = pindexTest->pprev;
2298 if (!fInvalidAncestor)
2299 return pindexNew;
2300 } while(true);
2303 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2304 static void PruneBlockIndexCandidates() {
2305 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2306 // reorganization to a better block fails.
2307 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2308 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2309 setBlockIndexCandidates.erase(it++);
2311 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2312 assert(!setBlockIndexCandidates.empty());
2316 * Try to make some progress towards making pindexMostWork the active block.
2317 * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
2319 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2321 AssertLockHeld(cs_main);
2322 const CBlockIndex *pindexOldTip = chainActive.Tip();
2323 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2325 // Disconnect active blocks which are no longer in the best chain.
2326 bool fBlocksDisconnected = false;
2327 DisconnectedBlockTransactions disconnectpool;
2328 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2329 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2330 // This is likely a fatal error, but keep the mempool consistent,
2331 // just in case. Only remove from the mempool in this case.
2332 UpdateMempoolForReorg(disconnectpool, false);
2333 return false;
2335 fBlocksDisconnected = true;
2338 // Build list of new blocks to connect.
2339 std::vector<CBlockIndex*> vpindexToConnect;
2340 bool fContinue = true;
2341 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2342 while (fContinue && nHeight != pindexMostWork->nHeight) {
2343 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2344 // a few blocks along the way.
2345 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2346 vpindexToConnect.clear();
2347 vpindexToConnect.reserve(nTargetHeight - nHeight);
2348 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2349 while (pindexIter && pindexIter->nHeight != nHeight) {
2350 vpindexToConnect.push_back(pindexIter);
2351 pindexIter = pindexIter->pprev;
2353 nHeight = nTargetHeight;
2355 // Connect new blocks.
2356 for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
2357 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2358 if (state.IsInvalid()) {
2359 // The block violates a consensus rule.
2360 if (!state.CorruptionPossible())
2361 InvalidChainFound(vpindexToConnect.back());
2362 state = CValidationState();
2363 fInvalidFound = true;
2364 fContinue = false;
2365 break;
2366 } else {
2367 // A system error occurred (disk space, database error, ...).
2368 // Make the mempool consistent with the current tip, just in case
2369 // any observers try to use it before shutdown.
2370 UpdateMempoolForReorg(disconnectpool, false);
2371 return false;
2373 } else {
2374 PruneBlockIndexCandidates();
2375 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2376 // We're in a better position than we were. Return temporarily to release the lock.
2377 fContinue = false;
2378 break;
2384 if (fBlocksDisconnected) {
2385 // If any blocks were disconnected, disconnectpool may be non empty. Add
2386 // any disconnected transactions back to the mempool.
2387 UpdateMempoolForReorg(disconnectpool, true);
2389 mempool.check(pcoinsTip);
2391 // Callbacks/notifications for a new best chain.
2392 if (fInvalidFound)
2393 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2394 else
2395 CheckForkWarningConditions();
2397 return true;
2400 static void NotifyHeaderTip() {
2401 bool fNotify = false;
2402 bool fInitialBlockDownload = false;
2403 static CBlockIndex* pindexHeaderOld = nullptr;
2404 CBlockIndex* pindexHeader = nullptr;
2406 LOCK(cs_main);
2407 pindexHeader = pindexBestHeader;
2409 if (pindexHeader != pindexHeaderOld) {
2410 fNotify = true;
2411 fInitialBlockDownload = IsInitialBlockDownload();
2412 pindexHeaderOld = pindexHeader;
2415 // Send block tip changed notifications without cs_main
2416 if (fNotify) {
2417 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2422 * Make the best chain active, in multiple steps. The result is either failure
2423 * or an activated best chain. pblock is either nullptr or a pointer to a block
2424 * that is already loaded (to avoid loading it again from disk).
2426 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2427 // Note that while we're often called here from ProcessNewBlock, this is
2428 // far from a guarantee. Things in the P2P/RPC will often end up calling
2429 // us in the middle of ProcessNewBlock - do not assume pblock is set
2430 // sanely for performance or correctness!
2432 CBlockIndex *pindexMostWork = nullptr;
2433 CBlockIndex *pindexNewTip = nullptr;
2434 int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2435 do {
2436 boost::this_thread::interruption_point();
2437 if (ShutdownRequested())
2438 break;
2440 const CBlockIndex *pindexFork;
2441 bool fInitialDownload;
2443 LOCK(cs_main);
2444 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2446 CBlockIndex *pindexOldTip = chainActive.Tip();
2447 if (pindexMostWork == nullptr) {
2448 pindexMostWork = FindMostWorkChain();
2451 // Whether we have anything to do at all.
2452 if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip())
2453 return true;
2455 bool fInvalidFound = false;
2456 std::shared_ptr<const CBlock> nullBlockPtr;
2457 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2458 return false;
2460 if (fInvalidFound) {
2461 // Wipe cache, we may need another branch now.
2462 pindexMostWork = nullptr;
2464 pindexNewTip = chainActive.Tip();
2465 pindexFork = chainActive.FindFork(pindexOldTip);
2466 fInitialDownload = IsInitialBlockDownload();
2468 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2469 assert(trace.pblock && trace.pindex);
2470 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, *trace.conflictedTxs);
2473 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2475 // Notifications/callbacks that can run without cs_main
2477 // Notify external listeners about the new tip.
2478 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2480 // Always notify the UI if a new block tip was connected
2481 if (pindexFork != pindexNewTip) {
2482 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2485 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2486 } while (pindexNewTip != pindexMostWork);
2487 CheckBlockIndex(chainparams.GetConsensus());
2489 // Write changes periodically to disk, after relay.
2490 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
2491 return false;
2494 return true;
2498 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2501 LOCK(cs_main);
2502 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2503 // Nothing to do, this block is not at the tip.
2504 return true;
2506 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2507 // The chain has been extended since the last call, reset the counter.
2508 nBlockReverseSequenceId = -1;
2510 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2511 setBlockIndexCandidates.erase(pindex);
2512 pindex->nSequenceId = nBlockReverseSequenceId;
2513 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2514 // We can't keep reducing the counter if somebody really wants to
2515 // call preciousblock 2**31-1 times on the same set of tips...
2516 nBlockReverseSequenceId--;
2518 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2519 setBlockIndexCandidates.insert(pindex);
2520 PruneBlockIndexCandidates();
2524 return ActivateBestChain(state, params);
2527 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2529 AssertLockHeld(cs_main);
2531 // Mark the block itself as invalid.
2532 pindex->nStatus |= BLOCK_FAILED_VALID;
2533 setDirtyBlockIndex.insert(pindex);
2534 setBlockIndexCandidates.erase(pindex);
2536 DisconnectedBlockTransactions disconnectpool;
2537 while (chainActive.Contains(pindex)) {
2538 CBlockIndex *pindexWalk = chainActive.Tip();
2539 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2540 setDirtyBlockIndex.insert(pindexWalk);
2541 setBlockIndexCandidates.erase(pindexWalk);
2542 // ActivateBestChain considers blocks already in chainActive
2543 // unconditionally valid already, so force disconnect away from it.
2544 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2545 // It's probably hopeless to try to make the mempool consistent
2546 // here if DisconnectTip failed, but we can try.
2547 UpdateMempoolForReorg(disconnectpool, false);
2548 return false;
2552 // DisconnectTip will add transactions to disconnectpool; try to add these
2553 // back to the mempool.
2554 UpdateMempoolForReorg(disconnectpool, true);
2556 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2557 // add it again.
2558 BlockMap::iterator it = mapBlockIndex.begin();
2559 while (it != mapBlockIndex.end()) {
2560 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2561 setBlockIndexCandidates.insert(it->second);
2563 it++;
2566 InvalidChainFound(pindex);
2567 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2568 return true;
2571 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2572 AssertLockHeld(cs_main);
2574 int nHeight = pindex->nHeight;
2576 // Remove the invalidity flag from this block and all its descendants.
2577 BlockMap::iterator it = mapBlockIndex.begin();
2578 while (it != mapBlockIndex.end()) {
2579 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2580 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2581 setDirtyBlockIndex.insert(it->second);
2582 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2583 setBlockIndexCandidates.insert(it->second);
2585 if (it->second == pindexBestInvalid) {
2586 // Reset invalid block marker if it was pointing to one of those.
2587 pindexBestInvalid = nullptr;
2590 it++;
2593 // Remove the invalidity flag from all ancestors too.
2594 while (pindex != nullptr) {
2595 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2596 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2597 setDirtyBlockIndex.insert(pindex);
2599 pindex = pindex->pprev;
2601 return true;
2604 static CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2606 // Check for duplicate
2607 uint256 hash = block.GetHash();
2608 BlockMap::iterator it = mapBlockIndex.find(hash);
2609 if (it != mapBlockIndex.end())
2610 return it->second;
2612 // Construct new block index object
2613 CBlockIndex* pindexNew = new CBlockIndex(block);
2614 assert(pindexNew);
2615 // We assign the sequence id to blocks only when the full data is available,
2616 // to avoid miners withholding blocks but broadcasting headers, to get a
2617 // competitive advantage.
2618 pindexNew->nSequenceId = 0;
2619 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2620 pindexNew->phashBlock = &((*mi).first);
2621 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2622 if (miPrev != mapBlockIndex.end())
2624 pindexNew->pprev = (*miPrev).second;
2625 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2626 pindexNew->BuildSkip();
2628 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2629 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2630 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2631 if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2632 pindexBestHeader = pindexNew;
2634 setDirtyBlockIndex.insert(pindexNew);
2636 return pindexNew;
2639 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2640 static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2642 pindexNew->nTx = block.vtx.size();
2643 pindexNew->nChainTx = 0;
2644 pindexNew->nFile = pos.nFile;
2645 pindexNew->nDataPos = pos.nPos;
2646 pindexNew->nUndoPos = 0;
2647 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2648 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2649 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2651 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2652 setDirtyBlockIndex.insert(pindexNew);
2654 if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
2655 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2656 std::deque<CBlockIndex*> queue;
2657 queue.push_back(pindexNew);
2659 // Recursively process any descendant blocks that now may be eligible to be connected.
2660 while (!queue.empty()) {
2661 CBlockIndex *pindex = queue.front();
2662 queue.pop_front();
2663 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2665 LOCK(cs_nBlockSequenceId);
2666 pindex->nSequenceId = nBlockSequenceId++;
2668 if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2669 setBlockIndexCandidates.insert(pindex);
2671 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2672 while (range.first != range.second) {
2673 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2674 queue.push_back(it->second);
2675 range.first++;
2676 mapBlocksUnlinked.erase(it);
2679 } else {
2680 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2681 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2685 return true;
2688 static bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2690 LOCK(cs_LastBlockFile);
2692 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2693 if (vinfoBlockFile.size() <= nFile) {
2694 vinfoBlockFile.resize(nFile + 1);
2697 if (!fKnown) {
2698 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2699 nFile++;
2700 if (vinfoBlockFile.size() <= nFile) {
2701 vinfoBlockFile.resize(nFile + 1);
2704 pos.nFile = nFile;
2705 pos.nPos = vinfoBlockFile[nFile].nSize;
2708 if ((int)nFile != nLastBlockFile) {
2709 if (!fKnown) {
2710 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2712 FlushBlockFile(!fKnown);
2713 nLastBlockFile = nFile;
2716 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2717 if (fKnown)
2718 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2719 else
2720 vinfoBlockFile[nFile].nSize += nAddSize;
2722 if (!fKnown) {
2723 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2724 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2725 if (nNewChunks > nOldChunks) {
2726 if (fPruneMode)
2727 fCheckForPruning = true;
2728 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2729 FILE *file = OpenBlockFile(pos);
2730 if (file) {
2731 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2732 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2733 fclose(file);
2736 else
2737 return state.Error("out of disk space");
2741 setDirtyFileInfo.insert(nFile);
2742 return true;
2745 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2747 pos.nFile = nFile;
2749 LOCK(cs_LastBlockFile);
2751 unsigned int nNewSize;
2752 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2753 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2754 setDirtyFileInfo.insert(nFile);
2756 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2757 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2758 if (nNewChunks > nOldChunks) {
2759 if (fPruneMode)
2760 fCheckForPruning = true;
2761 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2762 FILE *file = OpenUndoFile(pos);
2763 if (file) {
2764 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2765 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2766 fclose(file);
2769 else
2770 return state.Error("out of disk space");
2773 return true;
2776 static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
2778 // Check proof of work matches claimed amount
2779 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2780 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2782 return true;
2785 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2787 // These are checks that are independent of context.
2789 if (block.fChecked)
2790 return true;
2792 // Check that the header is valid (particularly PoW). This is mostly
2793 // redundant with the call in AcceptBlockHeader.
2794 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2795 return false;
2797 // Check the merkle root.
2798 if (fCheckMerkleRoot) {
2799 bool mutated;
2800 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2801 if (block.hashMerkleRoot != hashMerkleRoot2)
2802 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2804 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2805 // of transactions in a block without affecting the merkle root of a block,
2806 // while still invalidating it.
2807 if (mutated)
2808 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2811 // All potential-corruption validation must be done before we do any
2812 // transaction validation, as otherwise we may mark the header as invalid
2813 // because we receive the wrong transactions for it.
2814 // Note that witness malleability is checked in ContextualCheckBlock, so no
2815 // checks that use witness data may be performed here.
2817 // Size limits
2818 if (block.vtx.empty() || block.vtx.size() * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)
2819 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2821 // First transaction must be coinbase, the rest must not be
2822 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2823 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2824 for (unsigned int i = 1; i < block.vtx.size(); i++)
2825 if (block.vtx[i]->IsCoinBase())
2826 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2828 // Check transactions
2829 for (const auto& tx : block.vtx)
2830 if (!CheckTransaction(*tx, state, false))
2831 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2832 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2834 unsigned int nSigOps = 0;
2835 for (const auto& tx : block.vtx)
2837 nSigOps += GetLegacySigOpCount(*tx);
2839 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2840 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2842 if (fCheckPOW && fCheckMerkleRoot)
2843 block.fChecked = true;
2845 return true;
2848 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2850 LOCK(cs_main);
2851 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2854 // Compute at which vout of the block's coinbase transaction the witness
2855 // commitment occurs, or -1 if not found.
2856 static int GetWitnessCommitmentIndex(const CBlock& block)
2858 int commitpos = -1;
2859 if (!block.vtx.empty()) {
2860 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2861 if (block.vtx[0]->vout[o].scriptPubKey.size() >= 38 && block.vtx[0]->vout[o].scriptPubKey[0] == OP_RETURN && block.vtx[0]->vout[o].scriptPubKey[1] == 0x24 && block.vtx[0]->vout[o].scriptPubKey[2] == 0xaa && block.vtx[0]->vout[o].scriptPubKey[3] == 0x21 && block.vtx[0]->vout[o].scriptPubKey[4] == 0xa9 && block.vtx[0]->vout[o].scriptPubKey[5] == 0xed) {
2862 commitpos = o;
2866 return commitpos;
2869 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2871 int commitpos = GetWitnessCommitmentIndex(block);
2872 static const std::vector<unsigned char> nonce(32, 0x00);
2873 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2874 CMutableTransaction tx(*block.vtx[0]);
2875 tx.vin[0].scriptWitness.stack.resize(1);
2876 tx.vin[0].scriptWitness.stack[0] = nonce;
2877 block.vtx[0] = MakeTransactionRef(std::move(tx));
2881 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2883 std::vector<unsigned char> commitment;
2884 int commitpos = GetWitnessCommitmentIndex(block);
2885 std::vector<unsigned char> ret(32, 0x00);
2886 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2887 if (commitpos == -1) {
2888 uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
2889 CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
2890 CTxOut out;
2891 out.nValue = 0;
2892 out.scriptPubKey.resize(38);
2893 out.scriptPubKey[0] = OP_RETURN;
2894 out.scriptPubKey[1] = 0x24;
2895 out.scriptPubKey[2] = 0xaa;
2896 out.scriptPubKey[3] = 0x21;
2897 out.scriptPubKey[4] = 0xa9;
2898 out.scriptPubKey[5] = 0xed;
2899 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2900 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2901 CMutableTransaction tx(*block.vtx[0]);
2902 tx.vout.push_back(out);
2903 block.vtx[0] = MakeTransactionRef(std::move(tx));
2906 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2907 return commitment;
2910 /** Context-dependent validity checks.
2911 * By "context", we mean only the previous block headers, but not the UTXO
2912 * set; UTXO-related validity checks are done in ConnectBlock(). */
2913 static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2915 assert(pindexPrev != nullptr);
2916 const int nHeight = pindexPrev->nHeight + 1;
2918 // Check proof of work
2919 const Consensus::Params& consensusParams = params.GetConsensus();
2920 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2921 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2923 // Check against checkpoints
2924 if (fCheckpointsEnabled) {
2925 // Don't accept any forks from the main chain prior to last checkpoint.
2926 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
2927 // MapBlockIndex.
2928 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(params.Checkpoints());
2929 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2930 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
2933 // Check timestamp against prev
2934 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2935 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2937 // Check timestamp
2938 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
2939 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
2941 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2942 // check for version 2, 3 and 4 upgrades
2943 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
2944 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
2945 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
2946 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
2947 strprintf("rejected nVersion=0x%08x block", block.nVersion));
2949 return true;
2952 static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
2954 const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
2956 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
2957 int nLockTimeFlags = 0;
2958 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
2959 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
2962 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
2963 ? pindexPrev->GetMedianTimePast()
2964 : block.GetBlockTime();
2966 // Check that all transactions are finalized
2967 for (const auto& tx : block.vtx) {
2968 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
2969 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
2973 // Enforce rule that the coinbase starts with serialized block height
2974 if (nHeight >= consensusParams.BIP34Height)
2976 CScript expect = CScript() << nHeight;
2977 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
2978 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
2979 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
2983 // Validation for witness commitments.
2984 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
2985 // coinbase (where 0x0000....0000 is used instead).
2986 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
2987 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
2988 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
2989 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
2990 // multiple, the last one is used.
2991 bool fHaveWitness = false;
2992 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
2993 int commitpos = GetWitnessCommitmentIndex(block);
2994 if (commitpos != -1) {
2995 bool malleated = false;
2996 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
2997 // The malleation check is ignored; as the transaction tree itself
2998 // already does not permit it, it is impossible to trigger in the
2999 // witness tree.
3000 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3001 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
3003 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
3004 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3005 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
3007 fHaveWitness = true;
3011 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3012 if (!fHaveWitness) {
3013 for (const auto& tx : block.vtx) {
3014 if (tx->HasWitness()) {
3015 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
3020 // After the coinbase witness nonce and commitment are verified,
3021 // we can check if the block weight passes (before we've checked the
3022 // coinbase witness, it would be possible for the weight to be too
3023 // large by filling up the coinbase witness, which doesn't change
3024 // the block hash, so we couldn't mark the block as permanently
3025 // failed).
3026 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3027 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
3030 return true;
3033 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3035 AssertLockHeld(cs_main);
3036 // Check for duplicate
3037 uint256 hash = block.GetHash();
3038 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3039 CBlockIndex *pindex = nullptr;
3040 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3042 if (miSelf != mapBlockIndex.end()) {
3043 // Block header is already known.
3044 pindex = miSelf->second;
3045 if (ppindex)
3046 *ppindex = pindex;
3047 if (pindex->nStatus & BLOCK_FAILED_MASK)
3048 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3049 return true;
3052 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3053 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3055 // Get prev block index
3056 CBlockIndex* pindexPrev = nullptr;
3057 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3058 if (mi == mapBlockIndex.end())
3059 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
3060 pindexPrev = (*mi).second;
3061 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3062 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3063 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3064 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3066 if (pindex == nullptr)
3067 pindex = AddToBlockIndex(block);
3069 if (ppindex)
3070 *ppindex = pindex;
3072 CheckBlockIndex(chainparams.GetConsensus());
3074 return true;
3077 // Exposed wrapper for AcceptBlockHeader
3078 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
3081 LOCK(cs_main);
3082 for (const CBlockHeader& header : headers) {
3083 CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3084 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
3085 return false;
3087 if (ppindex) {
3088 *ppindex = pindex;
3092 NotifyHeaderTip();
3093 return true;
3096 /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
3097 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3099 const CBlock& block = *pblock;
3101 if (fNewBlock) *fNewBlock = false;
3102 AssertLockHeld(cs_main);
3104 CBlockIndex *pindexDummy = nullptr;
3105 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3107 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3108 return false;
3110 // Try to process all requested blocks that we don't have, but only
3111 // process an unrequested block if it's new and has enough work to
3112 // advance our tip, and isn't too many blocks ahead.
3113 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3114 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3115 // Blocks that are too out-of-order needlessly limit the effectiveness of
3116 // pruning, because pruning will not delete block files that contain any
3117 // blocks which are too close in height to the tip. Apply this test
3118 // regardless of whether pruning is enabled; it should generally be safe to
3119 // not process unrequested blocks.
3120 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3122 // TODO: Decouple this function from the block download logic by removing fRequested
3123 // This requires some new chain data structure to efficiently look up if a
3124 // block is in a chain leading to a candidate for best tip, despite not
3125 // being such a candidate itself.
3127 // TODO: deal better with return value and error conditions for duplicate
3128 // and unrequested blocks.
3129 if (fAlreadyHave) return true;
3130 if (!fRequested) { // If we didn't ask for it:
3131 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3132 if (!fHasMoreWork) return true; // Don't process less-work chains
3133 if (fTooFarAhead) return true; // Block height is too high
3135 if (fNewBlock) *fNewBlock = true;
3137 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3138 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3139 if (state.IsInvalid() && !state.CorruptionPossible()) {
3140 pindex->nStatus |= BLOCK_FAILED_VALID;
3141 setDirtyBlockIndex.insert(pindex);
3143 return error("%s: %s", __func__, FormatStateMessage(state));
3146 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3147 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3148 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3149 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3151 int nHeight = pindex->nHeight;
3153 // Write block to history file
3154 try {
3155 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3156 CDiskBlockPos blockPos;
3157 if (dbp != nullptr)
3158 blockPos = *dbp;
3159 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr))
3160 return error("AcceptBlock(): FindBlockPos failed");
3161 if (dbp == nullptr)
3162 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3163 AbortNode(state, "Failed to write block");
3164 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3165 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3166 } catch (const std::runtime_error& e) {
3167 return AbortNode(state, std::string("System error: ") + e.what());
3170 if (fCheckForPruning)
3171 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3173 return true;
3176 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3179 CBlockIndex *pindex = nullptr;
3180 if (fNewBlock) *fNewBlock = false;
3181 CValidationState state;
3182 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3183 // belt-and-suspenders.
3184 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3186 LOCK(cs_main);
3188 if (ret) {
3189 // Store to disk
3190 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
3192 CheckBlockIndex(chainparams.GetConsensus());
3193 if (!ret) {
3194 GetMainSignals().BlockChecked(*pblock, state);
3195 return error("%s: AcceptBlock FAILED (%s)", __func__, state.GetDebugMessage());
3199 NotifyHeaderTip();
3201 CValidationState state; // Only used to report errors, not invalidity - ignore it
3202 if (!ActivateBestChain(state, chainparams, pblock))
3203 return error("%s: ActivateBestChain failed", __func__);
3205 return true;
3208 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3210 AssertLockHeld(cs_main);
3211 assert(pindexPrev && pindexPrev == chainActive.Tip());
3212 CCoinsViewCache viewNew(pcoinsTip);
3213 CBlockIndex indexDummy(block);
3214 indexDummy.pprev = pindexPrev;
3215 indexDummy.nHeight = pindexPrev->nHeight + 1;
3217 // NOTE: CheckBlockHeader is called by CheckBlock
3218 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3219 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3220 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3221 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3222 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3223 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3224 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3225 return false;
3226 assert(state.IsValid());
3228 return true;
3232 * BLOCK PRUNING CODE
3235 /* Calculate the amount of disk space the block & undo files currently use */
3236 uint64_t CalculateCurrentUsage()
3238 LOCK(cs_LastBlockFile);
3240 uint64_t retval = 0;
3241 for (const CBlockFileInfo &file : vinfoBlockFile) {
3242 retval += file.nSize + file.nUndoSize;
3244 return retval;
3247 /* Prune a block file (modify associated database entries)*/
3248 void PruneOneBlockFile(const int fileNumber)
3250 LOCK(cs_LastBlockFile);
3252 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3253 CBlockIndex* pindex = it->second;
3254 if (pindex->nFile == fileNumber) {
3255 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3256 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3257 pindex->nFile = 0;
3258 pindex->nDataPos = 0;
3259 pindex->nUndoPos = 0;
3260 setDirtyBlockIndex.insert(pindex);
3262 // Prune from mapBlocksUnlinked -- any block we prune would have
3263 // to be downloaded again in order to consider its chain, at which
3264 // point it would be considered as a candidate for
3265 // mapBlocksUnlinked or setBlockIndexCandidates.
3266 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3267 while (range.first != range.second) {
3268 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3269 range.first++;
3270 if (_it->second == pindex) {
3271 mapBlocksUnlinked.erase(_it);
3277 vinfoBlockFile[fileNumber].SetNull();
3278 setDirtyFileInfo.insert(fileNumber);
3282 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3284 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3285 CDiskBlockPos pos(*it, 0);
3286 fs::remove(GetBlockPosFilename(pos, "blk"));
3287 fs::remove(GetBlockPosFilename(pos, "rev"));
3288 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3292 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3293 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3295 assert(fPruneMode && nManualPruneHeight > 0);
3297 LOCK2(cs_main, cs_LastBlockFile);
3298 if (chainActive.Tip() == nullptr)
3299 return;
3301 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3302 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3303 int count=0;
3304 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3305 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3306 continue;
3307 PruneOneBlockFile(fileNumber);
3308 setFilesToPrune.insert(fileNumber);
3309 count++;
3311 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3314 /* This function is called from the RPC code for pruneblockchain */
3315 void PruneBlockFilesManual(int nManualPruneHeight)
3317 CValidationState state;
3318 const CChainParams& chainparams = Params();
3319 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
3323 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
3324 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
3325 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
3326 * (which in this case means the blockchain must be re-downloaded.)
3328 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
3329 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
3330 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
3331 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
3332 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
3333 * A db flag records the fact that at least some block files have been pruned.
3335 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
3337 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3339 LOCK2(cs_main, cs_LastBlockFile);
3340 if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
3341 return;
3343 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3344 return;
3347 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3348 uint64_t nCurrentUsage = CalculateCurrentUsage();
3349 // We don't check to prune until after we've allocated new space for files
3350 // So we should leave a buffer under our target to account for another allocation
3351 // before the next pruning.
3352 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3353 uint64_t nBytesToPrune;
3354 int count=0;
3356 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3357 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3358 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3360 if (vinfoBlockFile[fileNumber].nSize == 0)
3361 continue;
3363 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3364 break;
3366 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3367 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3368 continue;
3370 PruneOneBlockFile(fileNumber);
3371 // Queue up the files for removal
3372 setFilesToPrune.insert(fileNumber);
3373 nCurrentUsage -= nBytesToPrune;
3374 count++;
3378 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3379 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3380 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3381 nLastBlockWeCanPrune, count);
3384 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3386 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3388 // Check for nMinDiskSpace bytes (currently 50MB)
3389 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3390 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3392 return true;
3395 static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3397 if (pos.IsNull())
3398 return nullptr;
3399 fs::path path = GetBlockPosFilename(pos, prefix);
3400 fs::create_directories(path.parent_path());
3401 FILE* file = fsbridge::fopen(path, "rb+");
3402 if (!file && !fReadOnly)
3403 file = fsbridge::fopen(path, "wb+");
3404 if (!file) {
3405 LogPrintf("Unable to open file %s\n", path.string());
3406 return nullptr;
3408 if (pos.nPos) {
3409 if (fseek(file, pos.nPos, SEEK_SET)) {
3410 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3411 fclose(file);
3412 return nullptr;
3415 return file;
3418 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3419 return OpenDiskFile(pos, "blk", fReadOnly);
3422 /** Open an undo file (rev?????.dat) */
3423 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3424 return OpenDiskFile(pos, "rev", fReadOnly);
3427 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3429 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3432 CBlockIndex * InsertBlockIndex(uint256 hash)
3434 if (hash.IsNull())
3435 return nullptr;
3437 // Return existing
3438 BlockMap::iterator mi = mapBlockIndex.find(hash);
3439 if (mi != mapBlockIndex.end())
3440 return (*mi).second;
3442 // Create new
3443 CBlockIndex* pindexNew = new CBlockIndex();
3444 if (!pindexNew)
3445 throw std::runtime_error(std::string(__func__) + ": new CBlockIndex failed");
3446 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3447 pindexNew->phashBlock = &((*mi).first);
3449 return pindexNew;
3452 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3454 if (!pblocktree->LoadBlockIndexGuts(chainparams.GetConsensus(), InsertBlockIndex))
3455 return false;
3457 boost::this_thread::interruption_point();
3459 // Calculate nChainWork
3460 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3461 vSortedByHeight.reserve(mapBlockIndex.size());
3462 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3464 CBlockIndex* pindex = item.second;
3465 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3467 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3468 for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
3470 CBlockIndex* pindex = item.second;
3471 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3472 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3473 // We can link the chain of blocks for which we've received transactions at some point.
3474 // Pruned nodes may have deleted the block.
3475 if (pindex->nTx > 0) {
3476 if (pindex->pprev) {
3477 if (pindex->pprev->nChainTx) {
3478 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3479 } else {
3480 pindex->nChainTx = 0;
3481 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3483 } else {
3484 pindex->nChainTx = pindex->nTx;
3487 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
3488 setBlockIndexCandidates.insert(pindex);
3489 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3490 pindexBestInvalid = pindex;
3491 if (pindex->pprev)
3492 pindex->BuildSkip();
3493 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3494 pindexBestHeader = pindex;
3497 // Load block file info
3498 pblocktree->ReadLastBlockFile(nLastBlockFile);
3499 vinfoBlockFile.resize(nLastBlockFile + 1);
3500 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3501 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3502 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3504 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3505 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3506 CBlockFileInfo info;
3507 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3508 vinfoBlockFile.push_back(info);
3509 } else {
3510 break;
3514 // Check presence of blk files
3515 LogPrintf("Checking all blk files are present...\n");
3516 std::set<int> setBlkDataFiles;
3517 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3519 CBlockIndex* pindex = item.second;
3520 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3521 setBlkDataFiles.insert(pindex->nFile);
3524 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3526 CDiskBlockPos pos(*it, 0);
3527 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3528 return false;
3532 // Check whether we have ever pruned block & undo files
3533 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3534 if (fHavePruned)
3535 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3537 // Check whether we need to continue reindexing
3538 bool fReindexing = false;
3539 pblocktree->ReadReindexing(fReindexing);
3540 if(fReindexing) fReindex = true;
3542 // Check whether we have a transaction index
3543 pblocktree->ReadFlag("txindex", fTxIndex);
3544 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3546 return true;
3549 bool LoadChainTip(const CChainParams& chainparams)
3551 if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
3553 if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
3554 // In case we just added the genesis block, connect it now, so
3555 // that we always have a chainActive.Tip() when we return.
3556 LogPrintf("%s: Connecting genesis block...\n", __func__);
3557 CValidationState state;
3558 if (!ActivateBestChain(state, chainparams)) {
3559 return false;
3563 // Load pointer to end of best chain
3564 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3565 if (it == mapBlockIndex.end())
3566 return false;
3567 chainActive.SetTip(it->second);
3569 PruneBlockIndexCandidates();
3571 LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
3572 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3573 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3574 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3575 return true;
3578 CVerifyDB::CVerifyDB()
3580 uiInterface.ShowProgress(_("Verifying blocks..."), 0, false);
3583 CVerifyDB::~CVerifyDB()
3585 uiInterface.ShowProgress("", 100, false);
3588 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3590 LOCK(cs_main);
3591 if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
3592 return true;
3594 // Verify blocks in the best chain
3595 if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height())
3596 nCheckDepth = chainActive.Height();
3597 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3598 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3599 CCoinsViewCache coins(coinsview);
3600 CBlockIndex* pindexState = chainActive.Tip();
3601 CBlockIndex* pindexFailure = nullptr;
3602 int nGoodTransactions = 0;
3603 CValidationState state;
3604 int reportDone = 0;
3605 LogPrintf("[0%%]...");
3606 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3608 boost::this_thread::interruption_point();
3609 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3610 if (reportDone < percentageDone/10) {
3611 // report every 10% step
3612 LogPrintf("[%d%%]...", percentageDone);
3613 reportDone = percentageDone/10;
3615 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false);
3616 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3617 break;
3618 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3619 // If pruning, only go back as far as we have data.
3620 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3621 break;
3623 CBlock block;
3624 // check level 0: read from disk
3625 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3626 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3627 // check level 1: verify block validity
3628 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3629 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3630 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3631 // check level 2: verify undo validity
3632 if (nCheckLevel >= 2 && pindex) {
3633 CBlockUndo undo;
3634 CDiskBlockPos pos = pindex->GetUndoPos();
3635 if (!pos.IsNull()) {
3636 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3637 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3640 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3641 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3642 assert(coins.GetBestBlock() == pindex->GetBlockHash());
3643 DisconnectResult res = DisconnectBlock(block, pindex, coins);
3644 if (res == DISCONNECT_FAILED) {
3645 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3647 pindexState = pindex->pprev;
3648 if (res == DISCONNECT_UNCLEAN) {
3649 nGoodTransactions = 0;
3650 pindexFailure = pindex;
3651 } else {
3652 nGoodTransactions += block.vtx.size();
3655 if (ShutdownRequested())
3656 return true;
3658 if (pindexFailure)
3659 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3661 // check level 4: try reconnecting blocks
3662 if (nCheckLevel >= 4) {
3663 CBlockIndex *pindex = pindexState;
3664 while (pindex != chainActive.Tip()) {
3665 boost::this_thread::interruption_point();
3666 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))), false);
3667 pindex = chainActive.Next(pindex);
3668 CBlock block;
3669 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3670 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3671 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3672 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3676 LogPrintf("[DONE].\n");
3677 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3679 return true;
3682 /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
3683 static bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
3685 // TODO: merge with ConnectBlock
3686 CBlock block;
3687 if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
3688 return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3691 for (const CTransactionRef& tx : block.vtx) {
3692 if (!tx->IsCoinBase()) {
3693 for (const CTxIn &txin : tx->vin) {
3694 inputs.SpendCoin(txin.prevout);
3697 // Pass check = true as every addition may be an overwrite.
3698 AddCoins(inputs, *tx, pindex->nHeight, true);
3700 return true;
3703 bool ReplayBlocks(const CChainParams& params, CCoinsView* view)
3705 LOCK(cs_main);
3707 CCoinsViewCache cache(view);
3709 std::vector<uint256> hashHeads = view->GetHeadBlocks();
3710 if (hashHeads.empty()) return true; // We're already in a consistent state.
3711 if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
3713 uiInterface.ShowProgress(_("Replaying blocks..."), 0, false);
3714 LogPrintf("Replaying blocks\n");
3716 const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
3717 const CBlockIndex* pindexNew; // New tip during the interrupted flush.
3718 const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
3720 if (mapBlockIndex.count(hashHeads[0]) == 0) {
3721 return error("ReplayBlocks(): reorganization to unknown block requested");
3723 pindexNew = mapBlockIndex[hashHeads[0]];
3725 if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
3726 if (mapBlockIndex.count(hashHeads[1]) == 0) {
3727 return error("ReplayBlocks(): reorganization from unknown block requested");
3729 pindexOld = mapBlockIndex[hashHeads[1]];
3730 pindexFork = LastCommonAncestor(pindexOld, pindexNew);
3731 assert(pindexFork != nullptr);
3734 // Rollback along the old branch.
3735 while (pindexOld != pindexFork) {
3736 if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
3737 CBlock block;
3738 if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
3739 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3741 LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
3742 DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
3743 if (res == DISCONNECT_FAILED) {
3744 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3746 // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
3747 // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
3748 // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
3749 // the result is still a version of the UTXO set with the effects of that block undone.
3751 pindexOld = pindexOld->pprev;
3754 // Roll forward from the forking point to the new tip.
3755 int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
3756 for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
3757 const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
3758 LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
3759 if (!RollforwardBlock(pindex, cache, params)) return false;
3762 cache.SetBestBlock(pindexNew->GetBlockHash());
3763 cache.Flush();
3764 uiInterface.ShowProgress("", 100, false);
3765 return true;
3768 bool RewindBlockIndex(const CChainParams& params)
3770 LOCK(cs_main);
3772 // Note that during -reindex-chainstate we are called with an empty chainActive!
3774 int nHeight = 1;
3775 while (nHeight <= chainActive.Height()) {
3776 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3777 break;
3779 nHeight++;
3782 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3783 CValidationState state;
3784 CBlockIndex* pindex = chainActive.Tip();
3785 while (chainActive.Height() >= nHeight) {
3786 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3787 // If pruning, don't try rewinding past the HAVE_DATA point;
3788 // since older blocks can't be served anyway, there's
3789 // no need to walk further, and trying to DisconnectTip()
3790 // will fail (and require a needless reindex/redownload
3791 // of the blockchain).
3792 break;
3794 if (!DisconnectTip(state, params, nullptr)) {
3795 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3797 // Occasionally flush state to disk.
3798 if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
3799 return false;
3802 // Reduce validity flag and have-data flags.
3803 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3804 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3805 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3806 CBlockIndex* pindexIter = it->second;
3808 // Note: If we encounter an insufficiently validated block that
3809 // is on chainActive, it must be because we are a pruning node, and
3810 // this block or some successor doesn't HAVE_DATA, so we were unable to
3811 // rewind all the way. Blocks remaining on chainActive at this point
3812 // must not have their validity reduced.
3813 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3814 // Reduce validity
3815 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3816 // Remove have-data flags.
3817 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3818 // Remove storage location.
3819 pindexIter->nFile = 0;
3820 pindexIter->nDataPos = 0;
3821 pindexIter->nUndoPos = 0;
3822 // Remove various other things
3823 pindexIter->nTx = 0;
3824 pindexIter->nChainTx = 0;
3825 pindexIter->nSequenceId = 0;
3826 // Make sure it gets written.
3827 setDirtyBlockIndex.insert(pindexIter);
3828 // Update indexes
3829 setBlockIndexCandidates.erase(pindexIter);
3830 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3831 while (ret.first != ret.second) {
3832 if (ret.first->second == pindexIter) {
3833 mapBlocksUnlinked.erase(ret.first++);
3834 } else {
3835 ++ret.first;
3838 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3839 setBlockIndexCandidates.insert(pindexIter);
3843 if (chainActive.Tip() != nullptr) {
3844 // We can't prune block index candidates based on our tip if we have
3845 // no tip due to chainActive being empty!
3846 PruneBlockIndexCandidates();
3848 CheckBlockIndex(params.GetConsensus());
3850 // FlushStateToDisk can possibly read chainActive. Be conservative
3851 // and skip it here, we're about to -reindex-chainstate anyway, so
3852 // it'll get called a bunch real soon.
3853 if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
3854 return false;
3858 return true;
3861 // May NOT be used after any connections are up as much
3862 // of the peer-processing logic assumes a consistent
3863 // block index state
3864 void UnloadBlockIndex()
3866 LOCK(cs_main);
3867 setBlockIndexCandidates.clear();
3868 chainActive.SetTip(nullptr);
3869 pindexBestInvalid = nullptr;
3870 pindexBestHeader = nullptr;
3871 mempool.clear();
3872 mapBlocksUnlinked.clear();
3873 vinfoBlockFile.clear();
3874 nLastBlockFile = 0;
3875 nBlockSequenceId = 1;
3876 setDirtyBlockIndex.clear();
3877 setDirtyFileInfo.clear();
3878 versionbitscache.Clear();
3879 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3880 warningcache[b].clear();
3883 for (BlockMap::value_type& entry : mapBlockIndex) {
3884 delete entry.second;
3886 mapBlockIndex.clear();
3887 fHavePruned = false;
3890 bool LoadBlockIndex(const CChainParams& chainparams)
3892 // Load block index from databases
3893 bool needs_init = fReindex;
3894 if (!fReindex) {
3895 bool ret = LoadBlockIndexDB(chainparams);
3896 if (!ret) return false;
3897 needs_init = mapBlockIndex.empty();
3900 if (needs_init) {
3901 // Everything here is for *new* reindex/DBs. Thus, though
3902 // LoadBlockIndexDB may have set fReindex if we shut down
3903 // mid-reindex previously, we don't check fReindex and
3904 // instead only check it prior to LoadBlockIndexDB to set
3905 // needs_init.
3907 LogPrintf("Initializing databases...\n");
3908 // Use the provided setting for -txindex in the new database
3909 fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
3910 pblocktree->WriteFlag("txindex", fTxIndex);
3912 return true;
3915 bool LoadGenesisBlock(const CChainParams& chainparams)
3917 LOCK(cs_main);
3919 // Check whether we're already initialized by checking for genesis in
3920 // mapBlockIndex. Note that we can't use chainActive here, since it is
3921 // set based on the coins db, not the block index db, which is the only
3922 // thing loaded at this point.
3923 if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
3924 return true;
3926 try {
3927 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3928 // Start new block file
3929 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3930 CDiskBlockPos blockPos;
3931 CValidationState state;
3932 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3933 return error("%s: FindBlockPos failed", __func__);
3934 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3935 return error("%s: writing genesis block to disk failed", __func__);
3936 CBlockIndex *pindex = AddToBlockIndex(block);
3937 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3938 return error("%s: genesis block not accepted", __func__);
3939 } catch (const std::runtime_error& e) {
3940 return error("%s: failed to write genesis block: %s", __func__, e.what());
3943 return true;
3946 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
3948 // Map of disk positions for blocks with unknown parent (only used for reindex)
3949 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3950 int64_t nStart = GetTimeMillis();
3952 int nLoaded = 0;
3953 try {
3954 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3955 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
3956 uint64_t nRewind = blkdat.GetPos();
3957 while (!blkdat.eof()) {
3958 boost::this_thread::interruption_point();
3960 blkdat.SetPos(nRewind);
3961 nRewind++; // start one byte further next time, in case of failure
3962 blkdat.SetLimit(); // remove former limit
3963 unsigned int nSize = 0;
3964 try {
3965 // locate a header
3966 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
3967 blkdat.FindByte(chainparams.MessageStart()[0]);
3968 nRewind = blkdat.GetPos()+1;
3969 blkdat >> FLATDATA(buf);
3970 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
3971 continue;
3972 // read size
3973 blkdat >> nSize;
3974 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3975 continue;
3976 } catch (const std::exception&) {
3977 // no valid block header found; don't complain
3978 break;
3980 try {
3981 // read block
3982 uint64_t nBlockPos = blkdat.GetPos();
3983 if (dbp)
3984 dbp->nPos = nBlockPos;
3985 blkdat.SetLimit(nBlockPos + nSize);
3986 blkdat.SetPos(nBlockPos);
3987 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3988 CBlock& block = *pblock;
3989 blkdat >> block;
3990 nRewind = blkdat.GetPos();
3992 // detect out of order blocks, and store them for later
3993 uint256 hash = block.GetHash();
3994 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3995 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3996 block.hashPrevBlock.ToString());
3997 if (dbp)
3998 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3999 continue;
4002 // process in case the block isn't known yet
4003 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4004 LOCK(cs_main);
4005 CValidationState state;
4006 if (AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
4007 nLoaded++;
4008 if (state.IsError())
4009 break;
4010 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4011 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4014 // Activate the genesis block so normal node progress can continue
4015 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
4016 CValidationState state;
4017 if (!ActivateBestChain(state, chainparams)) {
4018 break;
4022 NotifyHeaderTip();
4024 // Recursively process earlier encountered successors of this block
4025 std::deque<uint256> queue;
4026 queue.push_back(hash);
4027 while (!queue.empty()) {
4028 uint256 head = queue.front();
4029 queue.pop_front();
4030 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4031 while (range.first != range.second) {
4032 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4033 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4034 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
4036 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4037 head.ToString());
4038 LOCK(cs_main);
4039 CValidationState dummy;
4040 if (AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
4042 nLoaded++;
4043 queue.push_back(pblockrecursive->GetHash());
4046 range.first++;
4047 mapBlocksUnknownParent.erase(it);
4048 NotifyHeaderTip();
4051 } catch (const std::exception& e) {
4052 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4055 } catch (const std::runtime_error& e) {
4056 AbortNode(std::string("System error: ") + e.what());
4058 if (nLoaded > 0)
4059 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4060 return nLoaded > 0;
4063 void static CheckBlockIndex(const Consensus::Params& consensusParams)
4065 if (!fCheckBlockIndex) {
4066 return;
4069 LOCK(cs_main);
4071 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4072 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4073 // iterating the block tree require that chainActive has been initialized.)
4074 if (chainActive.Height() < 0) {
4075 assert(mapBlockIndex.size() <= 1);
4076 return;
4079 // Build forward-pointing map of the entire block tree.
4080 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4081 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4082 forward.insert(std::make_pair(it->second->pprev, it->second));
4085 assert(forward.size() == mapBlockIndex.size());
4087 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4088 CBlockIndex *pindex = rangeGenesis.first->second;
4089 rangeGenesis.first++;
4090 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4092 // Iterate over the entire block tree, using depth-first search.
4093 // Along the way, remember whether there are blocks on the path from genesis
4094 // block being explored which are the first to have certain properties.
4095 size_t nNodes = 0;
4096 int nHeight = 0;
4097 CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4098 CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4099 CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4100 CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4101 CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4102 CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4103 CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4104 while (pindex != nullptr) {
4105 nNodes++;
4106 if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4107 if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4108 if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4109 if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4110 if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4111 if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4112 if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4114 // Begin: actual consistency checks.
4115 if (pindex->pprev == nullptr) {
4116 // Genesis block checks.
4117 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4118 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4120 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)
4121 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4122 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4123 if (!fHavePruned) {
4124 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4125 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4126 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4127 } else {
4128 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4129 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4131 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4132 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4133 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4134 assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4135 assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
4136 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4137 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.
4138 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4139 assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
4140 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4141 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4142 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4143 if (pindexFirstInvalid == nullptr) {
4144 // Checks for not-invalid blocks.
4145 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4147 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
4148 if (pindexFirstInvalid == nullptr) {
4149 // If this block sorts at least as good as the current tip and
4150 // is valid and we have all data for its parents, it must be in
4151 // setBlockIndexCandidates. chainActive.Tip() must also be there
4152 // even if some data has been pruned.
4153 if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
4154 assert(setBlockIndexCandidates.count(pindex));
4156 // If some parent is missing, then it could be that this block was in
4157 // setBlockIndexCandidates but had to be removed because of the missing data.
4158 // In this case it must be in mapBlocksUnlinked -- see test below.
4160 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4161 assert(setBlockIndexCandidates.count(pindex) == 0);
4163 // Check whether this block is in mapBlocksUnlinked.
4164 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4165 bool foundInUnlinked = false;
4166 while (rangeUnlinked.first != rangeUnlinked.second) {
4167 assert(rangeUnlinked.first->first == pindex->pprev);
4168 if (rangeUnlinked.first->second == pindex) {
4169 foundInUnlinked = true;
4170 break;
4172 rangeUnlinked.first++;
4174 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4175 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4176 assert(foundInUnlinked);
4178 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4179 if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4180 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4181 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4182 assert(fHavePruned); // We must have pruned.
4183 // This block may have entered mapBlocksUnlinked if:
4184 // - it has a descendant that at some point had more work than the
4185 // tip, and
4186 // - we tried switching to that descendant but were missing
4187 // data for some intermediate block between chainActive and the
4188 // tip.
4189 // So if this block is itself better than chainActive.Tip() and it wasn't in
4190 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4191 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4192 if (pindexFirstInvalid == nullptr) {
4193 assert(foundInUnlinked);
4197 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4198 // End: actual consistency checks.
4200 // Try descending into the first subnode.
4201 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4202 if (range.first != range.second) {
4203 // A subnode was found.
4204 pindex = range.first->second;
4205 nHeight++;
4206 continue;
4208 // This is a leaf node.
4209 // Move upwards until we reach a node of which we have not yet visited the last child.
4210 while (pindex) {
4211 // We are going to either move to a parent or a sibling of pindex.
4212 // If pindex was the first with a certain property, unset the corresponding variable.
4213 if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4214 if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4215 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4216 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4217 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4218 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4219 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4220 // Find our parent.
4221 CBlockIndex* pindexPar = pindex->pprev;
4222 // Find which child we just visited.
4223 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4224 while (rangePar.first->second != pindex) {
4225 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4226 rangePar.first++;
4228 // Proceed to the next one.
4229 rangePar.first++;
4230 if (rangePar.first != rangePar.second) {
4231 // Move to the sibling.
4232 pindex = rangePar.first->second;
4233 break;
4234 } else {
4235 // Move up further.
4236 pindex = pindexPar;
4237 nHeight--;
4238 continue;
4243 // Check that we actually traversed the entire map.
4244 assert(nNodes == forward.size());
4247 std::string CBlockFileInfo::ToString() const
4249 return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast));
4252 CBlockFileInfo* GetBlockFileInfo(size_t n)
4254 LOCK(cs_LastBlockFile);
4256 return &vinfoBlockFile.at(n);
4259 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
4261 LOCK(cs_main);
4262 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4265 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
4267 LOCK(cs_main);
4268 return VersionBitsStatistics(chainActive.Tip(), params, pos);
4271 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
4273 LOCK(cs_main);
4274 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
4277 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4279 bool LoadMempool(void)
4281 const CChainParams& chainparams = Params();
4282 int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4283 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4284 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4285 if (file.IsNull()) {
4286 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4287 return false;
4290 int64_t count = 0;
4291 int64_t skipped = 0;
4292 int64_t failed = 0;
4293 int64_t nNow = GetTime();
4295 try {
4296 uint64_t version;
4297 file >> version;
4298 if (version != MEMPOOL_DUMP_VERSION) {
4299 return false;
4301 uint64_t num;
4302 file >> num;
4303 while (num--) {
4304 CTransactionRef tx;
4305 int64_t nTime;
4306 int64_t nFeeDelta;
4307 file >> tx;
4308 file >> nTime;
4309 file >> nFeeDelta;
4311 CAmount amountdelta = nFeeDelta;
4312 if (amountdelta) {
4313 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4315 CValidationState state;
4316 if (nTime + nExpiryTimeout > nNow) {
4317 LOCK(cs_main);
4318 AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, nullptr /* pfMissingInputs */, nTime,
4319 nullptr /* plTxnReplaced */, false /* bypass_limits */, 0 /* nAbsurdFee */);
4320 if (state.IsValid()) {
4321 ++count;
4322 } else {
4323 ++failed;
4325 } else {
4326 ++skipped;
4328 if (ShutdownRequested())
4329 return false;
4331 std::map<uint256, CAmount> mapDeltas;
4332 file >> mapDeltas;
4334 for (const auto& i : mapDeltas) {
4335 mempool.PrioritiseTransaction(i.first, i.second);
4337 } catch (const std::exception& e) {
4338 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4339 return false;
4342 LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
4343 return true;
4346 bool DumpMempool(void)
4348 int64_t start = GetTimeMicros();
4350 std::map<uint256, CAmount> mapDeltas;
4351 std::vector<TxMempoolInfo> vinfo;
4354 LOCK(mempool.cs);
4355 for (const auto &i : mempool.mapDeltas) {
4356 mapDeltas[i.first] = i.second;
4358 vinfo = mempool.infoAll();
4361 int64_t mid = GetTimeMicros();
4363 try {
4364 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4365 if (!filestr) {
4366 return false;
4369 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4371 uint64_t version = MEMPOOL_DUMP_VERSION;
4372 file << version;
4374 file << (uint64_t)vinfo.size();
4375 for (const auto& i : vinfo) {
4376 file << *(i.tx);
4377 file << (int64_t)i.nTime;
4378 file << (int64_t)i.nFeeDelta;
4379 mapDeltas.erase(i.tx->GetHash());
4382 file << mapDeltas;
4383 FileCommit(file.Get());
4384 file.fclose();
4385 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4386 int64_t last = GetTimeMicros();
4387 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
4388 } catch (const std::exception& e) {
4389 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4390 return false;
4392 return true;
4395 //! Guess how far we are in the verification process at the given block index
4396 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4397 if (pindex == nullptr)
4398 return 0.0;
4400 int64_t nNow = time(nullptr);
4402 double fTxTotal;
4404 if (pindex->nChainTx <= data.nTxCount) {
4405 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4406 } else {
4407 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4410 return pindex->nChainTx / fTxTotal;
4413 class CMainCleanup
4415 public:
4416 CMainCleanup() {}
4417 ~CMainCleanup() {
4418 // block headers
4419 BlockMap::iterator it1 = mapBlockIndex.begin();
4420 for (; it1 != mapBlockIndex.end(); it1++)
4421 delete (*it1).second;
4422 mapBlockIndex.clear();
4424 } instance_of_cmaincleanup;