Remove redundant nullptr checks before deallocation
[bitcoinplatinum.git] / src / validation.cpp
blob8bd23a0f1d721d32f248f7ff80adee3910bf5174
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 /**
57 * Global state
60 CCriticalSection cs_main;
62 BlockMap mapBlockIndex;
63 CChain chainActive;
64 CBlockIndex *pindexBestHeader = nullptr;
65 CWaitableCriticalSection csBestBlock;
66 CConditionVariable cvBlockChange;
67 int nScriptCheckThreads = 0;
68 std::atomic_bool fImporting(false);
69 bool fReindex = false;
70 bool fTxIndex = false;
71 bool fHavePruned = false;
72 bool fPruneMode = false;
73 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
74 bool fRequireStandard = true;
75 bool fCheckBlockIndex = false;
76 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
77 size_t nCoinCacheUsage = 5000 * 300;
78 uint64_t nPruneTarget = 0;
79 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
80 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
82 uint256 hashAssumeValid;
84 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
85 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
87 CBlockPolicyEstimator feeEstimator;
88 CTxMemPool mempool(&feeEstimator);
90 static void CheckBlockIndex(const Consensus::Params& consensusParams);
92 /** Constant stuff for coinbase transactions we create: */
93 CScript COINBASE_FLAGS;
95 const std::string strMessageMagic = "Bitcoin Signed Message:\n";
97 // Internal stuff
98 namespace {
100 struct CBlockIndexWorkComparator
102 bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
103 // First sort by most total work, ...
104 if (pa->nChainWork > pb->nChainWork) return false;
105 if (pa->nChainWork < pb->nChainWork) return true;
107 // ... then by earliest time received, ...
108 if (pa->nSequenceId < pb->nSequenceId) return false;
109 if (pa->nSequenceId > pb->nSequenceId) return true;
111 // Use pointer address as tie breaker (should only happen with blocks
112 // loaded from disk, as those all have id 0).
113 if (pa < pb) return false;
114 if (pa > pb) return true;
116 // Identical blocks.
117 return false;
121 CBlockIndex *pindexBestInvalid;
124 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
125 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
126 * missing the data for the block.
128 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
129 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
130 * Pruned nodes may have entries where B is missing data.
132 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
134 CCriticalSection cs_LastBlockFile;
135 std::vector<CBlockFileInfo> vinfoBlockFile;
136 int nLastBlockFile = 0;
137 /** Global flag to indicate we should check to see if there are
138 * block/undo files that should be deleted. Set on startup
139 * or if we allocate more file space when we're in prune mode
141 bool fCheckForPruning = false;
144 * Every received block is assigned a unique and increasing identifier, so we
145 * know which one to give priority in case of a fork.
147 CCriticalSection cs_nBlockSequenceId;
148 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
149 int32_t nBlockSequenceId = 1;
150 /** Decreasing counter (used by subsequent preciousblock calls). */
151 int32_t nBlockReverseSequenceId = -1;
152 /** chainwork for the last block that preciousblock has been applied to. */
153 arith_uint256 nLastPreciousChainwork = 0;
155 /** Dirty block index entries. */
156 std::set<CBlockIndex*> setDirtyBlockIndex;
158 /** Dirty block file entries. */
159 std::set<int> setDirtyFileInfo;
160 } // anon namespace
162 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
164 // Find the first block the caller has in the main chain
165 for (const uint256& hash : locator.vHave) {
166 BlockMap::iterator mi = mapBlockIndex.find(hash);
167 if (mi != mapBlockIndex.end())
169 CBlockIndex* pindex = (*mi).second;
170 if (chain.Contains(pindex))
171 return pindex;
172 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
173 return chain.Tip();
177 return chain.Genesis();
180 CCoinsViewDB *pcoinsdbview = nullptr;
181 CCoinsViewCache *pcoinsTip = nullptr;
182 CBlockTreeDB *pblocktree = nullptr;
184 enum FlushStateMode {
185 FLUSH_STATE_NONE,
186 FLUSH_STATE_IF_NEEDED,
187 FLUSH_STATE_PERIODIC,
188 FLUSH_STATE_ALWAYS
191 // See definition for documentation
192 static bool FlushStateToDisk(const CChainParams& chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
193 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
194 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
195 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);
196 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
198 bool CheckFinalTx(const CTransaction &tx, int flags)
200 AssertLockHeld(cs_main);
202 // By convention a negative value for flags indicates that the
203 // current network-enforced consensus rules should be used. In
204 // a future soft-fork scenario that would mean checking which
205 // rules would be enforced for the next block and setting the
206 // appropriate flags. At the present time no soft-forks are
207 // scheduled, so no flags are set.
208 flags = std::max(flags, 0);
210 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
211 // nLockTime because when IsFinalTx() is called within
212 // CBlock::AcceptBlock(), the height of the block *being*
213 // evaluated is what is used. Thus if we want to know if a
214 // transaction can be part of the *next* block, we need to call
215 // IsFinalTx() with one more than chainActive.Height().
216 const int nBlockHeight = chainActive.Height() + 1;
218 // BIP113 will require that time-locked transactions have nLockTime set to
219 // less than the median time of the previous block they're contained in.
220 // When the next block is created its previous block will be the current
221 // chain tip, so we use that to calculate the median time passed to
222 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
223 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
224 ? chainActive.Tip()->GetMedianTimePast()
225 : GetAdjustedTime();
227 return IsFinalTx(tx, nBlockHeight, nBlockTime);
230 bool TestLockPointValidity(const LockPoints* lp)
232 AssertLockHeld(cs_main);
233 assert(lp);
234 // If there are relative lock times then the maxInputBlock will be set
235 // If there are no relative lock times, the LockPoints don't depend on the chain
236 if (lp->maxInputBlock) {
237 // Check whether chainActive is an extension of the block at which the LockPoints
238 // calculation was valid. If not LockPoints are no longer valid
239 if (!chainActive.Contains(lp->maxInputBlock)) {
240 return false;
244 // LockPoints still valid
245 return true;
248 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
250 AssertLockHeld(cs_main);
251 AssertLockHeld(mempool.cs);
253 CBlockIndex* tip = chainActive.Tip();
254 CBlockIndex index;
255 index.pprev = tip;
256 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
257 // height based locks because when SequenceLocks() is called within
258 // ConnectBlock(), the height of the block *being*
259 // evaluated is what is used.
260 // Thus if we want to know if a transaction can be part of the
261 // *next* block, we need to use one more than chainActive.Height()
262 index.nHeight = tip->nHeight + 1;
264 std::pair<int, int64_t> lockPair;
265 if (useExistingLockPoints) {
266 assert(lp);
267 lockPair.first = lp->height;
268 lockPair.second = lp->time;
270 else {
271 // pcoinsTip contains the UTXO set for chainActive.Tip()
272 CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
273 std::vector<int> prevheights;
274 prevheights.resize(tx.vin.size());
275 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
276 const CTxIn& txin = tx.vin[txinIndex];
277 Coin coin;
278 if (!viewMemPool.GetCoin(txin.prevout, coin)) {
279 return error("%s: Missing input", __func__);
281 if (coin.nHeight == MEMPOOL_HEIGHT) {
282 // Assume all mempool transaction confirm in the next block
283 prevheights[txinIndex] = tip->nHeight + 1;
284 } else {
285 prevheights[txinIndex] = coin.nHeight;
288 lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
289 if (lp) {
290 lp->height = lockPair.first;
291 lp->time = lockPair.second;
292 // Also store the hash of the block with the highest height of
293 // all the blocks which have sequence locked prevouts.
294 // This hash needs to still be on the chain
295 // for these LockPoint calculations to be valid
296 // Note: It is impossible to correctly calculate a maxInputBlock
297 // if any of the sequence locked inputs depend on unconfirmed txs,
298 // except in the special case where the relative lock time/height
299 // is 0, which is equivalent to no sequence lock. Since we assume
300 // input height of tip+1 for mempool txs and test the resulting
301 // lockPair from CalculateSequenceLocks against tip+1. We know
302 // EvaluateSequenceLocks will fail if there was a non-zero sequence
303 // lock on a mempool input, so we can use the return value of
304 // CheckSequenceLocks to indicate the LockPoints validity
305 int maxInputHeight = 0;
306 for (int height : prevheights) {
307 // Can ignore mempool inputs since we'll fail if they had non-zero locks
308 if (height != tip->nHeight+1) {
309 maxInputHeight = std::max(maxInputHeight, height);
312 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
315 return EvaluateSequenceLocks(index, lockPair);
318 // Returns the script flags which should be checked for a given block
319 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
321 static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
322 int expired = pool.Expire(GetTime() - age);
323 if (expired != 0) {
324 LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
327 std::vector<COutPoint> vNoSpendsRemaining;
328 pool.TrimToSize(limit, &vNoSpendsRemaining);
329 for (const COutPoint& removed : vNoSpendsRemaining)
330 pcoinsTip->Uncache(removed);
333 /** Convert CValidationState to a human-readable message for logging */
334 std::string FormatStateMessage(const CValidationState &state)
336 return strprintf("%s%s (code %i)",
337 state.GetRejectReason(),
338 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
339 state.GetRejectCode());
342 static bool IsCurrentForFeeEstimation()
344 AssertLockHeld(cs_main);
345 if (IsInitialBlockDownload())
346 return false;
347 if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
348 return false;
349 if (chainActive.Height() < pindexBestHeader->nHeight - 1)
350 return false;
351 return true;
354 /* Make mempool consistent after a reorg, by re-adding or recursively erasing
355 * disconnected block transactions from the mempool, and also removing any
356 * other transactions from the mempool that are no longer valid given the new
357 * tip/height.
359 * Note: we assume that disconnectpool only contains transactions that are NOT
360 * confirmed in the current chain nor already in the mempool (otherwise,
361 * in-mempool descendants of such transactions would be removed).
363 * Passing fAddToMempool=false will skip trying to add the transactions back,
364 * and instead just erase from the mempool as needed.
367 void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
369 AssertLockHeld(cs_main);
370 std::vector<uint256> vHashUpdate;
371 // disconnectpool's insertion_order index sorts the entries from
372 // oldest to newest, but the oldest entry will be the last tx from the
373 // latest mined block that was disconnected.
374 // Iterate disconnectpool in reverse, so that we add transactions
375 // back to the mempool starting with the earliest transaction that had
376 // been previously seen in a block.
377 auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
378 while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
379 // ignore validation errors in resurrected transactions
380 CValidationState stateDummy;
381 if (!fAddToMempool || (*it)->IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, *it, false, nullptr, nullptr, true)) {
382 // If the transaction doesn't make it in to the mempool, remove any
383 // transactions that depend on it (which would now be orphans).
384 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
385 } else if (mempool.exists((*it)->GetHash())) {
386 vHashUpdate.push_back((*it)->GetHash());
388 ++it;
390 disconnectpool.queuedTx.clear();
391 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
392 // no in-mempool children, which is generally not true when adding
393 // previously-confirmed transactions back to the mempool.
394 // UpdateTransactionsFromBlock finds descendants of any transactions in
395 // the disconnectpool that were added back and cleans up the mempool state.
396 mempool.UpdateTransactionsFromBlock(vHashUpdate);
398 // We also need to remove any now-immature transactions
399 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
400 // Re-limit mempool size, in case we added any transactions
401 LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
404 // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
405 // were somehow broken and returning the wrong scriptPubKeys
406 static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool& pool,
407 unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) {
408 AssertLockHeld(cs_main);
410 // pool.cs should be locked already, but go ahead and re-take the lock here
411 // to enforce that mempool doesn't change between when we check the view
412 // and when we actually call through to CheckInputs
413 LOCK(pool.cs);
415 assert(!tx.IsCoinBase());
416 for (const CTxIn& txin : tx.vin) {
417 const Coin& coin = view.AccessCoin(txin.prevout);
419 // At this point we haven't actually checked if the coins are all
420 // available (or shouldn't assume we have, since CheckInputs does).
421 // So we just return failure if the inputs are not available here,
422 // and then only have to check equivalence for available inputs.
423 if (coin.IsSpent()) return false;
425 const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
426 if (txFrom) {
427 assert(txFrom->GetHash() == txin.prevout.hash);
428 assert(txFrom->vout.size() > txin.prevout.n);
429 assert(txFrom->vout[txin.prevout.n] == coin.out);
430 } else {
431 const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout);
432 assert(!coinFromDisk.IsSpent());
433 assert(coinFromDisk.out == coin.out);
437 return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata);
440 static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool fLimitFree,
441 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
442 bool fOverrideMempoolLimit, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache)
444 const CTransaction& tx = *ptx;
445 const uint256 hash = tx.GetHash();
446 AssertLockHeld(cs_main);
447 if (pfMissingInputs)
448 *pfMissingInputs = false;
450 if (!CheckTransaction(tx, state))
451 return false; // state filled in by CheckTransaction
453 // Coinbase is only valid in a block, not as a loose transaction
454 if (tx.IsCoinBase())
455 return state.DoS(100, false, REJECT_INVALID, "coinbase");
457 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
458 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), chainparams.GetConsensus());
459 if (!gArgs.GetBoolArg("-prematurewitness", false) && tx.HasWitness() && !witnessEnabled) {
460 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
463 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
464 std::string reason;
465 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
466 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
468 // Only accept nLockTime-using transactions that can be mined in the next
469 // block; we don't want our mempool filled up with transactions that can't
470 // be mined yet.
471 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
472 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
474 // is it already in the memory pool?
475 if (pool.exists(hash)) {
476 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool");
479 // Check for conflicts with in-memory transactions
480 std::set<uint256> setConflicts;
482 LOCK(pool.cs); // protect pool.mapNextTx
483 for (const CTxIn &txin : tx.vin)
485 auto itConflicting = pool.mapNextTx.find(txin.prevout);
486 if (itConflicting != pool.mapNextTx.end())
488 const CTransaction *ptxConflicting = itConflicting->second;
489 if (!setConflicts.count(ptxConflicting->GetHash()))
491 // Allow opt-out of transaction replacement by setting
492 // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
494 // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
495 // non-replaceable transactions. All inputs rather than just one
496 // is for the sake of multi-party protocols, where we don't
497 // want a single party to be able to disable replacement.
499 // The opt-out ignores descendants as anyone relying on
500 // first-seen mempool behavior should be checking all
501 // unconfirmed ancestors anyway; doing otherwise is hopelessly
502 // insecure.
503 bool fReplacementOptOut = true;
504 if (fEnableReplacement)
506 for (const CTxIn &_txin : ptxConflicting->vin)
508 if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
510 fReplacementOptOut = false;
511 break;
515 if (fReplacementOptOut) {
516 return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict");
519 setConflicts.insert(ptxConflicting->GetHash());
526 CCoinsView dummy;
527 CCoinsViewCache view(&dummy);
529 CAmount nValueIn = 0;
530 LockPoints lp;
532 LOCK(pool.cs);
533 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
534 view.SetBackend(viewMemPool);
536 // do all inputs exist?
537 for (const CTxIn txin : tx.vin) {
538 if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
539 coins_to_uncache.push_back(txin.prevout);
541 if (!view.HaveCoin(txin.prevout)) {
542 // Are inputs missing because we already have the tx?
543 for (size_t out = 0; out < tx.vout.size(); out++) {
544 // Optimistically just do efficient check of cache for outputs
545 if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
546 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
549 // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
550 if (pfMissingInputs) {
551 *pfMissingInputs = true;
553 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
557 // Bring the best block into scope
558 view.GetBestBlock();
560 nValueIn = view.GetValueIn(tx);
562 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
563 view.SetBackend(dummy);
565 // Only accept BIP68 sequence locked transactions that can be mined in the next
566 // block; we don't want our mempool filled up with transactions that can't
567 // be mined yet.
568 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
569 // CoinsViewCache instead of create its own
570 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
571 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
574 // Check for non-standard pay-to-script-hash in inputs
575 if (fRequireStandard && !AreInputsStandard(tx, view))
576 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
578 // Check for non-standard witness in P2WSH
579 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
580 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
582 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
584 CAmount nValueOut = tx.GetValueOut();
585 CAmount nFees = nValueIn-nValueOut;
586 // nModifiedFees includes any fee deltas from PrioritiseTransaction
587 CAmount nModifiedFees = nFees;
588 pool.ApplyDelta(hash, nModifiedFees);
590 // Keep track of transactions that spend a coinbase, which we re-scan
591 // during reorgs to ensure COINBASE_MATURITY is still met.
592 bool fSpendsCoinbase = false;
593 for (const CTxIn &txin : tx.vin) {
594 const Coin &coin = view.AccessCoin(txin.prevout);
595 if (coin.IsCoinBase()) {
596 fSpendsCoinbase = true;
597 break;
601 CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
602 fSpendsCoinbase, nSigOpsCost, lp);
603 unsigned int nSize = entry.GetTxSize();
605 // Check that the transaction doesn't have an excessive number of
606 // sigops, making it impossible to mine. Since the coinbase transaction
607 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
608 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
609 // merely non-standard transaction.
610 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
611 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
612 strprintf("%d", nSigOpsCost));
614 CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
615 if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
616 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
619 // No transactions are allowed below minRelayTxFee except from disconnected blocks
620 if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
621 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
624 if (nAbsurdFee && nFees > nAbsurdFee)
625 return state.Invalid(false,
626 REJECT_HIGHFEE, "absurdly-high-fee",
627 strprintf("%d > %d", nFees, nAbsurdFee));
629 // Calculate in-mempool ancestors, up to a limit.
630 CTxMemPool::setEntries setAncestors;
631 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
632 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
633 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
634 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
635 std::string errString;
636 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
637 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
640 // A transaction that spends outputs that would be replaced by it is invalid. Now
641 // that we have the set of all ancestors we can detect this
642 // pathological case by making sure setConflicts and setAncestors don't
643 // intersect.
644 for (CTxMemPool::txiter ancestorIt : setAncestors)
646 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
647 if (setConflicts.count(hashAncestor))
649 return state.DoS(10, false,
650 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
651 strprintf("%s spends conflicting transaction %s",
652 hash.ToString(),
653 hashAncestor.ToString()));
657 // Check if it's economically rational to mine this transaction rather
658 // than the ones it replaces.
659 CAmount nConflictingFees = 0;
660 size_t nConflictingSize = 0;
661 uint64_t nConflictingCount = 0;
662 CTxMemPool::setEntries allConflicting;
664 // If we don't hold the lock allConflicting might be incomplete; the
665 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
666 // mempool consistency for us.
667 LOCK(pool.cs);
668 const bool fReplacementTransaction = setConflicts.size();
669 if (fReplacementTransaction)
671 CFeeRate newFeeRate(nModifiedFees, nSize);
672 std::set<uint256> setConflictsParents;
673 const int maxDescendantsToVisit = 100;
674 CTxMemPool::setEntries setIterConflicting;
675 for (const uint256 &hashConflicting : setConflicts)
677 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
678 if (mi == pool.mapTx.end())
679 continue;
681 // Save these to avoid repeated lookups
682 setIterConflicting.insert(mi);
684 // Don't allow the replacement to reduce the feerate of the
685 // mempool.
687 // We usually don't want to accept replacements with lower
688 // feerates than what they replaced as that would lower the
689 // feerate of the next block. Requiring that the feerate always
690 // be increased is also an easy-to-reason about way to prevent
691 // DoS attacks via replacements.
693 // The mining code doesn't (currently) take children into
694 // account (CPFP) so we only consider the feerates of
695 // transactions being directly replaced, not their indirect
696 // descendants. While that does mean high feerate children are
697 // ignored when deciding whether or not to replace, we do
698 // require the replacement to pay more overall fees too,
699 // mitigating most cases.
700 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
701 if (newFeeRate <= oldFeeRate)
703 return state.DoS(0, false,
704 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
705 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
706 hash.ToString(),
707 newFeeRate.ToString(),
708 oldFeeRate.ToString()));
711 for (const CTxIn &txin : mi->GetTx().vin)
713 setConflictsParents.insert(txin.prevout.hash);
716 nConflictingCount += mi->GetCountWithDescendants();
718 // This potentially overestimates the number of actual descendants
719 // but we just want to be conservative to avoid doing too much
720 // work.
721 if (nConflictingCount <= maxDescendantsToVisit) {
722 // If not too many to replace, then calculate the set of
723 // transactions that would have to be evicted
724 for (CTxMemPool::txiter it : setIterConflicting) {
725 pool.CalculateDescendants(it, allConflicting);
727 for (CTxMemPool::txiter it : allConflicting) {
728 nConflictingFees += it->GetModifiedFee();
729 nConflictingSize += it->GetTxSize();
731 } else {
732 return state.DoS(0, false,
733 REJECT_NONSTANDARD, "too many potential replacements", false,
734 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
735 hash.ToString(),
736 nConflictingCount,
737 maxDescendantsToVisit));
740 for (unsigned int j = 0; j < tx.vin.size(); j++)
742 // We don't want to accept replacements that require low
743 // feerate junk to be mined first. Ideally we'd keep track of
744 // the ancestor feerates and make the decision based on that,
745 // but for now requiring all new inputs to be confirmed works.
746 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
748 // Rather than check the UTXO set - potentially expensive -
749 // it's cheaper to just check if the new input refers to a
750 // tx that's in the mempool.
751 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
752 return state.DoS(0, false,
753 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
754 strprintf("replacement %s adds unconfirmed input, idx %d",
755 hash.ToString(), j));
759 // The replacement must pay greater fees than the transactions it
760 // replaces - if we did the bandwidth used by those conflicting
761 // transactions would not be paid for.
762 if (nModifiedFees < nConflictingFees)
764 return state.DoS(0, false,
765 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
766 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
767 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
770 // Finally in addition to paying more fees than the conflicts the
771 // new transaction must pay for its own bandwidth.
772 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
773 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
775 return state.DoS(0, false,
776 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
777 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
778 hash.ToString(),
779 FormatMoney(nDeltaFees),
780 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
784 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
785 if (!chainparams.RequireStandard()) {
786 scriptVerifyFlags = gArgs.GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
789 // Check against previous transactions
790 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
791 PrecomputedTransactionData txdata(tx);
792 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, txdata)) {
793 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
794 // need to turn both off, and compare against just turning off CLEANSTACK
795 // to see if the failure is specifically due to witness validation.
796 CValidationState stateDummy; // Want reported failures to be from first CheckInputs
797 if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
798 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
799 // Only the witness is missing, so the transaction itself may be fine.
800 state.SetCorruptionPossible();
802 return false; // state filled in by CheckInputs
805 // Check again against the current block tip's script verification
806 // flags to cache our script execution flags. This is, of course,
807 // useless if the next block has different script flags from the
808 // previous one, but because the cache tracks script flags for us it
809 // will auto-invalidate and we'll just have a few blocks of extra
810 // misses on soft-fork activation.
812 // This is also useful in case of bugs in the standard flags that cause
813 // transactions to pass as valid when they're actually invalid. For
814 // instance the STRICTENC flag was incorrectly allowing certain
815 // CHECKSIG NOT scripts to pass, even though they were invalid.
817 // There is a similar check in CreateNewBlock() to prevent creating
818 // invalid blocks (using TestBlockValidity), however allowing such
819 // transactions into the mempool can be exploited as a DoS attack.
820 unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus());
821 if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata))
823 // If we're using promiscuousmempoolflags, we may hit this normally
824 // Check if current block has some flags that scriptVerifyFlags
825 // does not before printing an ominous warning
826 if (!(~scriptVerifyFlags & currentBlockScriptVerifyFlags)) {
827 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against latest-block but not STANDARD flags %s, %s",
828 __func__, hash.ToString(), FormatStateMessage(state));
829 } else {
830 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, false, txdata)) {
831 return error("%s: ConnectInputs failed against MANDATORY but not STANDARD flags due to promiscuous mempool %s, %s",
832 __func__, hash.ToString(), FormatStateMessage(state));
833 } else {
834 LogPrintf("Warning: -promiscuousmempool flags set to not include currently enforced soft forks, this may break mining or otherwise cause instability!\n");
839 // Remove conflicting transactions from the mempool
840 for (const CTxMemPool::txiter it : allConflicting)
842 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
843 it->GetTx().GetHash().ToString(),
844 hash.ToString(),
845 FormatMoney(nModifiedFees - nConflictingFees),
846 (int)nSize - (int)nConflictingSize);
847 if (plTxnReplaced)
848 plTxnReplaced->push_back(it->GetSharedTx());
850 pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
852 // This transaction should only count for fee estimation if it isn't a
853 // BIP 125 replacement transaction (may not be widely supported), the
854 // node is not behind, and the transaction is not dependent on any other
855 // transactions in the mempool.
856 bool validForFeeEstimation = !fReplacementTransaction && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
858 // Store transaction in memory
859 pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
861 // trim mempool and check if tx was trimmed
862 if (!fOverrideMempoolLimit) {
863 LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
864 if (!pool.exists(hash))
865 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
869 GetMainSignals().TransactionAddedToMempool(ptx);
871 return true;
874 /** (try to) add transaction to memory pool with a specified acceptance time **/
875 static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
876 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
877 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
879 std::vector<COutPoint> coins_to_uncache;
880 bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, coins_to_uncache);
881 if (!res) {
882 for (const COutPoint& hashTx : coins_to_uncache)
883 pcoinsTip->Uncache(hashTx);
885 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
886 CValidationState stateDummy;
887 FlushStateToDisk(chainparams, stateDummy, FLUSH_STATE_PERIODIC);
888 return res;
891 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
892 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
893 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
895 const CChainParams& chainparams = Params();
896 return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, fLimitFree, pfMissingInputs, GetTime(), plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee);
899 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
900 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
902 CBlockIndex *pindexSlow = nullptr;
904 LOCK(cs_main);
906 CTransactionRef ptx = mempool.get(hash);
907 if (ptx)
909 txOut = ptx;
910 return true;
913 if (fTxIndex) {
914 CDiskTxPos postx;
915 if (pblocktree->ReadTxIndex(hash, postx)) {
916 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
917 if (file.IsNull())
918 return error("%s: OpenBlockFile failed", __func__);
919 CBlockHeader header;
920 try {
921 file >> header;
922 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
923 file >> txOut;
924 } catch (const std::exception& e) {
925 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
927 hashBlock = header.GetHash();
928 if (txOut->GetHash() != hash)
929 return error("%s: txid mismatch", __func__);
930 return true;
934 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
935 const Coin& coin = AccessByTxid(*pcoinsTip, hash);
936 if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
939 if (pindexSlow) {
940 CBlock block;
941 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
942 for (const auto& tx : block.vtx) {
943 if (tx->GetHash() == hash) {
944 txOut = tx;
945 hashBlock = pindexSlow->GetBlockHash();
946 return true;
952 return false;
960 //////////////////////////////////////////////////////////////////////////////
962 // CBlock and CBlockIndex
965 static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
967 // Open history file to append
968 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
969 if (fileout.IsNull())
970 return error("WriteBlockToDisk: OpenBlockFile failed");
972 // Write index header
973 unsigned int nSize = GetSerializeSize(fileout, block);
974 fileout << FLATDATA(messageStart) << nSize;
976 // Write block
977 long fileOutPos = ftell(fileout.Get());
978 if (fileOutPos < 0)
979 return error("WriteBlockToDisk: ftell failed");
980 pos.nPos = (unsigned int)fileOutPos;
981 fileout << block;
983 return true;
986 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
988 block.SetNull();
990 // Open history file to read
991 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
992 if (filein.IsNull())
993 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
995 // Read block
996 try {
997 filein >> block;
999 catch (const std::exception& e) {
1000 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1003 // Check the header
1004 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1005 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1007 return true;
1010 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1012 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1013 return false;
1014 if (block.GetHash() != pindex->GetBlockHash())
1015 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1016 pindex->ToString(), pindex->GetBlockPos().ToString());
1017 return true;
1020 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1022 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1023 // Force block reward to zero when right shift is undefined.
1024 if (halvings >= 64)
1025 return 0;
1027 CAmount nSubsidy = 50 * COIN;
1028 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1029 nSubsidy >>= halvings;
1030 return nSubsidy;
1033 bool IsInitialBlockDownload()
1035 const CChainParams& chainParams = Params();
1037 // Once this function has returned false, it must remain false.
1038 static std::atomic<bool> latchToFalse{false};
1039 // Optimization: pre-test latch before taking the lock.
1040 if (latchToFalse.load(std::memory_order_relaxed))
1041 return false;
1043 LOCK(cs_main);
1044 if (latchToFalse.load(std::memory_order_relaxed))
1045 return false;
1046 if (fImporting || fReindex)
1047 return true;
1048 if (chainActive.Tip() == nullptr)
1049 return true;
1050 if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork))
1051 return true;
1052 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1053 return true;
1054 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1055 latchToFalse.store(true, std::memory_order_relaxed);
1056 return false;
1059 CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
1061 static void AlertNotify(const std::string& strMessage)
1063 uiInterface.NotifyAlertChanged();
1064 std::string strCmd = gArgs.GetArg("-alertnotify", "");
1065 if (strCmd.empty()) return;
1067 // Alert text should be plain ascii coming from a trusted source, but to
1068 // be safe we first strip anything not in safeChars, then add single quotes around
1069 // the whole string before passing it to the shell:
1070 std::string singleQuote("'");
1071 std::string safeStatus = SanitizeString(strMessage);
1072 safeStatus = singleQuote+safeStatus+singleQuote;
1073 boost::replace_all(strCmd, "%s", safeStatus);
1075 boost::thread t(runCommand, strCmd); // thread runs free
1078 static void CheckForkWarningConditions()
1080 AssertLockHeld(cs_main);
1081 // Before we get past initial download, we cannot reliably alert about forks
1082 // (we assume we don't get stuck on a fork before finishing our initial sync)
1083 if (IsInitialBlockDownload())
1084 return;
1086 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1087 // of our head, drop it
1088 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1089 pindexBestForkTip = nullptr;
1091 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1093 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
1095 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1096 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1097 AlertNotify(warning);
1099 if (pindexBestForkTip && pindexBestForkBase)
1101 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__,
1102 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1103 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1104 SetfLargeWorkForkFound(true);
1106 else
1108 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1109 SetfLargeWorkInvalidChainFound(true);
1112 else
1114 SetfLargeWorkForkFound(false);
1115 SetfLargeWorkInvalidChainFound(false);
1119 static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1121 AssertLockHeld(cs_main);
1122 // If we are on a fork that is sufficiently large, set a warning flag
1123 CBlockIndex* pfork = pindexNewForkTip;
1124 CBlockIndex* plonger = chainActive.Tip();
1125 while (pfork && pfork != plonger)
1127 while (plonger && plonger->nHeight > pfork->nHeight)
1128 plonger = plonger->pprev;
1129 if (pfork == plonger)
1130 break;
1131 pfork = pfork->pprev;
1134 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1135 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1136 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1137 // hash rate operating on the fork.
1138 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1139 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1140 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1141 if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
1142 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1143 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1145 pindexBestForkTip = pindexNewForkTip;
1146 pindexBestForkBase = pfork;
1149 CheckForkWarningConditions();
1152 void static InvalidChainFound(CBlockIndex* pindexNew)
1154 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1155 pindexBestInvalid = pindexNew;
1157 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1158 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1159 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1160 pindexNew->GetBlockTime()));
1161 CBlockIndex *tip = chainActive.Tip();
1162 assert (tip);
1163 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1164 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1165 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1166 CheckForkWarningConditions();
1169 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1170 if (!state.CorruptionPossible()) {
1171 pindex->nStatus |= BLOCK_FAILED_VALID;
1172 setDirtyBlockIndex.insert(pindex);
1173 setBlockIndexCandidates.erase(pindex);
1174 InvalidChainFound(pindex);
1178 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1180 // mark inputs spent
1181 if (!tx.IsCoinBase()) {
1182 txundo.vprevout.reserve(tx.vin.size());
1183 for (const CTxIn &txin : tx.vin) {
1184 txundo.vprevout.emplace_back();
1185 bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1186 assert(is_spent);
1189 // add outputs
1190 AddCoins(inputs, tx, nHeight);
1193 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1195 CTxUndo txundo;
1196 UpdateCoins(tx, inputs, txundo, nHeight);
1199 bool CScriptCheck::operator()() {
1200 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1201 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1202 return VerifyScript(scriptSig, scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), &error);
1205 int GetSpendHeight(const CCoinsViewCache& inputs)
1207 LOCK(cs_main);
1208 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1209 return pindexPrev->nHeight + 1;
1213 static CuckooCache::cache<uint256, SignatureCacheHasher> scriptExecutionCache;
1214 static uint256 scriptExecutionCacheNonce(GetRandHash());
1216 void InitScriptExecutionCache() {
1217 // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1218 // setup_bytes creates the minimum possible cache (2 elements).
1219 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);
1220 size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
1221 LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1222 (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1226 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
1227 * This does not modify the UTXO set.
1229 * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
1230 * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
1231 * not pushed onto pvChecks/run.
1233 * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
1234 * which are matched. This is useful for checking blocks where we will likely never need the cache
1235 * entry again.
1237 * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
1239 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)
1241 if (!tx.IsCoinBase())
1243 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1244 return false;
1246 if (pvChecks)
1247 pvChecks->reserve(tx.vin.size());
1249 // The first loop above does all the inexpensive checks.
1250 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1251 // Helps prevent CPU exhaustion attacks.
1253 // Skip script verification when connecting blocks under the
1254 // assumevalid block. Assuming the assumevalid block is valid this
1255 // is safe because block merkle hashes are still computed and checked,
1256 // Of course, if an assumed valid block is invalid due to false scriptSigs
1257 // this optimization would allow an invalid chain to be accepted.
1258 if (fScriptChecks) {
1259 // First check if script executions have been cached with the same
1260 // flags. Note that this assumes that the inputs provided are
1261 // correct (ie that the transaction hash which is in tx's prevouts
1262 // properly commits to the scriptPubKey in the inputs view of that
1263 // transaction).
1264 uint256 hashCacheEntry;
1265 // We only use the first 19 bytes of nonce to avoid a second SHA
1266 // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
1267 static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
1268 CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1269 AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1270 if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1271 return true;
1274 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1275 const COutPoint &prevout = tx.vin[i].prevout;
1276 const Coin& coin = inputs.AccessCoin(prevout);
1277 assert(!coin.IsSpent());
1279 // We very carefully only pass in things to CScriptCheck which
1280 // are clearly committed to by tx' witness hash. This provides
1281 // a sanity check that our caching is not introducing consensus
1282 // failures through additional data in, eg, the coins being
1283 // spent being checked as a part of CScriptCheck.
1284 const CScript& scriptPubKey = coin.out.scriptPubKey;
1285 const CAmount amount = coin.out.nValue;
1287 // Verify signature
1288 CScriptCheck check(scriptPubKey, amount, tx, i, flags, cacheSigStore, &txdata);
1289 if (pvChecks) {
1290 pvChecks->push_back(CScriptCheck());
1291 check.swap(pvChecks->back());
1292 } else if (!check()) {
1293 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1294 // Check whether the failure was caused by a
1295 // non-mandatory script verification check, such as
1296 // non-standard DER encodings or non-null dummy
1297 // arguments; if so, don't trigger DoS protection to
1298 // avoid splitting the network between upgraded and
1299 // non-upgraded nodes.
1300 CScriptCheck check2(scriptPubKey, amount, tx, i,
1301 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1302 if (check2())
1303 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1305 // Failures of other flags indicate a transaction that is
1306 // invalid in new blocks, e.g. an invalid P2SH. We DoS ban
1307 // such nodes as they are not following the protocol. That
1308 // said during an upgrade careful thought should be taken
1309 // as to the correct behavior - we may want to continue
1310 // peering with non-upgraded nodes even after soft-fork
1311 // super-majority signaling has occurred.
1312 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1316 if (cacheFullScriptStore && !pvChecks) {
1317 // We executed all of the provided scripts, and were told to
1318 // cache the result. Do so now.
1319 scriptExecutionCache.insert(hashCacheEntry);
1324 return true;
1327 namespace {
1329 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1331 // Open history file to append
1332 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1333 if (fileout.IsNull())
1334 return error("%s: OpenUndoFile failed", __func__);
1336 // Write index header
1337 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1338 fileout << FLATDATA(messageStart) << nSize;
1340 // Write undo data
1341 long fileOutPos = ftell(fileout.Get());
1342 if (fileOutPos < 0)
1343 return error("%s: ftell failed", __func__);
1344 pos.nPos = (unsigned int)fileOutPos;
1345 fileout << blockundo;
1347 // calculate & write checksum
1348 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1349 hasher << hashBlock;
1350 hasher << blockundo;
1351 fileout << hasher.GetHash();
1353 return true;
1356 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1358 // Open history file to read
1359 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1360 if (filein.IsNull())
1361 return error("%s: OpenUndoFile failed", __func__);
1363 // Read block
1364 uint256 hashChecksum;
1365 CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1366 try {
1367 verifier << hashBlock;
1368 verifier >> blockundo;
1369 filein >> hashChecksum;
1371 catch (const std::exception& e) {
1372 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1375 // Verify checksum
1376 if (hashChecksum != verifier.GetHash())
1377 return error("%s: Checksum mismatch", __func__);
1379 return true;
1382 /** Abort with a message */
1383 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1385 SetMiscWarning(strMessage);
1386 LogPrintf("*** %s\n", strMessage);
1387 uiInterface.ThreadSafeMessageBox(
1388 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1389 "", CClientUIInterface::MSG_ERROR);
1390 StartShutdown();
1391 return false;
1394 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1396 AbortNode(strMessage, userMessage);
1397 return state.Error(strMessage);
1400 } // namespace
1402 enum DisconnectResult
1404 DISCONNECT_OK, // All good.
1405 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
1406 DISCONNECT_FAILED // Something else went wrong.
1410 * Restore the UTXO in a Coin at a given COutPoint
1411 * @param undo The Coin to be restored.
1412 * @param view The coins view to which to apply the changes.
1413 * @param out The out point that corresponds to the tx input.
1414 * @return A DisconnectResult as an int
1416 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1418 bool fClean = true;
1420 if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1422 if (undo.nHeight == 0) {
1423 // Missing undo metadata (height and coinbase). Older versions included this
1424 // information only in undo records for the last spend of a transactions'
1425 // outputs. This implies that it must be present for some other output of the same tx.
1426 const Coin& alternate = AccessByTxid(view, out.hash);
1427 if (!alternate.IsSpent()) {
1428 undo.nHeight = alternate.nHeight;
1429 undo.fCoinBase = alternate.fCoinBase;
1430 } else {
1431 return DISCONNECT_FAILED; // adding output for transaction without known metadata
1434 // The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
1435 // sure that the coin did not already exist in the cache. As we have queried for that above
1436 // using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
1437 // it is an overwrite.
1438 view.AddCoin(out, std::move(undo), !fClean);
1440 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1443 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1444 * When FAILED is returned, view is left in an indeterminate state. */
1445 static DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1447 bool fClean = true;
1449 CBlockUndo blockUndo;
1450 CDiskBlockPos pos = pindex->GetUndoPos();
1451 if (pos.IsNull()) {
1452 error("DisconnectBlock(): no undo data available");
1453 return DISCONNECT_FAILED;
1455 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) {
1456 error("DisconnectBlock(): failure reading undo data");
1457 return DISCONNECT_FAILED;
1460 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1461 error("DisconnectBlock(): block and undo data inconsistent");
1462 return DISCONNECT_FAILED;
1465 // undo transactions in reverse order
1466 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1467 const CTransaction &tx = *(block.vtx[i]);
1468 uint256 hash = tx.GetHash();
1469 bool is_coinbase = tx.IsCoinBase();
1471 // Check that all outputs are available and match the outputs in the block itself
1472 // exactly.
1473 for (size_t o = 0; o < tx.vout.size(); o++) {
1474 if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1475 COutPoint out(hash, o);
1476 Coin coin;
1477 bool is_spent = view.SpendCoin(out, &coin);
1478 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1479 fClean = false; // transaction output mismatch
1484 // restore inputs
1485 if (i > 0) { // not coinbases
1486 CTxUndo &txundo = blockUndo.vtxundo[i-1];
1487 if (txundo.vprevout.size() != tx.vin.size()) {
1488 error("DisconnectBlock(): transaction and undo data inconsistent");
1489 return DISCONNECT_FAILED;
1491 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1492 const COutPoint &out = tx.vin[j].prevout;
1493 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1494 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1495 fClean = fClean && res != DISCONNECT_UNCLEAN;
1497 // At this point, all of txundo.vprevout should have been moved out.
1501 // move best block pointer to prevout block
1502 view.SetBestBlock(pindex->pprev->GetBlockHash());
1504 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1507 void static FlushBlockFile(bool fFinalize = false)
1509 LOCK(cs_LastBlockFile);
1511 CDiskBlockPos posOld(nLastBlockFile, 0);
1513 FILE *fileOld = OpenBlockFile(posOld);
1514 if (fileOld) {
1515 if (fFinalize)
1516 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1517 FileCommit(fileOld);
1518 fclose(fileOld);
1521 fileOld = OpenUndoFile(posOld);
1522 if (fileOld) {
1523 if (fFinalize)
1524 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1525 FileCommit(fileOld);
1526 fclose(fileOld);
1530 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1532 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1534 void ThreadScriptCheck() {
1535 RenameThread("bitcoin-scriptch");
1536 scriptcheckqueue.Thread();
1539 // Protected by cs_main
1540 VersionBitsCache versionbitscache;
1542 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1544 LOCK(cs_main);
1545 int32_t nVersion = VERSIONBITS_TOP_BITS;
1547 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1548 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1549 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1550 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1554 return nVersion;
1558 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1560 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1562 private:
1563 int bit;
1565 public:
1566 WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1568 int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1569 int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1570 int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1571 int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1573 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1575 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1576 ((pindex->nVersion >> bit) & 1) != 0 &&
1577 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1581 // Protected by cs_main
1582 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1584 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) {
1585 AssertLockHeld(cs_main);
1587 // BIP16 didn't become active until Apr 1 2012
1588 int64_t nBIP16SwitchTime = 1333238400;
1589 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1591 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1593 // Start enforcing the DERSIG (BIP66) rule
1594 if (pindex->nHeight >= consensusparams.BIP66Height) {
1595 flags |= SCRIPT_VERIFY_DERSIG;
1598 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1599 if (pindex->nHeight >= consensusparams.BIP65Height) {
1600 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1603 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1604 if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1605 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1608 // Start enforcing WITNESS rules using versionbits logic.
1609 if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
1610 flags |= SCRIPT_VERIFY_WITNESS;
1611 flags |= SCRIPT_VERIFY_NULLDUMMY;
1614 return flags;
1619 static int64_t nTimeCheck = 0;
1620 static int64_t nTimeForks = 0;
1621 static int64_t nTimeVerify = 0;
1622 static int64_t nTimeConnect = 0;
1623 static int64_t nTimeIndex = 0;
1624 static int64_t nTimeCallbacks = 0;
1625 static int64_t nTimeTotal = 0;
1627 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1628 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1629 * can fail if those validity checks fail (among other reasons). */
1630 static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1631 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false)
1633 AssertLockHeld(cs_main);
1634 assert(pindex);
1635 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1636 assert((pindex->phashBlock == nullptr) ||
1637 (*pindex->phashBlock == block.GetHash()));
1638 int64_t nTimeStart = GetTimeMicros();
1640 // Check it again in case a previous version let a bad block in
1641 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1642 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1644 // verify that the view's current state corresponds to the previous block
1645 uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
1646 assert(hashPrevBlock == view.GetBestBlock());
1648 // Special case for the genesis block, skipping connection of its transactions
1649 // (its coinbase is unspendable)
1650 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1651 if (!fJustCheck)
1652 view.SetBestBlock(pindex->GetBlockHash());
1653 return true;
1656 bool fScriptChecks = true;
1657 if (!hashAssumeValid.IsNull()) {
1658 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1659 // A suitable default value is included with the software and updated from time to time. Because validity
1660 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1661 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1662 // effectively caching the result of part of the verification.
1663 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1664 if (it != mapBlockIndex.end()) {
1665 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1666 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1667 pindexBestHeader->nChainWork >= UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
1668 // This block is a member of the assumed verified chain and an ancestor of the best header.
1669 // The equivalent time check discourages hash power from extorting the network via DOS attack
1670 // into accepting an invalid block through telling users they must manually set assumevalid.
1671 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1672 // it hard to hide the implication of the demand. This also avoids having release candidates
1673 // that are hardly doing any signature verification at all in testing without having to
1674 // artificially set the default assumed verified block further back.
1675 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1676 // least as good as the expected chain.
1677 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1682 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1683 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
1685 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1686 // unless those are already completely spent.
1687 // If such overwrites are allowed, coinbases and transactions depending upon those
1688 // can be duplicated to remove the ability to spend the first instance -- even after
1689 // being sent to another address.
1690 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1691 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1692 // already refuses previously-known transaction ids entirely.
1693 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1694 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1695 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1696 // initial block download.
1697 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1698 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1699 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1701 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1702 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1703 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1704 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1705 // duplicate transactions descending from the known pairs either.
1706 // 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.
1707 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1708 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1709 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1711 if (fEnforceBIP30) {
1712 for (const auto& tx : block.vtx) {
1713 for (size_t o = 0; o < tx->vout.size(); o++) {
1714 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
1715 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1716 REJECT_INVALID, "bad-txns-BIP30");
1722 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1723 int nLockTimeFlags = 0;
1724 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1725 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1728 // Get the script flags for this block
1729 unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
1731 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1732 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
1734 CBlockUndo blockundo;
1736 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
1738 std::vector<int> prevheights;
1739 CAmount nFees = 0;
1740 int nInputs = 0;
1741 int64_t nSigOpsCost = 0;
1742 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1743 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1744 vPos.reserve(block.vtx.size());
1745 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1746 std::vector<PrecomputedTransactionData> txdata;
1747 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1748 for (unsigned int i = 0; i < block.vtx.size(); i++)
1750 const CTransaction &tx = *(block.vtx[i]);
1752 nInputs += tx.vin.size();
1754 if (!tx.IsCoinBase())
1756 if (!view.HaveInputs(tx))
1757 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1758 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1760 // Check that transaction is BIP68 final
1761 // BIP68 lock checks (as opposed to nLockTime checks) must
1762 // be in ConnectBlock because they require the UTXO set
1763 prevheights.resize(tx.vin.size());
1764 for (size_t j = 0; j < tx.vin.size(); j++) {
1765 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
1768 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1769 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1770 REJECT_INVALID, "bad-txns-nonfinal");
1774 // GetTransactionSigOpCost counts 3 types of sigops:
1775 // * legacy (always)
1776 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1777 // * witness (when witness enabled in flags and excludes coinbase)
1778 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1779 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1780 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1781 REJECT_INVALID, "bad-blk-sigops");
1783 txdata.emplace_back(tx);
1784 if (!tx.IsCoinBase())
1786 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1788 std::vector<CScriptCheck> vChecks;
1789 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1790 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr))
1791 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1792 tx.GetHash().ToString(), FormatStateMessage(state));
1793 control.Add(vChecks);
1796 CTxUndo undoDummy;
1797 if (i > 0) {
1798 blockundo.vtxundo.push_back(CTxUndo());
1800 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1802 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1803 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1805 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1806 LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001);
1808 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1809 if (block.vtx[0]->GetValueOut() > blockReward)
1810 return state.DoS(100,
1811 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1812 block.vtx[0]->GetValueOut(), blockReward),
1813 REJECT_INVALID, "bad-cb-amount");
1815 if (!control.Wait())
1816 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1817 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1818 LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime4 - nTime2), nInputs <= 1 ? 0 : 0.001 * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * 0.000001);
1820 if (fJustCheck)
1821 return true;
1823 // Write undo information to disk
1824 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1826 if (pindex->GetUndoPos().IsNull()) {
1827 CDiskBlockPos _pos;
1828 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1829 return error("ConnectBlock(): FindUndoPos failed");
1830 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1831 return AbortNode(state, "Failed to write undo data");
1833 // update nUndoPos in block index
1834 pindex->nUndoPos = _pos.nPos;
1835 pindex->nStatus |= BLOCK_HAVE_UNDO;
1838 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1839 setDirtyBlockIndex.insert(pindex);
1842 if (fTxIndex)
1843 if (!pblocktree->WriteTxIndex(vPos))
1844 return AbortNode(state, "Failed to write transaction index");
1846 // add this block to the view's block chain
1847 view.SetBestBlock(pindex->GetBlockHash());
1849 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1850 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
1852 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1853 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
1855 return true;
1859 * Update the on-disk chain state.
1860 * The caches and indexes are flushed depending on the mode we're called with
1861 * if they're too large, if it's been a while since the last write,
1862 * or always and in all cases if we're in prune mode and are deleting files.
1864 bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
1865 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
1866 LOCK(cs_main);
1867 static int64_t nLastWrite = 0;
1868 static int64_t nLastFlush = 0;
1869 static int64_t nLastSetChain = 0;
1870 std::set<int> setFilesToPrune;
1871 bool fFlushForPrune = false;
1872 bool fDoFullFlush = false;
1873 int64_t nNow = 0;
1874 try {
1876 LOCK(cs_LastBlockFile);
1877 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1878 if (nManualPruneHeight > 0) {
1879 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
1880 } else {
1881 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1882 fCheckForPruning = false;
1884 if (!setFilesToPrune.empty()) {
1885 fFlushForPrune = true;
1886 if (!fHavePruned) {
1887 pblocktree->WriteFlag("prunedblockfiles", true);
1888 fHavePruned = true;
1892 nNow = GetTimeMicros();
1893 // Avoid writing/flushing immediately after startup.
1894 if (nLastWrite == 0) {
1895 nLastWrite = nNow;
1897 if (nLastFlush == 0) {
1898 nLastFlush = nNow;
1900 if (nLastSetChain == 0) {
1901 nLastSetChain = nNow;
1903 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1904 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1905 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
1906 // 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).
1907 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
1908 // The cache is over the limit, we have to write now.
1909 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
1910 // 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.
1911 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1912 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1913 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1914 // Combine all conditions that result in a full cache flush.
1915 fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1916 // Write blocks and block index to disk.
1917 if (fDoFullFlush || fPeriodicWrite) {
1918 // Depend on nMinDiskSpace to ensure we can write block index
1919 if (!CheckDiskSpace(0))
1920 return state.Error("out of disk space");
1921 // First make sure all block and undo data is flushed to disk.
1922 FlushBlockFile();
1923 // Then update all block file information (which may refer to block and undo files).
1925 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1926 vFiles.reserve(setDirtyFileInfo.size());
1927 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1928 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
1929 setDirtyFileInfo.erase(it++);
1931 std::vector<const CBlockIndex*> vBlocks;
1932 vBlocks.reserve(setDirtyBlockIndex.size());
1933 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1934 vBlocks.push_back(*it);
1935 setDirtyBlockIndex.erase(it++);
1937 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1938 return AbortNode(state, "Failed to write to block index database");
1941 // Finally remove any pruned files
1942 if (fFlushForPrune)
1943 UnlinkPrunedFiles(setFilesToPrune);
1944 nLastWrite = nNow;
1946 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1947 if (fDoFullFlush) {
1948 // Typical Coin structures on disk are around 48 bytes in size.
1949 // Pushing a new one to the database can cause it to be written
1950 // twice (once in the log, and once in the tables). This is already
1951 // an overestimation, as most will delete an existing entry or
1952 // overwrite one. Still, use a conservative safety factor of 2.
1953 if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
1954 return state.Error("out of disk space");
1955 // Flush the chainstate (which may refer to block index entries).
1956 if (!pcoinsTip->Flush())
1957 return AbortNode(state, "Failed to write to coin database");
1958 nLastFlush = nNow;
1961 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
1962 // Update best block in wallet (so we can detect restored wallets).
1963 GetMainSignals().SetBestChain(chainActive.GetLocator());
1964 nLastSetChain = nNow;
1966 } catch (const std::runtime_error& e) {
1967 return AbortNode(state, std::string("System error while flushing: ") + e.what());
1969 return true;
1972 void FlushStateToDisk() {
1973 CValidationState state;
1974 const CChainParams& chainparams = Params();
1975 FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
1978 void PruneAndFlush() {
1979 CValidationState state;
1980 fCheckForPruning = true;
1981 const CChainParams& chainparams = Params();
1982 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
1985 static void DoWarning(const std::string& strWarning)
1987 static bool fWarned = false;
1988 SetMiscWarning(strWarning);
1989 if (!fWarned) {
1990 AlertNotify(strWarning);
1991 fWarned = true;
1995 /** Update chainActive and related internal data structures. */
1996 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
1997 chainActive.SetTip(pindexNew);
1999 // New best block
2000 mempool.AddTransactionsUpdated(1);
2002 cvBlockChange.notify_all();
2004 std::vector<std::string> warningMessages;
2005 if (!IsInitialBlockDownload())
2007 int nUpgraded = 0;
2008 const CBlockIndex* pindex = chainActive.Tip();
2009 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2010 WarningBitsConditionChecker checker(bit);
2011 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2012 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2013 const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2014 if (state == THRESHOLD_ACTIVE) {
2015 DoWarning(strWarning);
2016 } else {
2017 warningMessages.push_back(strWarning);
2021 // Check the version of the last 100 blocks to see if we need to upgrade:
2022 for (int i = 0; i < 100 && pindex != nullptr; i++)
2024 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2025 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2026 ++nUpgraded;
2027 pindex = pindex->pprev;
2029 if (nUpgraded > 0)
2030 warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
2031 if (nUpgraded > 100/2)
2033 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2034 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2035 DoWarning(strWarning);
2038 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
2039 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
2040 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2041 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2042 GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2043 if (!warningMessages.empty())
2044 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2045 LogPrintf("\n");
2049 /** Disconnect chainActive's tip.
2050 * After calling, the mempool will be in an inconsistent state, with
2051 * transactions from disconnected blocks being added to disconnectpool. You
2052 * should make the mempool consistent again by calling UpdateMempoolForReorg.
2053 * with cs_main held.
2055 * If disconnectpool is nullptr, then no disconnected transactions are added to
2056 * disconnectpool (note that the caller is responsible for mempool consistency
2057 * in any case).
2059 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
2061 CBlockIndex *pindexDelete = chainActive.Tip();
2062 assert(pindexDelete);
2063 // Read block from disk.
2064 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2065 CBlock& block = *pblock;
2066 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2067 return AbortNode(state, "Failed to read block");
2068 // Apply the block atomically to the chain state.
2069 int64_t nStart = GetTimeMicros();
2071 CCoinsViewCache view(pcoinsTip);
2072 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2073 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2074 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2075 bool flushed = view.Flush();
2076 assert(flushed);
2078 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2079 // Write the chain state to disk, if necessary.
2080 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2081 return false;
2083 if (disconnectpool) {
2084 // Save transactions to re-add to mempool at end of reorg
2085 for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2086 disconnectpool->addTransaction(*it);
2088 while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2089 // Drop the earliest entry, and remove its children from the mempool.
2090 auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2091 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
2092 disconnectpool->removeEntry(it);
2096 // Update chainActive and related variables.
2097 UpdateTip(pindexDelete->pprev, chainparams);
2098 // Let wallets know transactions went from 1-confirmed to
2099 // 0-confirmed or conflicted:
2100 GetMainSignals().BlockDisconnected(pblock);
2101 return true;
2104 static int64_t nTimeReadFromDisk = 0;
2105 static int64_t nTimeConnectTotal = 0;
2106 static int64_t nTimeFlush = 0;
2107 static int64_t nTimeChainState = 0;
2108 static int64_t nTimePostConnect = 0;
2110 struct PerBlockConnectTrace {
2111 CBlockIndex* pindex = nullptr;
2112 std::shared_ptr<const CBlock> pblock;
2113 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
2114 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
2117 * Used to track blocks whose transactions were applied to the UTXO state as a
2118 * part of a single ActivateBestChainStep call.
2120 * This class also tracks transactions that are removed from the mempool as
2121 * conflicts (per block) and can be used to pass all those transactions
2122 * through SyncTransaction.
2124 * This class assumes (and asserts) that the conflicted transactions for a given
2125 * block are added via mempool callbacks prior to the BlockConnected() associated
2126 * with those transactions. If any transactions are marked conflicted, it is
2127 * assumed that an associated block will always be added.
2129 * This class is single-use, once you call GetBlocksConnected() you have to throw
2130 * it away and make a new one.
2132 class ConnectTrace {
2133 private:
2134 std::vector<PerBlockConnectTrace> blocksConnected;
2135 CTxMemPool &pool;
2137 public:
2138 ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
2139 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2142 ~ConnectTrace() {
2143 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2146 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2147 assert(!blocksConnected.back().pindex);
2148 assert(pindex);
2149 assert(pblock);
2150 blocksConnected.back().pindex = pindex;
2151 blocksConnected.back().pblock = std::move(pblock);
2152 blocksConnected.emplace_back();
2155 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2156 // We always keep one extra block at the end of our list because
2157 // blocks are added after all the conflicted transactions have
2158 // been filled in. Thus, the last entry should always be an empty
2159 // one waiting for the transactions from the next block. We pop
2160 // the last entry here to make sure the list we return is sane.
2161 assert(!blocksConnected.back().pindex);
2162 assert(blocksConnected.back().conflictedTxs->empty());
2163 blocksConnected.pop_back();
2164 return blocksConnected;
2167 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
2168 assert(!blocksConnected.back().pindex);
2169 if (reason == MemPoolRemovalReason::CONFLICT) {
2170 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2176 * Connect a new block to chainActive. pblock is either nullptr or a pointer to a CBlock
2177 * corresponding to pindexNew, to bypass loading it again from disk.
2179 * The block is added to connectTrace if connection succeeds.
2181 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
2183 assert(pindexNew->pprev == chainActive.Tip());
2184 // Read block from disk.
2185 int64_t nTime1 = GetTimeMicros();
2186 std::shared_ptr<const CBlock> pthisBlock;
2187 if (!pblock) {
2188 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2189 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2190 return AbortNode(state, "Failed to read block");
2191 pthisBlock = pblockNew;
2192 } else {
2193 pthisBlock = pblock;
2195 const CBlock& blockConnecting = *pthisBlock;
2196 // Apply the block atomically to the chain state.
2197 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2198 int64_t nTime3;
2199 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2201 CCoinsViewCache view(pcoinsTip);
2202 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2203 GetMainSignals().BlockChecked(blockConnecting, state);
2204 if (!rv) {
2205 if (state.IsInvalid())
2206 InvalidBlockFound(pindexNew, state);
2207 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2209 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2210 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2211 bool flushed = view.Flush();
2212 assert(flushed);
2214 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2215 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2216 // Write the chain state to disk, if necessary.
2217 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2218 return false;
2219 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2220 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2221 // Remove conflicting transactions from the mempool.;
2222 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2223 disconnectpool.removeForBlock(blockConnecting.vtx);
2224 // Update chainActive & related variables.
2225 UpdateTip(pindexNew, chainparams);
2227 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2228 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2229 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2231 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2232 return true;
2236 * Return the tip of the chain with the most work in it, that isn't
2237 * known to be invalid (it's however far from certain to be valid).
2239 static CBlockIndex* FindMostWorkChain() {
2240 do {
2241 CBlockIndex *pindexNew = nullptr;
2243 // Find the best candidate header.
2245 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2246 if (it == setBlockIndexCandidates.rend())
2247 return nullptr;
2248 pindexNew = *it;
2251 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2252 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2253 CBlockIndex *pindexTest = pindexNew;
2254 bool fInvalidAncestor = false;
2255 while (pindexTest && !chainActive.Contains(pindexTest)) {
2256 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2258 // Pruned nodes may have entries in setBlockIndexCandidates for
2259 // which block files have been deleted. Remove those as candidates
2260 // for the most work chain if we come across them; we can't switch
2261 // to a chain unless we have all the non-active-chain parent blocks.
2262 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2263 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2264 if (fFailedChain || fMissingData) {
2265 // Candidate chain is not usable (either invalid or missing data)
2266 if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2267 pindexBestInvalid = pindexNew;
2268 CBlockIndex *pindexFailed = pindexNew;
2269 // Remove the entire chain from the set.
2270 while (pindexTest != pindexFailed) {
2271 if (fFailedChain) {
2272 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2273 } else if (fMissingData) {
2274 // If we're missing data, then add back to mapBlocksUnlinked,
2275 // so that if the block arrives in the future we can try adding
2276 // to setBlockIndexCandidates again.
2277 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2279 setBlockIndexCandidates.erase(pindexFailed);
2280 pindexFailed = pindexFailed->pprev;
2282 setBlockIndexCandidates.erase(pindexTest);
2283 fInvalidAncestor = true;
2284 break;
2286 pindexTest = pindexTest->pprev;
2288 if (!fInvalidAncestor)
2289 return pindexNew;
2290 } while(true);
2293 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2294 static void PruneBlockIndexCandidates() {
2295 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2296 // reorganization to a better block fails.
2297 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2298 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2299 setBlockIndexCandidates.erase(it++);
2301 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2302 assert(!setBlockIndexCandidates.empty());
2306 * Try to make some progress towards making pindexMostWork the active block.
2307 * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
2309 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2311 AssertLockHeld(cs_main);
2312 const CBlockIndex *pindexOldTip = chainActive.Tip();
2313 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2315 // Disconnect active blocks which are no longer in the best chain.
2316 bool fBlocksDisconnected = false;
2317 DisconnectedBlockTransactions disconnectpool;
2318 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2319 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2320 // This is likely a fatal error, but keep the mempool consistent,
2321 // just in case. Only remove from the mempool in this case.
2322 UpdateMempoolForReorg(disconnectpool, false);
2323 return false;
2325 fBlocksDisconnected = true;
2328 // Build list of new blocks to connect.
2329 std::vector<CBlockIndex*> vpindexToConnect;
2330 bool fContinue = true;
2331 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2332 while (fContinue && nHeight != pindexMostWork->nHeight) {
2333 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2334 // a few blocks along the way.
2335 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2336 vpindexToConnect.clear();
2337 vpindexToConnect.reserve(nTargetHeight - nHeight);
2338 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2339 while (pindexIter && pindexIter->nHeight != nHeight) {
2340 vpindexToConnect.push_back(pindexIter);
2341 pindexIter = pindexIter->pprev;
2343 nHeight = nTargetHeight;
2345 // Connect new blocks.
2346 for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
2347 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2348 if (state.IsInvalid()) {
2349 // The block violates a consensus rule.
2350 if (!state.CorruptionPossible())
2351 InvalidChainFound(vpindexToConnect.back());
2352 state = CValidationState();
2353 fInvalidFound = true;
2354 fContinue = false;
2355 break;
2356 } else {
2357 // A system error occurred (disk space, database error, ...).
2358 // Make the mempool consistent with the current tip, just in case
2359 // any observers try to use it before shutdown.
2360 UpdateMempoolForReorg(disconnectpool, false);
2361 return false;
2363 } else {
2364 PruneBlockIndexCandidates();
2365 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2366 // We're in a better position than we were. Return temporarily to release the lock.
2367 fContinue = false;
2368 break;
2374 if (fBlocksDisconnected) {
2375 // If any blocks were disconnected, disconnectpool may be non empty. Add
2376 // any disconnected transactions back to the mempool.
2377 UpdateMempoolForReorg(disconnectpool, true);
2379 mempool.check(pcoinsTip);
2381 // Callbacks/notifications for a new best chain.
2382 if (fInvalidFound)
2383 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2384 else
2385 CheckForkWarningConditions();
2387 return true;
2390 static void NotifyHeaderTip() {
2391 bool fNotify = false;
2392 bool fInitialBlockDownload = false;
2393 static CBlockIndex* pindexHeaderOld = nullptr;
2394 CBlockIndex* pindexHeader = nullptr;
2396 LOCK(cs_main);
2397 pindexHeader = pindexBestHeader;
2399 if (pindexHeader != pindexHeaderOld) {
2400 fNotify = true;
2401 fInitialBlockDownload = IsInitialBlockDownload();
2402 pindexHeaderOld = pindexHeader;
2405 // Send block tip changed notifications without cs_main
2406 if (fNotify) {
2407 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2412 * Make the best chain active, in multiple steps. The result is either failure
2413 * or an activated best chain. pblock is either nullptr or a pointer to a block
2414 * that is already loaded (to avoid loading it again from disk).
2416 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2417 // Note that while we're often called here from ProcessNewBlock, this is
2418 // far from a guarantee. Things in the P2P/RPC will often end up calling
2419 // us in the middle of ProcessNewBlock - do not assume pblock is set
2420 // sanely for performance or correctness!
2422 CBlockIndex *pindexMostWork = nullptr;
2423 CBlockIndex *pindexNewTip = nullptr;
2424 int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2425 do {
2426 boost::this_thread::interruption_point();
2427 if (ShutdownRequested())
2428 break;
2430 const CBlockIndex *pindexFork;
2431 bool fInitialDownload;
2433 LOCK(cs_main);
2434 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2436 CBlockIndex *pindexOldTip = chainActive.Tip();
2437 if (pindexMostWork == nullptr) {
2438 pindexMostWork = FindMostWorkChain();
2441 // Whether we have anything to do at all.
2442 if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip())
2443 return true;
2445 bool fInvalidFound = false;
2446 std::shared_ptr<const CBlock> nullBlockPtr;
2447 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2448 return false;
2450 if (fInvalidFound) {
2451 // Wipe cache, we may need another branch now.
2452 pindexMostWork = nullptr;
2454 pindexNewTip = chainActive.Tip();
2455 pindexFork = chainActive.FindFork(pindexOldTip);
2456 fInitialDownload = IsInitialBlockDownload();
2458 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2459 assert(trace.pblock && trace.pindex);
2460 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, *trace.conflictedTxs);
2463 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2465 // Notifications/callbacks that can run without cs_main
2467 // Notify external listeners about the new tip.
2468 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2470 // Always notify the UI if a new block tip was connected
2471 if (pindexFork != pindexNewTip) {
2472 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2475 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2476 } while (pindexNewTip != pindexMostWork);
2477 CheckBlockIndex(chainparams.GetConsensus());
2479 // Write changes periodically to disk, after relay.
2480 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
2481 return false;
2484 return true;
2488 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2491 LOCK(cs_main);
2492 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2493 // Nothing to do, this block is not at the tip.
2494 return true;
2496 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2497 // The chain has been extended since the last call, reset the counter.
2498 nBlockReverseSequenceId = -1;
2500 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2501 setBlockIndexCandidates.erase(pindex);
2502 pindex->nSequenceId = nBlockReverseSequenceId;
2503 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2504 // We can't keep reducing the counter if somebody really wants to
2505 // call preciousblock 2**31-1 times on the same set of tips...
2506 nBlockReverseSequenceId--;
2508 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2509 setBlockIndexCandidates.insert(pindex);
2510 PruneBlockIndexCandidates();
2514 return ActivateBestChain(state, params);
2517 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2519 AssertLockHeld(cs_main);
2521 // Mark the block itself as invalid.
2522 pindex->nStatus |= BLOCK_FAILED_VALID;
2523 setDirtyBlockIndex.insert(pindex);
2524 setBlockIndexCandidates.erase(pindex);
2526 DisconnectedBlockTransactions disconnectpool;
2527 while (chainActive.Contains(pindex)) {
2528 CBlockIndex *pindexWalk = chainActive.Tip();
2529 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2530 setDirtyBlockIndex.insert(pindexWalk);
2531 setBlockIndexCandidates.erase(pindexWalk);
2532 // ActivateBestChain considers blocks already in chainActive
2533 // unconditionally valid already, so force disconnect away from it.
2534 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2535 // It's probably hopeless to try to make the mempool consistent
2536 // here if DisconnectTip failed, but we can try.
2537 UpdateMempoolForReorg(disconnectpool, false);
2538 return false;
2542 // DisconnectTip will add transactions to disconnectpool; try to add these
2543 // back to the mempool.
2544 UpdateMempoolForReorg(disconnectpool, true);
2546 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2547 // add it again.
2548 BlockMap::iterator it = mapBlockIndex.begin();
2549 while (it != mapBlockIndex.end()) {
2550 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2551 setBlockIndexCandidates.insert(it->second);
2553 it++;
2556 InvalidChainFound(pindex);
2557 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2558 return true;
2561 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2562 AssertLockHeld(cs_main);
2564 int nHeight = pindex->nHeight;
2566 // Remove the invalidity flag from this block and all its descendants.
2567 BlockMap::iterator it = mapBlockIndex.begin();
2568 while (it != mapBlockIndex.end()) {
2569 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2570 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2571 setDirtyBlockIndex.insert(it->second);
2572 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2573 setBlockIndexCandidates.insert(it->second);
2575 if (it->second == pindexBestInvalid) {
2576 // Reset invalid block marker if it was pointing to one of those.
2577 pindexBestInvalid = nullptr;
2580 it++;
2583 // Remove the invalidity flag from all ancestors too.
2584 while (pindex != nullptr) {
2585 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2586 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2587 setDirtyBlockIndex.insert(pindex);
2589 pindex = pindex->pprev;
2591 return true;
2594 static CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2596 // Check for duplicate
2597 uint256 hash = block.GetHash();
2598 BlockMap::iterator it = mapBlockIndex.find(hash);
2599 if (it != mapBlockIndex.end())
2600 return it->second;
2602 // Construct new block index object
2603 CBlockIndex* pindexNew = new CBlockIndex(block);
2604 assert(pindexNew);
2605 // We assign the sequence id to blocks only when the full data is available,
2606 // to avoid miners withholding blocks but broadcasting headers, to get a
2607 // competitive advantage.
2608 pindexNew->nSequenceId = 0;
2609 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2610 pindexNew->phashBlock = &((*mi).first);
2611 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2612 if (miPrev != mapBlockIndex.end())
2614 pindexNew->pprev = (*miPrev).second;
2615 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2616 pindexNew->BuildSkip();
2618 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2619 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2620 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2621 if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2622 pindexBestHeader = pindexNew;
2624 setDirtyBlockIndex.insert(pindexNew);
2626 return pindexNew;
2629 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2630 static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2632 pindexNew->nTx = block.vtx.size();
2633 pindexNew->nChainTx = 0;
2634 pindexNew->nFile = pos.nFile;
2635 pindexNew->nDataPos = pos.nPos;
2636 pindexNew->nUndoPos = 0;
2637 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2638 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2639 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2641 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2642 setDirtyBlockIndex.insert(pindexNew);
2644 if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
2645 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2646 std::deque<CBlockIndex*> queue;
2647 queue.push_back(pindexNew);
2649 // Recursively process any descendant blocks that now may be eligible to be connected.
2650 while (!queue.empty()) {
2651 CBlockIndex *pindex = queue.front();
2652 queue.pop_front();
2653 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2655 LOCK(cs_nBlockSequenceId);
2656 pindex->nSequenceId = nBlockSequenceId++;
2658 if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2659 setBlockIndexCandidates.insert(pindex);
2661 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2662 while (range.first != range.second) {
2663 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2664 queue.push_back(it->second);
2665 range.first++;
2666 mapBlocksUnlinked.erase(it);
2669 } else {
2670 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2671 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2675 return true;
2678 static bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2680 LOCK(cs_LastBlockFile);
2682 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2683 if (vinfoBlockFile.size() <= nFile) {
2684 vinfoBlockFile.resize(nFile + 1);
2687 if (!fKnown) {
2688 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2689 nFile++;
2690 if (vinfoBlockFile.size() <= nFile) {
2691 vinfoBlockFile.resize(nFile + 1);
2694 pos.nFile = nFile;
2695 pos.nPos = vinfoBlockFile[nFile].nSize;
2698 if ((int)nFile != nLastBlockFile) {
2699 if (!fKnown) {
2700 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2702 FlushBlockFile(!fKnown);
2703 nLastBlockFile = nFile;
2706 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2707 if (fKnown)
2708 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2709 else
2710 vinfoBlockFile[nFile].nSize += nAddSize;
2712 if (!fKnown) {
2713 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2714 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2715 if (nNewChunks > nOldChunks) {
2716 if (fPruneMode)
2717 fCheckForPruning = true;
2718 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2719 FILE *file = OpenBlockFile(pos);
2720 if (file) {
2721 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2722 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2723 fclose(file);
2726 else
2727 return state.Error("out of disk space");
2731 setDirtyFileInfo.insert(nFile);
2732 return true;
2735 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2737 pos.nFile = nFile;
2739 LOCK(cs_LastBlockFile);
2741 unsigned int nNewSize;
2742 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2743 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2744 setDirtyFileInfo.insert(nFile);
2746 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2747 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2748 if (nNewChunks > nOldChunks) {
2749 if (fPruneMode)
2750 fCheckForPruning = true;
2751 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2752 FILE *file = OpenUndoFile(pos);
2753 if (file) {
2754 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2755 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2756 fclose(file);
2759 else
2760 return state.Error("out of disk space");
2763 return true;
2766 static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
2768 // Check proof of work matches claimed amount
2769 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2770 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2772 return true;
2775 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2777 // These are checks that are independent of context.
2779 if (block.fChecked)
2780 return true;
2782 // Check that the header is valid (particularly PoW). This is mostly
2783 // redundant with the call in AcceptBlockHeader.
2784 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2785 return false;
2787 // Check the merkle root.
2788 if (fCheckMerkleRoot) {
2789 bool mutated;
2790 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2791 if (block.hashMerkleRoot != hashMerkleRoot2)
2792 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2794 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2795 // of transactions in a block without affecting the merkle root of a block,
2796 // while still invalidating it.
2797 if (mutated)
2798 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2801 // All potential-corruption validation must be done before we do any
2802 // transaction validation, as otherwise we may mark the header as invalid
2803 // because we receive the wrong transactions for it.
2804 // Note that witness malleability is checked in ContextualCheckBlock, so no
2805 // checks that use witness data may be performed here.
2807 // Size limits
2808 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)
2809 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2811 // First transaction must be coinbase, the rest must not be
2812 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2813 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2814 for (unsigned int i = 1; i < block.vtx.size(); i++)
2815 if (block.vtx[i]->IsCoinBase())
2816 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2818 // Check transactions
2819 for (const auto& tx : block.vtx)
2820 if (!CheckTransaction(*tx, state, false))
2821 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2822 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2824 unsigned int nSigOps = 0;
2825 for (const auto& tx : block.vtx)
2827 nSigOps += GetLegacySigOpCount(*tx);
2829 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2830 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2832 if (fCheckPOW && fCheckMerkleRoot)
2833 block.fChecked = true;
2835 return true;
2838 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2840 LOCK(cs_main);
2841 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2844 // Compute at which vout of the block's coinbase transaction the witness
2845 // commitment occurs, or -1 if not found.
2846 static int GetWitnessCommitmentIndex(const CBlock& block)
2848 int commitpos = -1;
2849 if (!block.vtx.empty()) {
2850 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2851 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) {
2852 commitpos = o;
2856 return commitpos;
2859 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2861 int commitpos = GetWitnessCommitmentIndex(block);
2862 static const std::vector<unsigned char> nonce(32, 0x00);
2863 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2864 CMutableTransaction tx(*block.vtx[0]);
2865 tx.vin[0].scriptWitness.stack.resize(1);
2866 tx.vin[0].scriptWitness.stack[0] = nonce;
2867 block.vtx[0] = MakeTransactionRef(std::move(tx));
2871 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2873 std::vector<unsigned char> commitment;
2874 int commitpos = GetWitnessCommitmentIndex(block);
2875 std::vector<unsigned char> ret(32, 0x00);
2876 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2877 if (commitpos == -1) {
2878 uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
2879 CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
2880 CTxOut out;
2881 out.nValue = 0;
2882 out.scriptPubKey.resize(38);
2883 out.scriptPubKey[0] = OP_RETURN;
2884 out.scriptPubKey[1] = 0x24;
2885 out.scriptPubKey[2] = 0xaa;
2886 out.scriptPubKey[3] = 0x21;
2887 out.scriptPubKey[4] = 0xa9;
2888 out.scriptPubKey[5] = 0xed;
2889 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2890 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2891 CMutableTransaction tx(*block.vtx[0]);
2892 tx.vout.push_back(out);
2893 block.vtx[0] = MakeTransactionRef(std::move(tx));
2896 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2897 return commitment;
2900 /** Context-dependent validity checks.
2901 * By "context", we mean only the previous block headers, but not the UTXO
2902 * set; UTXO-related validity checks are done in ConnectBlock(). */
2903 static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2905 assert(pindexPrev != nullptr);
2906 const int nHeight = pindexPrev->nHeight + 1;
2908 // Check proof of work
2909 const Consensus::Params& consensusParams = params.GetConsensus();
2910 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2911 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2913 // Check against checkpoints
2914 if (fCheckpointsEnabled) {
2915 // Don't accept any forks from the main chain prior to last checkpoint.
2916 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
2917 // MapBlockIndex.
2918 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(params.Checkpoints());
2919 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2920 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
2923 // Check timestamp against prev
2924 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2925 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2927 // Check timestamp
2928 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
2929 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
2931 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2932 // check for version 2, 3 and 4 upgrades
2933 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
2934 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
2935 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
2936 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
2937 strprintf("rejected nVersion=0x%08x block", block.nVersion));
2939 return true;
2942 static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
2944 const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
2946 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
2947 int nLockTimeFlags = 0;
2948 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
2949 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
2952 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
2953 ? pindexPrev->GetMedianTimePast()
2954 : block.GetBlockTime();
2956 // Check that all transactions are finalized
2957 for (const auto& tx : block.vtx) {
2958 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
2959 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
2963 // Enforce rule that the coinbase starts with serialized block height
2964 if (nHeight >= consensusParams.BIP34Height)
2966 CScript expect = CScript() << nHeight;
2967 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
2968 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
2969 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
2973 // Validation for witness commitments.
2974 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
2975 // coinbase (where 0x0000....0000 is used instead).
2976 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
2977 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
2978 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
2979 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
2980 // multiple, the last one is used.
2981 bool fHaveWitness = false;
2982 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
2983 int commitpos = GetWitnessCommitmentIndex(block);
2984 if (commitpos != -1) {
2985 bool malleated = false;
2986 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
2987 // The malleation check is ignored; as the transaction tree itself
2988 // already does not permit it, it is impossible to trigger in the
2989 // witness tree.
2990 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
2991 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
2993 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
2994 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
2995 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
2997 fHaveWitness = true;
3001 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3002 if (!fHaveWitness) {
3003 for (const auto& tx : block.vtx) {
3004 if (tx->HasWitness()) {
3005 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
3010 // After the coinbase witness nonce and commitment are verified,
3011 // we can check if the block weight passes (before we've checked the
3012 // coinbase witness, it would be possible for the weight to be too
3013 // large by filling up the coinbase witness, which doesn't change
3014 // the block hash, so we couldn't mark the block as permanently
3015 // failed).
3016 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3017 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
3020 return true;
3023 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3025 AssertLockHeld(cs_main);
3026 // Check for duplicate
3027 uint256 hash = block.GetHash();
3028 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3029 CBlockIndex *pindex = nullptr;
3030 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3032 if (miSelf != mapBlockIndex.end()) {
3033 // Block header is already known.
3034 pindex = miSelf->second;
3035 if (ppindex)
3036 *ppindex = pindex;
3037 if (pindex->nStatus & BLOCK_FAILED_MASK)
3038 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3039 return true;
3042 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3043 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3045 // Get prev block index
3046 CBlockIndex* pindexPrev = nullptr;
3047 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3048 if (mi == mapBlockIndex.end())
3049 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
3050 pindexPrev = (*mi).second;
3051 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3052 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3053 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3054 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3056 if (pindex == nullptr)
3057 pindex = AddToBlockIndex(block);
3059 if (ppindex)
3060 *ppindex = pindex;
3062 CheckBlockIndex(chainparams.GetConsensus());
3064 return true;
3067 // Exposed wrapper for AcceptBlockHeader
3068 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
3071 LOCK(cs_main);
3072 for (const CBlockHeader& header : headers) {
3073 CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3074 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
3075 return false;
3077 if (ppindex) {
3078 *ppindex = pindex;
3082 NotifyHeaderTip();
3083 return true;
3086 /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
3087 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3089 const CBlock& block = *pblock;
3091 if (fNewBlock) *fNewBlock = false;
3092 AssertLockHeld(cs_main);
3094 CBlockIndex *pindexDummy = nullptr;
3095 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3097 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3098 return false;
3100 // Try to process all requested blocks that we don't have, but only
3101 // process an unrequested block if it's new and has enough work to
3102 // advance our tip, and isn't too many blocks ahead.
3103 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3104 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3105 // Blocks that are too out-of-order needlessly limit the effectiveness of
3106 // pruning, because pruning will not delete block files that contain any
3107 // blocks which are too close in height to the tip. Apply this test
3108 // regardless of whether pruning is enabled; it should generally be safe to
3109 // not process unrequested blocks.
3110 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3112 // TODO: Decouple this function from the block download logic by removing fRequested
3113 // This requires some new chain data structure to efficiently look up if a
3114 // block is in a chain leading to a candidate for best tip, despite not
3115 // being such a candidate itself.
3117 // TODO: deal better with return value and error conditions for duplicate
3118 // and unrequested blocks.
3119 if (fAlreadyHave) return true;
3120 if (!fRequested) { // If we didn't ask for it:
3121 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3122 if (!fHasMoreWork) return true; // Don't process less-work chains
3123 if (fTooFarAhead) return true; // Block height is too high
3125 if (fNewBlock) *fNewBlock = true;
3127 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3128 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3129 if (state.IsInvalid() && !state.CorruptionPossible()) {
3130 pindex->nStatus |= BLOCK_FAILED_VALID;
3131 setDirtyBlockIndex.insert(pindex);
3133 return error("%s: %s", __func__, FormatStateMessage(state));
3136 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3137 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3138 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3139 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3141 int nHeight = pindex->nHeight;
3143 // Write block to history file
3144 try {
3145 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3146 CDiskBlockPos blockPos;
3147 if (dbp != nullptr)
3148 blockPos = *dbp;
3149 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr))
3150 return error("AcceptBlock(): FindBlockPos failed");
3151 if (dbp == nullptr)
3152 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3153 AbortNode(state, "Failed to write block");
3154 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3155 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3156 } catch (const std::runtime_error& e) {
3157 return AbortNode(state, std::string("System error: ") + e.what());
3160 if (fCheckForPruning)
3161 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3163 return true;
3166 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3169 CBlockIndex *pindex = nullptr;
3170 if (fNewBlock) *fNewBlock = false;
3171 CValidationState state;
3172 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3173 // belt-and-suspenders.
3174 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3176 LOCK(cs_main);
3178 if (ret) {
3179 // Store to disk
3180 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
3182 CheckBlockIndex(chainparams.GetConsensus());
3183 if (!ret) {
3184 GetMainSignals().BlockChecked(*pblock, state);
3185 return error("%s: AcceptBlock FAILED", __func__);
3189 NotifyHeaderTip();
3191 CValidationState state; // Only used to report errors, not invalidity - ignore it
3192 if (!ActivateBestChain(state, chainparams, pblock))
3193 return error("%s: ActivateBestChain failed", __func__);
3195 return true;
3198 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3200 AssertLockHeld(cs_main);
3201 assert(pindexPrev && pindexPrev == chainActive.Tip());
3202 CCoinsViewCache viewNew(pcoinsTip);
3203 CBlockIndex indexDummy(block);
3204 indexDummy.pprev = pindexPrev;
3205 indexDummy.nHeight = pindexPrev->nHeight + 1;
3207 // NOTE: CheckBlockHeader is called by CheckBlock
3208 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3209 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3210 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3211 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3212 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3213 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3214 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3215 return false;
3216 assert(state.IsValid());
3218 return true;
3222 * BLOCK PRUNING CODE
3225 /* Calculate the amount of disk space the block & undo files currently use */
3226 static uint64_t CalculateCurrentUsage()
3228 uint64_t retval = 0;
3229 for (const CBlockFileInfo &file : vinfoBlockFile) {
3230 retval += file.nSize + file.nUndoSize;
3232 return retval;
3235 /* Prune a block file (modify associated database entries)*/
3236 void PruneOneBlockFile(const int fileNumber)
3238 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3239 CBlockIndex* pindex = it->second;
3240 if (pindex->nFile == fileNumber) {
3241 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3242 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3243 pindex->nFile = 0;
3244 pindex->nDataPos = 0;
3245 pindex->nUndoPos = 0;
3246 setDirtyBlockIndex.insert(pindex);
3248 // Prune from mapBlocksUnlinked -- any block we prune would have
3249 // to be downloaded again in order to consider its chain, at which
3250 // point it would be considered as a candidate for
3251 // mapBlocksUnlinked or setBlockIndexCandidates.
3252 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3253 while (range.first != range.second) {
3254 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3255 range.first++;
3256 if (_it->second == pindex) {
3257 mapBlocksUnlinked.erase(_it);
3263 vinfoBlockFile[fileNumber].SetNull();
3264 setDirtyFileInfo.insert(fileNumber);
3268 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3270 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3271 CDiskBlockPos pos(*it, 0);
3272 fs::remove(GetBlockPosFilename(pos, "blk"));
3273 fs::remove(GetBlockPosFilename(pos, "rev"));
3274 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3278 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3279 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3281 assert(fPruneMode && nManualPruneHeight > 0);
3283 LOCK2(cs_main, cs_LastBlockFile);
3284 if (chainActive.Tip() == nullptr)
3285 return;
3287 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3288 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3289 int count=0;
3290 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3291 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3292 continue;
3293 PruneOneBlockFile(fileNumber);
3294 setFilesToPrune.insert(fileNumber);
3295 count++;
3297 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3300 /* This function is called from the RPC code for pruneblockchain */
3301 void PruneBlockFilesManual(int nManualPruneHeight)
3303 CValidationState state;
3304 const CChainParams& chainparams = Params();
3305 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
3309 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
3310 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
3311 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
3312 * (which in this case means the blockchain must be re-downloaded.)
3314 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
3315 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
3316 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
3317 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
3318 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
3319 * A db flag records the fact that at least some block files have been pruned.
3321 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
3323 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3325 LOCK2(cs_main, cs_LastBlockFile);
3326 if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
3327 return;
3329 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3330 return;
3333 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3334 uint64_t nCurrentUsage = CalculateCurrentUsage();
3335 // We don't check to prune until after we've allocated new space for files
3336 // So we should leave a buffer under our target to account for another allocation
3337 // before the next pruning.
3338 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3339 uint64_t nBytesToPrune;
3340 int count=0;
3342 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3343 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3344 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3346 if (vinfoBlockFile[fileNumber].nSize == 0)
3347 continue;
3349 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3350 break;
3352 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3353 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3354 continue;
3356 PruneOneBlockFile(fileNumber);
3357 // Queue up the files for removal
3358 setFilesToPrune.insert(fileNumber);
3359 nCurrentUsage -= nBytesToPrune;
3360 count++;
3364 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3365 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3366 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3367 nLastBlockWeCanPrune, count);
3370 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3372 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3374 // Check for nMinDiskSpace bytes (currently 50MB)
3375 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3376 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3378 return true;
3381 static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3383 if (pos.IsNull())
3384 return nullptr;
3385 fs::path path = GetBlockPosFilename(pos, prefix);
3386 fs::create_directories(path.parent_path());
3387 FILE* file = fsbridge::fopen(path, "rb+");
3388 if (!file && !fReadOnly)
3389 file = fsbridge::fopen(path, "wb+");
3390 if (!file) {
3391 LogPrintf("Unable to open file %s\n", path.string());
3392 return nullptr;
3394 if (pos.nPos) {
3395 if (fseek(file, pos.nPos, SEEK_SET)) {
3396 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3397 fclose(file);
3398 return nullptr;
3401 return file;
3404 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3405 return OpenDiskFile(pos, "blk", fReadOnly);
3408 /** Open an undo file (rev?????.dat) */
3409 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3410 return OpenDiskFile(pos, "rev", fReadOnly);
3413 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3415 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3418 CBlockIndex * InsertBlockIndex(uint256 hash)
3420 if (hash.IsNull())
3421 return nullptr;
3423 // Return existing
3424 BlockMap::iterator mi = mapBlockIndex.find(hash);
3425 if (mi != mapBlockIndex.end())
3426 return (*mi).second;
3428 // Create new
3429 CBlockIndex* pindexNew = new CBlockIndex();
3430 if (!pindexNew)
3431 throw std::runtime_error(std::string(__func__) + ": new CBlockIndex failed");
3432 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3433 pindexNew->phashBlock = &((*mi).first);
3435 return pindexNew;
3438 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3440 if (!pblocktree->LoadBlockIndexGuts(chainparams.GetConsensus(), InsertBlockIndex))
3441 return false;
3443 boost::this_thread::interruption_point();
3445 // Calculate nChainWork
3446 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3447 vSortedByHeight.reserve(mapBlockIndex.size());
3448 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3450 CBlockIndex* pindex = item.second;
3451 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3453 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3454 for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
3456 CBlockIndex* pindex = item.second;
3457 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3458 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3459 // We can link the chain of blocks for which we've received transactions at some point.
3460 // Pruned nodes may have deleted the block.
3461 if (pindex->nTx > 0) {
3462 if (pindex->pprev) {
3463 if (pindex->pprev->nChainTx) {
3464 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3465 } else {
3466 pindex->nChainTx = 0;
3467 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3469 } else {
3470 pindex->nChainTx = pindex->nTx;
3473 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
3474 setBlockIndexCandidates.insert(pindex);
3475 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3476 pindexBestInvalid = pindex;
3477 if (pindex->pprev)
3478 pindex->BuildSkip();
3479 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3480 pindexBestHeader = pindex;
3483 // Load block file info
3484 pblocktree->ReadLastBlockFile(nLastBlockFile);
3485 vinfoBlockFile.resize(nLastBlockFile + 1);
3486 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3487 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3488 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3490 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3491 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3492 CBlockFileInfo info;
3493 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3494 vinfoBlockFile.push_back(info);
3495 } else {
3496 break;
3500 // Check presence of blk files
3501 LogPrintf("Checking all blk files are present...\n");
3502 std::set<int> setBlkDataFiles;
3503 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3505 CBlockIndex* pindex = item.second;
3506 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3507 setBlkDataFiles.insert(pindex->nFile);
3510 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3512 CDiskBlockPos pos(*it, 0);
3513 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3514 return false;
3518 // Check whether we have ever pruned block & undo files
3519 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3520 if (fHavePruned)
3521 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3523 // Check whether we need to continue reindexing
3524 bool fReindexing = false;
3525 pblocktree->ReadReindexing(fReindexing);
3526 fReindex |= fReindexing;
3528 // Check whether we have a transaction index
3529 pblocktree->ReadFlag("txindex", fTxIndex);
3530 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3532 return true;
3535 bool LoadChainTip(const CChainParams& chainparams)
3537 if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
3539 if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
3540 // In case we just added the genesis block, connect it now, so
3541 // that we always have a chainActive.Tip() when we return.
3542 LogPrintf("%s: Connecting genesis block...\n", __func__);
3543 CValidationState state;
3544 if (!ActivateBestChain(state, chainparams)) {
3545 return false;
3549 // Load pointer to end of best chain
3550 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3551 if (it == mapBlockIndex.end())
3552 return false;
3553 chainActive.SetTip(it->second);
3555 PruneBlockIndexCandidates();
3557 LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
3558 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3559 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3560 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3561 return true;
3564 CVerifyDB::CVerifyDB()
3566 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3569 CVerifyDB::~CVerifyDB()
3571 uiInterface.ShowProgress("", 100);
3574 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3576 LOCK(cs_main);
3577 if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
3578 return true;
3580 // Verify blocks in the best chain
3581 if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height())
3582 nCheckDepth = chainActive.Height();
3583 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3584 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3585 CCoinsViewCache coins(coinsview);
3586 CBlockIndex* pindexState = chainActive.Tip();
3587 CBlockIndex* pindexFailure = nullptr;
3588 int nGoodTransactions = 0;
3589 CValidationState state;
3590 int reportDone = 0;
3591 LogPrintf("[0%%]...");
3592 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3594 boost::this_thread::interruption_point();
3595 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3596 if (reportDone < percentageDone/10) {
3597 // report every 10% step
3598 LogPrintf("[%d%%]...", percentageDone);
3599 reportDone = percentageDone/10;
3601 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone);
3602 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3603 break;
3604 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3605 // If pruning, only go back as far as we have data.
3606 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3607 break;
3609 CBlock block;
3610 // check level 0: read from disk
3611 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3612 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3613 // check level 1: verify block validity
3614 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3615 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3616 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3617 // check level 2: verify undo validity
3618 if (nCheckLevel >= 2 && pindex) {
3619 CBlockUndo undo;
3620 CDiskBlockPos pos = pindex->GetUndoPos();
3621 if (!pos.IsNull()) {
3622 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3623 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3626 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3627 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3628 assert(coins.GetBestBlock() == pindex->GetBlockHash());
3629 DisconnectResult res = DisconnectBlock(block, pindex, coins);
3630 if (res == DISCONNECT_FAILED) {
3631 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3633 pindexState = pindex->pprev;
3634 if (res == DISCONNECT_UNCLEAN) {
3635 nGoodTransactions = 0;
3636 pindexFailure = pindex;
3637 } else {
3638 nGoodTransactions += block.vtx.size();
3641 if (ShutdownRequested())
3642 return true;
3644 if (pindexFailure)
3645 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3647 // check level 4: try reconnecting blocks
3648 if (nCheckLevel >= 4) {
3649 CBlockIndex *pindex = pindexState;
3650 while (pindex != chainActive.Tip()) {
3651 boost::this_thread::interruption_point();
3652 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3653 pindex = chainActive.Next(pindex);
3654 CBlock block;
3655 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3656 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3657 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3658 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3662 LogPrintf("[DONE].\n");
3663 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3665 return true;
3668 /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
3669 static bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
3671 // TODO: merge with ConnectBlock
3672 CBlock block;
3673 if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
3674 return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3677 for (const CTransactionRef& tx : block.vtx) {
3678 if (!tx->IsCoinBase()) {
3679 for (const CTxIn &txin : tx->vin) {
3680 inputs.SpendCoin(txin.prevout);
3683 // Pass check = true as every addition may be an overwrite.
3684 AddCoins(inputs, *tx, pindex->nHeight, true);
3686 return true;
3689 bool ReplayBlocks(const CChainParams& params, CCoinsView* view)
3691 LOCK(cs_main);
3693 CCoinsViewCache cache(view);
3695 std::vector<uint256> hashHeads = view->GetHeadBlocks();
3696 if (hashHeads.empty()) return true; // We're already in a consistent state.
3697 if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
3699 uiInterface.ShowProgress(_("Replaying blocks..."), 0);
3700 LogPrintf("Replaying blocks\n");
3702 const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
3703 const CBlockIndex* pindexNew; // New tip during the interrupted flush.
3704 const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
3706 if (mapBlockIndex.count(hashHeads[0]) == 0) {
3707 return error("ReplayBlocks(): reorganization to unknown block requested");
3709 pindexNew = mapBlockIndex[hashHeads[0]];
3711 if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
3712 if (mapBlockIndex.count(hashHeads[1]) == 0) {
3713 return error("ReplayBlocks(): reorganization from unknown block requested");
3715 pindexOld = mapBlockIndex[hashHeads[1]];
3716 pindexFork = LastCommonAncestor(pindexOld, pindexNew);
3717 assert(pindexFork != nullptr);
3720 // Rollback along the old branch.
3721 while (pindexOld != pindexFork) {
3722 if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
3723 CBlock block;
3724 if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
3725 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3727 LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
3728 DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
3729 if (res == DISCONNECT_FAILED) {
3730 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3732 // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
3733 // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
3734 // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
3735 // the result is still a version of the UTXO set with the effects of that block undone.
3737 pindexOld = pindexOld->pprev;
3740 // Roll forward from the forking point to the new tip.
3741 int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
3742 for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
3743 const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
3744 LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
3745 if (!RollforwardBlock(pindex, cache, params)) return false;
3748 cache.SetBestBlock(pindexNew->GetBlockHash());
3749 cache.Flush();
3750 uiInterface.ShowProgress("", 100);
3751 return true;
3754 bool RewindBlockIndex(const CChainParams& params)
3756 LOCK(cs_main);
3758 // Note that during -reindex-chainstate we are called with an empty chainActive!
3760 int nHeight = 1;
3761 while (nHeight <= chainActive.Height()) {
3762 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3763 break;
3765 nHeight++;
3768 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3769 CValidationState state;
3770 CBlockIndex* pindex = chainActive.Tip();
3771 while (chainActive.Height() >= nHeight) {
3772 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3773 // If pruning, don't try rewinding past the HAVE_DATA point;
3774 // since older blocks can't be served anyway, there's
3775 // no need to walk further, and trying to DisconnectTip()
3776 // will fail (and require a needless reindex/redownload
3777 // of the blockchain).
3778 break;
3780 if (!DisconnectTip(state, params, nullptr)) {
3781 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3783 // Occasionally flush state to disk.
3784 if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
3785 return false;
3788 // Reduce validity flag and have-data flags.
3789 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3790 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3791 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3792 CBlockIndex* pindexIter = it->second;
3794 // Note: If we encounter an insufficiently validated block that
3795 // is on chainActive, it must be because we are a pruning node, and
3796 // this block or some successor doesn't HAVE_DATA, so we were unable to
3797 // rewind all the way. Blocks remaining on chainActive at this point
3798 // must not have their validity reduced.
3799 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3800 // Reduce validity
3801 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3802 // Remove have-data flags.
3803 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3804 // Remove storage location.
3805 pindexIter->nFile = 0;
3806 pindexIter->nDataPos = 0;
3807 pindexIter->nUndoPos = 0;
3808 // Remove various other things
3809 pindexIter->nTx = 0;
3810 pindexIter->nChainTx = 0;
3811 pindexIter->nSequenceId = 0;
3812 // Make sure it gets written.
3813 setDirtyBlockIndex.insert(pindexIter);
3814 // Update indexes
3815 setBlockIndexCandidates.erase(pindexIter);
3816 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3817 while (ret.first != ret.second) {
3818 if (ret.first->second == pindexIter) {
3819 mapBlocksUnlinked.erase(ret.first++);
3820 } else {
3821 ++ret.first;
3824 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3825 setBlockIndexCandidates.insert(pindexIter);
3829 if (chainActive.Tip() != nullptr) {
3830 // We can't prune block index candidates based on our tip if we have
3831 // no tip due to chainActive being empty!
3832 PruneBlockIndexCandidates();
3834 CheckBlockIndex(params.GetConsensus());
3836 // FlushStateToDisk can possibly read chainActive. Be conservative
3837 // and skip it here, we're about to -reindex-chainstate anyway, so
3838 // it'll get called a bunch real soon.
3839 if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
3840 return false;
3844 return true;
3847 // May NOT be used after any connections are up as much
3848 // of the peer-processing logic assumes a consistent
3849 // block index state
3850 void UnloadBlockIndex()
3852 LOCK(cs_main);
3853 setBlockIndexCandidates.clear();
3854 chainActive.SetTip(nullptr);
3855 pindexBestInvalid = nullptr;
3856 pindexBestHeader = nullptr;
3857 mempool.clear();
3858 mapBlocksUnlinked.clear();
3859 vinfoBlockFile.clear();
3860 nLastBlockFile = 0;
3861 nBlockSequenceId = 1;
3862 setDirtyBlockIndex.clear();
3863 setDirtyFileInfo.clear();
3864 versionbitscache.Clear();
3865 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3866 warningcache[b].clear();
3869 for (BlockMap::value_type& entry : mapBlockIndex) {
3870 delete entry.second;
3872 mapBlockIndex.clear();
3873 fHavePruned = false;
3876 bool LoadBlockIndex(const CChainParams& chainparams)
3878 // Load block index from databases
3879 bool needs_init = fReindex;
3880 if (!fReindex) {
3881 bool ret = LoadBlockIndexDB(chainparams);
3882 if (!ret) return false;
3883 needs_init = mapBlockIndex.empty();
3886 if (needs_init) {
3887 // Everything here is for *new* reindex/DBs. Thus, though
3888 // LoadBlockIndexDB may have set fReindex if we shut down
3889 // mid-reindex previously, we don't check fReindex and
3890 // instead only check it prior to LoadBlockIndexDB to set
3891 // needs_init.
3893 LogPrintf("Initializing databases...\n");
3894 // Use the provided setting for -txindex in the new database
3895 fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
3896 pblocktree->WriteFlag("txindex", fTxIndex);
3898 return true;
3901 bool LoadGenesisBlock(const CChainParams& chainparams)
3903 LOCK(cs_main);
3905 // Check whether we're already initialized by checking for genesis in
3906 // mapBlockIndex. Note that we can't use chainActive here, since it is
3907 // set based on the coins db, not the block index db, which is the only
3908 // thing loaded at this point.
3909 if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
3910 return true;
3912 try {
3913 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3914 // Start new block file
3915 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3916 CDiskBlockPos blockPos;
3917 CValidationState state;
3918 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3919 return error("%s: FindBlockPos failed", __func__);
3920 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3921 return error("%s: writing genesis block to disk failed", __func__);
3922 CBlockIndex *pindex = AddToBlockIndex(block);
3923 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3924 return error("%s: genesis block not accepted", __func__);
3925 } catch (const std::runtime_error& e) {
3926 return error("%s: failed to write genesis block: %s", __func__, e.what());
3929 return true;
3932 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
3934 // Map of disk positions for blocks with unknown parent (only used for reindex)
3935 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3936 int64_t nStart = GetTimeMillis();
3938 int nLoaded = 0;
3939 try {
3940 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3941 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
3942 uint64_t nRewind = blkdat.GetPos();
3943 while (!blkdat.eof()) {
3944 boost::this_thread::interruption_point();
3946 blkdat.SetPos(nRewind);
3947 nRewind++; // start one byte further next time, in case of failure
3948 blkdat.SetLimit(); // remove former limit
3949 unsigned int nSize = 0;
3950 try {
3951 // locate a header
3952 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
3953 blkdat.FindByte(chainparams.MessageStart()[0]);
3954 nRewind = blkdat.GetPos()+1;
3955 blkdat >> FLATDATA(buf);
3956 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
3957 continue;
3958 // read size
3959 blkdat >> nSize;
3960 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3961 continue;
3962 } catch (const std::exception&) {
3963 // no valid block header found; don't complain
3964 break;
3966 try {
3967 // read block
3968 uint64_t nBlockPos = blkdat.GetPos();
3969 if (dbp)
3970 dbp->nPos = nBlockPos;
3971 blkdat.SetLimit(nBlockPos + nSize);
3972 blkdat.SetPos(nBlockPos);
3973 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3974 CBlock& block = *pblock;
3975 blkdat >> block;
3976 nRewind = blkdat.GetPos();
3978 // detect out of order blocks, and store them for later
3979 uint256 hash = block.GetHash();
3980 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3981 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3982 block.hashPrevBlock.ToString());
3983 if (dbp)
3984 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3985 continue;
3988 // process in case the block isn't known yet
3989 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3990 LOCK(cs_main);
3991 CValidationState state;
3992 if (AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
3993 nLoaded++;
3994 if (state.IsError())
3995 break;
3996 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3997 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4000 // Activate the genesis block so normal node progress can continue
4001 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
4002 CValidationState state;
4003 if (!ActivateBestChain(state, chainparams)) {
4004 break;
4008 NotifyHeaderTip();
4010 // Recursively process earlier encountered successors of this block
4011 std::deque<uint256> queue;
4012 queue.push_back(hash);
4013 while (!queue.empty()) {
4014 uint256 head = queue.front();
4015 queue.pop_front();
4016 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4017 while (range.first != range.second) {
4018 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4019 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4020 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
4022 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4023 head.ToString());
4024 LOCK(cs_main);
4025 CValidationState dummy;
4026 if (AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
4028 nLoaded++;
4029 queue.push_back(pblockrecursive->GetHash());
4032 range.first++;
4033 mapBlocksUnknownParent.erase(it);
4034 NotifyHeaderTip();
4037 } catch (const std::exception& e) {
4038 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4041 } catch (const std::runtime_error& e) {
4042 AbortNode(std::string("System error: ") + e.what());
4044 if (nLoaded > 0)
4045 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4046 return nLoaded > 0;
4049 void static CheckBlockIndex(const Consensus::Params& consensusParams)
4051 if (!fCheckBlockIndex) {
4052 return;
4055 LOCK(cs_main);
4057 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4058 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4059 // iterating the block tree require that chainActive has been initialized.)
4060 if (chainActive.Height() < 0) {
4061 assert(mapBlockIndex.size() <= 1);
4062 return;
4065 // Build forward-pointing map of the entire block tree.
4066 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4067 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4068 forward.insert(std::make_pair(it->second->pprev, it->second));
4071 assert(forward.size() == mapBlockIndex.size());
4073 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4074 CBlockIndex *pindex = rangeGenesis.first->second;
4075 rangeGenesis.first++;
4076 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4078 // Iterate over the entire block tree, using depth-first search.
4079 // Along the way, remember whether there are blocks on the path from genesis
4080 // block being explored which are the first to have certain properties.
4081 size_t nNodes = 0;
4082 int nHeight = 0;
4083 CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4084 CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4085 CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4086 CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4087 CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4088 CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4089 CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4090 while (pindex != nullptr) {
4091 nNodes++;
4092 if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4093 if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4094 if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4095 if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4096 if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4097 if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4098 if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4100 // Begin: actual consistency checks.
4101 if (pindex->pprev == nullptr) {
4102 // Genesis block checks.
4103 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4104 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4106 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)
4107 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4108 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4109 if (!fHavePruned) {
4110 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4111 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4112 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4113 } else {
4114 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4115 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4117 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4118 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4119 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4120 assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4121 assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
4122 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4123 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.
4124 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4125 assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
4126 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4127 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4128 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4129 if (pindexFirstInvalid == nullptr) {
4130 // Checks for not-invalid blocks.
4131 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4133 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
4134 if (pindexFirstInvalid == nullptr) {
4135 // If this block sorts at least as good as the current tip and
4136 // is valid and we have all data for its parents, it must be in
4137 // setBlockIndexCandidates. chainActive.Tip() must also be there
4138 // even if some data has been pruned.
4139 if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
4140 assert(setBlockIndexCandidates.count(pindex));
4142 // If some parent is missing, then it could be that this block was in
4143 // setBlockIndexCandidates but had to be removed because of the missing data.
4144 // In this case it must be in mapBlocksUnlinked -- see test below.
4146 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4147 assert(setBlockIndexCandidates.count(pindex) == 0);
4149 // Check whether this block is in mapBlocksUnlinked.
4150 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4151 bool foundInUnlinked = false;
4152 while (rangeUnlinked.first != rangeUnlinked.second) {
4153 assert(rangeUnlinked.first->first == pindex->pprev);
4154 if (rangeUnlinked.first->second == pindex) {
4155 foundInUnlinked = true;
4156 break;
4158 rangeUnlinked.first++;
4160 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4161 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4162 assert(foundInUnlinked);
4164 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4165 if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4166 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4167 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4168 assert(fHavePruned); // We must have pruned.
4169 // This block may have entered mapBlocksUnlinked if:
4170 // - it has a descendant that at some point had more work than the
4171 // tip, and
4172 // - we tried switching to that descendant but were missing
4173 // data for some intermediate block between chainActive and the
4174 // tip.
4175 // So if this block is itself better than chainActive.Tip() and it wasn't in
4176 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4177 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4178 if (pindexFirstInvalid == nullptr) {
4179 assert(foundInUnlinked);
4183 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4184 // End: actual consistency checks.
4186 // Try descending into the first subnode.
4187 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4188 if (range.first != range.second) {
4189 // A subnode was found.
4190 pindex = range.first->second;
4191 nHeight++;
4192 continue;
4194 // This is a leaf node.
4195 // Move upwards until we reach a node of which we have not yet visited the last child.
4196 while (pindex) {
4197 // We are going to either move to a parent or a sibling of pindex.
4198 // If pindex was the first with a certain property, unset the corresponding variable.
4199 if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4200 if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4201 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4202 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4203 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4204 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4205 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4206 // Find our parent.
4207 CBlockIndex* pindexPar = pindex->pprev;
4208 // Find which child we just visited.
4209 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4210 while (rangePar.first->second != pindex) {
4211 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4212 rangePar.first++;
4214 // Proceed to the next one.
4215 rangePar.first++;
4216 if (rangePar.first != rangePar.second) {
4217 // Move to the sibling.
4218 pindex = rangePar.first->second;
4219 break;
4220 } else {
4221 // Move up further.
4222 pindex = pindexPar;
4223 nHeight--;
4224 continue;
4229 // Check that we actually traversed the entire map.
4230 assert(nNodes == forward.size());
4233 std::string CBlockFileInfo::ToString() const
4235 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));
4238 CBlockFileInfo* GetBlockFileInfo(size_t n)
4240 return &vinfoBlockFile.at(n);
4243 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
4245 LOCK(cs_main);
4246 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4249 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
4251 LOCK(cs_main);
4252 return VersionBitsStatistics(chainActive.Tip(), params, pos);
4255 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
4257 LOCK(cs_main);
4258 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
4261 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4263 bool LoadMempool(void)
4265 const CChainParams& chainparams = Params();
4266 int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4267 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4268 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4269 if (file.IsNull()) {
4270 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4271 return false;
4274 int64_t count = 0;
4275 int64_t skipped = 0;
4276 int64_t failed = 0;
4277 int64_t nNow = GetTime();
4279 try {
4280 uint64_t version;
4281 file >> version;
4282 if (version != MEMPOOL_DUMP_VERSION) {
4283 return false;
4285 uint64_t num;
4286 file >> num;
4287 while (num--) {
4288 CTransactionRef tx;
4289 int64_t nTime;
4290 int64_t nFeeDelta;
4291 file >> tx;
4292 file >> nTime;
4293 file >> nFeeDelta;
4295 CAmount amountdelta = nFeeDelta;
4296 if (amountdelta) {
4297 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4299 CValidationState state;
4300 if (nTime + nExpiryTimeout > nNow) {
4301 LOCK(cs_main);
4302 AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, true, nullptr, nTime, nullptr, false, 0);
4303 if (state.IsValid()) {
4304 ++count;
4305 } else {
4306 ++failed;
4308 } else {
4309 ++skipped;
4311 if (ShutdownRequested())
4312 return false;
4314 std::map<uint256, CAmount> mapDeltas;
4315 file >> mapDeltas;
4317 for (const auto& i : mapDeltas) {
4318 mempool.PrioritiseTransaction(i.first, i.second);
4320 } catch (const std::exception& e) {
4321 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4322 return false;
4325 LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
4326 return true;
4329 void DumpMempool(void)
4331 int64_t start = GetTimeMicros();
4333 std::map<uint256, CAmount> mapDeltas;
4334 std::vector<TxMempoolInfo> vinfo;
4337 LOCK(mempool.cs);
4338 for (const auto &i : mempool.mapDeltas) {
4339 mapDeltas[i.first] = i.second;
4341 vinfo = mempool.infoAll();
4344 int64_t mid = GetTimeMicros();
4346 try {
4347 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4348 if (!filestr) {
4349 return;
4352 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4354 uint64_t version = MEMPOOL_DUMP_VERSION;
4355 file << version;
4357 file << (uint64_t)vinfo.size();
4358 for (const auto& i : vinfo) {
4359 file << *(i.tx);
4360 file << (int64_t)i.nTime;
4361 file << (int64_t)i.nFeeDelta;
4362 mapDeltas.erase(i.tx->GetHash());
4365 file << mapDeltas;
4366 FileCommit(file.Get());
4367 file.fclose();
4368 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4369 int64_t last = GetTimeMicros();
4370 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*0.000001, (last-mid)*0.000001);
4371 } catch (const std::exception& e) {
4372 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4376 //! Guess how far we are in the verification process at the given block index
4377 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4378 if (pindex == nullptr)
4379 return 0.0;
4381 int64_t nNow = time(nullptr);
4383 double fTxTotal;
4385 if (pindex->nChainTx <= data.nTxCount) {
4386 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4387 } else {
4388 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4391 return pindex->nChainTx / fTxTotal;
4394 class CMainCleanup
4396 public:
4397 CMainCleanup() {}
4398 ~CMainCleanup() {
4399 // block headers
4400 BlockMap::iterator it1 = mapBlockIndex.begin();
4401 for (; it1 != mapBlockIndex.end(); it1++)
4402 delete (*it1).second;
4403 mapBlockIndex.clear();
4405 } instance_of_cmaincleanup;