Merge #11722: Switched sync.{cpp,h} to std threading primitives.
[bitcoinplatinum.git] / src / validation.cpp
blob99ea1433f9c7e728c880225a4204a978e699cb2c
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include <validation.h>
8 #include <arith_uint256.h>
9 #include <chain.h>
10 #include <chainparams.h>
11 #include <checkpoints.h>
12 #include <checkqueue.h>
13 #include <consensus/consensus.h>
14 #include <consensus/merkle.h>
15 #include <consensus/tx_verify.h>
16 #include <consensus/validation.h>
17 #include <cuckoocache.h>
18 #include <fs.h>
19 #include <hash.h>
20 #include <init.h>
21 #include <policy/fees.h>
22 #include <policy/policy.h>
23 #include <policy/rbf.h>
24 #include <pow.h>
25 #include <primitives/block.h>
26 #include <primitives/transaction.h>
27 #include <random.h>
28 #include <reverse_iterator.h>
29 #include <script/script.h>
30 #include <script/sigcache.h>
31 #include <script/standard.h>
32 #include <timedata.h>
33 #include <tinyformat.h>
34 #include <txdb.h>
35 #include <txmempool.h>
36 #include <ui_interface.h>
37 #include <undo.h>
38 #include <util.h>
39 #include <utilmoneystr.h>
40 #include <utilstrencodings.h>
41 #include <validationinterface.h>
42 #include <versionbits.h>
43 #include <warnings.h>
45 #include <atomic>
46 #include <sstream>
48 #include <boost/algorithm/string/replace.hpp>
49 #include <boost/algorithm/string/join.hpp>
50 #include <boost/thread.hpp>
52 #if defined(NDEBUG)
53 # error "Bitcoin cannot be compiled without assertions."
54 #endif
56 #define MICRO 0.000001
57 #define MILLI 0.001
59 /**
60 * Global state
63 CCriticalSection cs_main;
65 BlockMap mapBlockIndex;
66 CChain chainActive;
67 CBlockIndex *pindexBestHeader = nullptr;
68 CWaitableCriticalSection csBestBlock;
69 CConditionVariable cvBlockChange;
70 int nScriptCheckThreads = 0;
71 std::atomic_bool fImporting(false);
72 std::atomic_bool fReindex(false);
73 bool fTxIndex = false;
74 bool fHavePruned = false;
75 bool fPruneMode = false;
76 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
77 bool fRequireStandard = true;
78 bool fCheckBlockIndex = false;
79 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
80 size_t nCoinCacheUsage = 5000 * 300;
81 uint64_t nPruneTarget = 0;
82 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
83 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
85 uint256 hashAssumeValid;
86 arith_uint256 nMinimumChainWork;
88 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
89 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
91 CBlockPolicyEstimator feeEstimator;
92 CTxMemPool mempool(&feeEstimator);
94 static void CheckBlockIndex(const Consensus::Params& consensusParams);
96 /** Constant stuff for coinbase transactions we create: */
97 CScript COINBASE_FLAGS;
99 const std::string strMessageMagic = "Bitcoin Signed Message:\n";
101 // Internal stuff
102 namespace {
104 struct CBlockIndexWorkComparator
106 bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
107 // First sort by most total work, ...
108 if (pa->nChainWork > pb->nChainWork) return false;
109 if (pa->nChainWork < pb->nChainWork) return true;
111 // ... then by earliest time received, ...
112 if (pa->nSequenceId < pb->nSequenceId) return false;
113 if (pa->nSequenceId > pb->nSequenceId) return true;
115 // Use pointer address as tie breaker (should only happen with blocks
116 // loaded from disk, as those all have id 0).
117 if (pa < pb) return false;
118 if (pa > pb) return true;
120 // Identical blocks.
121 return false;
125 CBlockIndex *pindexBestInvalid;
128 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
129 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
130 * missing the data for the block.
132 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
133 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
134 * Pruned nodes may have entries where B is missing data.
136 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
138 CCriticalSection cs_LastBlockFile;
139 std::vector<CBlockFileInfo> vinfoBlockFile;
140 int nLastBlockFile = 0;
141 /** Global flag to indicate we should check to see if there are
142 * block/undo files that should be deleted. Set on startup
143 * or if we allocate more file space when we're in prune mode
145 bool fCheckForPruning = false;
148 * Every received block is assigned a unique and increasing identifier, so we
149 * know which one to give priority in case of a fork.
151 CCriticalSection cs_nBlockSequenceId;
152 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
153 int32_t nBlockSequenceId = 1;
154 /** Decreasing counter (used by subsequent preciousblock calls). */
155 int32_t nBlockReverseSequenceId = -1;
156 /** chainwork for the last block that preciousblock has been applied to. */
157 arith_uint256 nLastPreciousChainwork = 0;
159 /** In order to efficiently track invalidity of headers, we keep the set of
160 * blocks which we tried to connect and found to be invalid here (ie which
161 * were set to BLOCK_FAILED_VALID since the last restart). We can then
162 * walk this set and check if a new header is a descendant of something in
163 * this set, preventing us from having to walk mapBlockIndex when we try
164 * to connect a bad block and fail.
166 * While this is more complicated than marking everything which descends
167 * from an invalid block as invalid at the time we discover it to be
168 * invalid, doing so would require walking all of mapBlockIndex to find all
169 * descendants. Since this case should be very rare, keeping track of all
170 * BLOCK_FAILED_VALID blocks in a set should be just fine and work just as
171 * well.
173 * Because we already walk mapBlockIndex in height-order at startup, we go
174 * ahead and mark descendants of invalid blocks as FAILED_CHILD at that time,
175 * instead of putting things in this set.
177 std::set<CBlockIndex*> g_failed_blocks;
179 /** Dirty block index entries. */
180 std::set<CBlockIndex*> setDirtyBlockIndex;
182 /** Dirty block file entries. */
183 std::set<int> setDirtyFileInfo;
184 } // anon namespace
186 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
188 // Find the first block the caller has in the main chain
189 for (const uint256& hash : locator.vHave) {
190 BlockMap::iterator mi = mapBlockIndex.find(hash);
191 if (mi != mapBlockIndex.end())
193 CBlockIndex* pindex = (*mi).second;
194 if (chain.Contains(pindex))
195 return pindex;
196 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
197 return chain.Tip();
201 return chain.Genesis();
204 std::unique_ptr<CCoinsViewDB> pcoinsdbview;
205 std::unique_ptr<CCoinsViewCache> pcoinsTip;
206 std::unique_ptr<CBlockTreeDB> pblocktree;
208 enum FlushStateMode {
209 FLUSH_STATE_NONE,
210 FLUSH_STATE_IF_NEEDED,
211 FLUSH_STATE_PERIODIC,
212 FLUSH_STATE_ALWAYS
215 // See definition for documentation
216 static bool FlushStateToDisk(const CChainParams& chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
217 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
218 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
219 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);
220 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
222 bool CheckFinalTx(const CTransaction &tx, int flags)
224 AssertLockHeld(cs_main);
226 // By convention a negative value for flags indicates that the
227 // current network-enforced consensus rules should be used. In
228 // a future soft-fork scenario that would mean checking which
229 // rules would be enforced for the next block and setting the
230 // appropriate flags. At the present time no soft-forks are
231 // scheduled, so no flags are set.
232 flags = std::max(flags, 0);
234 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
235 // nLockTime because when IsFinalTx() is called within
236 // CBlock::AcceptBlock(), the height of the block *being*
237 // evaluated is what is used. Thus if we want to know if a
238 // transaction can be part of the *next* block, we need to call
239 // IsFinalTx() with one more than chainActive.Height().
240 const int nBlockHeight = chainActive.Height() + 1;
242 // BIP113 requires that time-locked transactions have nLockTime set to
243 // less than the median time of the previous block they're contained in.
244 // When the next block is created its previous block will be the current
245 // chain tip, so we use that to calculate the median time passed to
246 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
247 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
248 ? chainActive.Tip()->GetMedianTimePast()
249 : GetAdjustedTime();
251 return IsFinalTx(tx, nBlockHeight, nBlockTime);
254 bool TestLockPointValidity(const LockPoints* lp)
256 AssertLockHeld(cs_main);
257 assert(lp);
258 // If there are relative lock times then the maxInputBlock will be set
259 // If there are no relative lock times, the LockPoints don't depend on the chain
260 if (lp->maxInputBlock) {
261 // Check whether chainActive is an extension of the block at which the LockPoints
262 // calculation was valid. If not LockPoints are no longer valid
263 if (!chainActive.Contains(lp->maxInputBlock)) {
264 return false;
268 // LockPoints still valid
269 return true;
272 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
274 AssertLockHeld(cs_main);
275 AssertLockHeld(mempool.cs);
277 CBlockIndex* tip = chainActive.Tip();
278 assert(tip != nullptr);
280 CBlockIndex index;
281 index.pprev = tip;
282 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
283 // height based locks because when SequenceLocks() is called within
284 // ConnectBlock(), the height of the block *being*
285 // evaluated is what is used.
286 // Thus if we want to know if a transaction can be part of the
287 // *next* block, we need to use one more than chainActive.Height()
288 index.nHeight = tip->nHeight + 1;
290 std::pair<int, int64_t> lockPair;
291 if (useExistingLockPoints) {
292 assert(lp);
293 lockPair.first = lp->height;
294 lockPair.second = lp->time;
296 else {
297 // pcoinsTip contains the UTXO set for chainActive.Tip()
298 CCoinsViewMemPool viewMemPool(pcoinsTip.get(), mempool);
299 std::vector<int> prevheights;
300 prevheights.resize(tx.vin.size());
301 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
302 const CTxIn& txin = tx.vin[txinIndex];
303 Coin coin;
304 if (!viewMemPool.GetCoin(txin.prevout, coin)) {
305 return error("%s: Missing input", __func__);
307 if (coin.nHeight == MEMPOOL_HEIGHT) {
308 // Assume all mempool transaction confirm in the next block
309 prevheights[txinIndex] = tip->nHeight + 1;
310 } else {
311 prevheights[txinIndex] = coin.nHeight;
314 lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
315 if (lp) {
316 lp->height = lockPair.first;
317 lp->time = lockPair.second;
318 // Also store the hash of the block with the highest height of
319 // all the blocks which have sequence locked prevouts.
320 // This hash needs to still be on the chain
321 // for these LockPoint calculations to be valid
322 // Note: It is impossible to correctly calculate a maxInputBlock
323 // if any of the sequence locked inputs depend on unconfirmed txs,
324 // except in the special case where the relative lock time/height
325 // is 0, which is equivalent to no sequence lock. Since we assume
326 // input height of tip+1 for mempool txs and test the resulting
327 // lockPair from CalculateSequenceLocks against tip+1. We know
328 // EvaluateSequenceLocks will fail if there was a non-zero sequence
329 // lock on a mempool input, so we can use the return value of
330 // CheckSequenceLocks to indicate the LockPoints validity
331 int maxInputHeight = 0;
332 for (int height : prevheights) {
333 // Can ignore mempool inputs since we'll fail if they had non-zero locks
334 if (height != tip->nHeight+1) {
335 maxInputHeight = std::max(maxInputHeight, height);
338 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
341 return EvaluateSequenceLocks(index, lockPair);
344 // Returns the script flags which should be checked for a given block
345 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
347 static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
348 int expired = pool.Expire(GetTime() - age);
349 if (expired != 0) {
350 LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
353 std::vector<COutPoint> vNoSpendsRemaining;
354 pool.TrimToSize(limit, &vNoSpendsRemaining);
355 for (const COutPoint& removed : vNoSpendsRemaining)
356 pcoinsTip->Uncache(removed);
359 /** Convert CValidationState to a human-readable message for logging */
360 std::string FormatStateMessage(const CValidationState &state)
362 return strprintf("%s%s (code %i)",
363 state.GetRejectReason(),
364 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
365 state.GetRejectCode());
368 static bool IsCurrentForFeeEstimation()
370 AssertLockHeld(cs_main);
371 if (IsInitialBlockDownload())
372 return false;
373 if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
374 return false;
375 if (chainActive.Height() < pindexBestHeader->nHeight - 1)
376 return false;
377 return true;
380 /* Make mempool consistent after a reorg, by re-adding or recursively erasing
381 * disconnected block transactions from the mempool, and also removing any
382 * other transactions from the mempool that are no longer valid given the new
383 * tip/height.
385 * Note: we assume that disconnectpool only contains transactions that are NOT
386 * confirmed in the current chain nor already in the mempool (otherwise,
387 * in-mempool descendants of such transactions would be removed).
389 * Passing fAddToMempool=false will skip trying to add the transactions back,
390 * and instead just erase from the mempool as needed.
393 void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
395 AssertLockHeld(cs_main);
396 std::vector<uint256> vHashUpdate;
397 // disconnectpool's insertion_order index sorts the entries from
398 // oldest to newest, but the oldest entry will be the last tx from the
399 // latest mined block that was disconnected.
400 // Iterate disconnectpool in reverse, so that we add transactions
401 // back to the mempool starting with the earliest transaction that had
402 // been previously seen in a block.
403 auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
404 while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
405 // ignore validation errors in resurrected transactions
406 CValidationState stateDummy;
407 if (!fAddToMempool || (*it)->IsCoinBase() ||
408 !AcceptToMemoryPool(mempool, stateDummy, *it, nullptr /* pfMissingInputs */,
409 nullptr /* plTxnReplaced */, true /* bypass_limits */, 0 /* nAbsurdFee */)) {
410 // If the transaction doesn't make it in to the mempool, remove any
411 // transactions that depend on it (which would now be orphans).
412 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
413 } else if (mempool.exists((*it)->GetHash())) {
414 vHashUpdate.push_back((*it)->GetHash());
416 ++it;
418 disconnectpool.queuedTx.clear();
419 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
420 // no in-mempool children, which is generally not true when adding
421 // previously-confirmed transactions back to the mempool.
422 // UpdateTransactionsFromBlock finds descendants of any transactions in
423 // the disconnectpool that were added back and cleans up the mempool state.
424 mempool.UpdateTransactionsFromBlock(vHashUpdate);
426 // We also need to remove any now-immature transactions
427 mempool.removeForReorg(pcoinsTip.get(), chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
428 // Re-limit mempool size, in case we added any transactions
429 LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
432 // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
433 // were somehow broken and returning the wrong scriptPubKeys
434 static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool& pool,
435 unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) {
436 AssertLockHeld(cs_main);
438 // pool.cs should be locked already, but go ahead and re-take the lock here
439 // to enforce that mempool doesn't change between when we check the view
440 // and when we actually call through to CheckInputs
441 LOCK(pool.cs);
443 assert(!tx.IsCoinBase());
444 for (const CTxIn& txin : tx.vin) {
445 const Coin& coin = view.AccessCoin(txin.prevout);
447 // At this point we haven't actually checked if the coins are all
448 // available (or shouldn't assume we have, since CheckInputs does).
449 // So we just return failure if the inputs are not available here,
450 // and then only have to check equivalence for available inputs.
451 if (coin.IsSpent()) return false;
453 const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
454 if (txFrom) {
455 assert(txFrom->GetHash() == txin.prevout.hash);
456 assert(txFrom->vout.size() > txin.prevout.n);
457 assert(txFrom->vout[txin.prevout.n] == coin.out);
458 } else {
459 const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout);
460 assert(!coinFromDisk.IsSpent());
461 assert(coinFromDisk.out == coin.out);
465 return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata);
468 static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx,
469 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
470 bool bypass_limits, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache)
472 const CTransaction& tx = *ptx;
473 const uint256 hash = tx.GetHash();
474 AssertLockHeld(cs_main);
475 if (pfMissingInputs)
476 *pfMissingInputs = false;
478 if (!CheckTransaction(tx, state))
479 return false; // state filled in by CheckTransaction
481 // Coinbase is only valid in a block, not as a loose transaction
482 if (tx.IsCoinBase())
483 return state.DoS(100, false, REJECT_INVALID, "coinbase");
485 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
486 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), chainparams.GetConsensus());
487 if (!gArgs.GetBoolArg("-prematurewitness", false) && tx.HasWitness() && !witnessEnabled) {
488 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
491 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
492 std::string reason;
493 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
494 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
496 // Only accept nLockTime-using transactions that can be mined in the next
497 // block; we don't want our mempool filled up with transactions that can't
498 // be mined yet.
499 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
500 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
502 // is it already in the memory pool?
503 if (pool.exists(hash)) {
504 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool");
507 // Check for conflicts with in-memory transactions
508 std::set<uint256> setConflicts;
510 LOCK(pool.cs); // protect pool.mapNextTx
511 for (const CTxIn &txin : tx.vin)
513 auto itConflicting = pool.mapNextTx.find(txin.prevout);
514 if (itConflicting != pool.mapNextTx.end())
516 const CTransaction *ptxConflicting = itConflicting->second;
517 if (!setConflicts.count(ptxConflicting->GetHash()))
519 // Allow opt-out of transaction replacement by setting
520 // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
522 // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
523 // non-replaceable transactions. All inputs rather than just one
524 // is for the sake of multi-party protocols, where we don't
525 // want a single party to be able to disable replacement.
527 // The opt-out ignores descendants as anyone relying on
528 // first-seen mempool behavior should be checking all
529 // unconfirmed ancestors anyway; doing otherwise is hopelessly
530 // insecure.
531 bool fReplacementOptOut = true;
532 if (fEnableReplacement)
534 for (const CTxIn &_txin : ptxConflicting->vin)
536 if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
538 fReplacementOptOut = false;
539 break;
543 if (fReplacementOptOut) {
544 return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict");
547 setConflicts.insert(ptxConflicting->GetHash());
554 CCoinsView dummy;
555 CCoinsViewCache view(&dummy);
557 LockPoints lp;
559 LOCK(pool.cs);
560 CCoinsViewMemPool viewMemPool(pcoinsTip.get(), pool);
561 view.SetBackend(viewMemPool);
563 // do all inputs exist?
564 for (const CTxIn txin : tx.vin) {
565 if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
566 coins_to_uncache.push_back(txin.prevout);
568 if (!view.HaveCoin(txin.prevout)) {
569 // Are inputs missing because we already have the tx?
570 for (size_t out = 0; out < tx.vout.size(); out++) {
571 // Optimistically just do efficient check of cache for outputs
572 if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
573 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
576 // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
577 if (pfMissingInputs) {
578 *pfMissingInputs = true;
580 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
584 // Bring the best block into scope
585 view.GetBestBlock();
587 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
588 view.SetBackend(dummy);
590 // Only accept BIP68 sequence locked transactions that can be mined in the next
591 // block; we don't want our mempool filled up with transactions that can't
592 // be mined yet.
593 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
594 // CoinsViewCache instead of create its own
595 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
596 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
598 } // end LOCK(pool.cs)
600 CAmount nFees = 0;
601 if (!Consensus::CheckTxInputs(tx, state, view, GetSpendHeight(view), nFees)) {
602 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
605 // Check for non-standard pay-to-script-hash in inputs
606 if (fRequireStandard && !AreInputsStandard(tx, view))
607 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
609 // Check for non-standard witness in P2WSH
610 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
611 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
613 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
615 // nModifiedFees includes any fee deltas from PrioritiseTransaction
616 CAmount nModifiedFees = nFees;
617 pool.ApplyDelta(hash, nModifiedFees);
619 // Keep track of transactions that spend a coinbase, which we re-scan
620 // during reorgs to ensure COINBASE_MATURITY is still met.
621 bool fSpendsCoinbase = false;
622 for (const CTxIn &txin : tx.vin) {
623 const Coin &coin = view.AccessCoin(txin.prevout);
624 if (coin.IsCoinBase()) {
625 fSpendsCoinbase = true;
626 break;
630 CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
631 fSpendsCoinbase, nSigOpsCost, lp);
632 unsigned int nSize = entry.GetTxSize();
634 // Check that the transaction doesn't have an excessive number of
635 // sigops, making it impossible to mine. Since the coinbase transaction
636 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
637 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
638 // merely non-standard transaction.
639 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
640 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
641 strprintf("%d", nSigOpsCost));
643 CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
644 if (!bypass_limits && mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
645 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
648 // No transactions are allowed below minRelayTxFee except from disconnected blocks
649 if (!bypass_limits && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
650 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
653 if (nAbsurdFee && nFees > nAbsurdFee)
654 return state.Invalid(false,
655 REJECT_HIGHFEE, "absurdly-high-fee",
656 strprintf("%d > %d", nFees, nAbsurdFee));
658 // Calculate in-mempool ancestors, up to a limit.
659 CTxMemPool::setEntries setAncestors;
660 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
661 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
662 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
663 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
664 std::string errString;
665 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
666 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
669 // A transaction that spends outputs that would be replaced by it is invalid. Now
670 // that we have the set of all ancestors we can detect this
671 // pathological case by making sure setConflicts and setAncestors don't
672 // intersect.
673 for (CTxMemPool::txiter ancestorIt : setAncestors)
675 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
676 if (setConflicts.count(hashAncestor))
678 return state.DoS(10, false,
679 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
680 strprintf("%s spends conflicting transaction %s",
681 hash.ToString(),
682 hashAncestor.ToString()));
686 // Check if it's economically rational to mine this transaction rather
687 // than the ones it replaces.
688 CAmount nConflictingFees = 0;
689 size_t nConflictingSize = 0;
690 uint64_t nConflictingCount = 0;
691 CTxMemPool::setEntries allConflicting;
693 // If we don't hold the lock allConflicting might be incomplete; the
694 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
695 // mempool consistency for us.
696 LOCK(pool.cs);
697 const bool fReplacementTransaction = setConflicts.size();
698 if (fReplacementTransaction)
700 CFeeRate newFeeRate(nModifiedFees, nSize);
701 std::set<uint256> setConflictsParents;
702 const int maxDescendantsToVisit = 100;
703 CTxMemPool::setEntries setIterConflicting;
704 for (const uint256 &hashConflicting : setConflicts)
706 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
707 if (mi == pool.mapTx.end())
708 continue;
710 // Save these to avoid repeated lookups
711 setIterConflicting.insert(mi);
713 // Don't allow the replacement to reduce the feerate of the
714 // mempool.
716 // We usually don't want to accept replacements with lower
717 // feerates than what they replaced as that would lower the
718 // feerate of the next block. Requiring that the feerate always
719 // be increased is also an easy-to-reason about way to prevent
720 // DoS attacks via replacements.
722 // The mining code doesn't (currently) take children into
723 // account (CPFP) so we only consider the feerates of
724 // transactions being directly replaced, not their indirect
725 // descendants. While that does mean high feerate children are
726 // ignored when deciding whether or not to replace, we do
727 // require the replacement to pay more overall fees too,
728 // mitigating most cases.
729 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
730 if (newFeeRate <= oldFeeRate)
732 return state.DoS(0, false,
733 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
734 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
735 hash.ToString(),
736 newFeeRate.ToString(),
737 oldFeeRate.ToString()));
740 for (const CTxIn &txin : mi->GetTx().vin)
742 setConflictsParents.insert(txin.prevout.hash);
745 nConflictingCount += mi->GetCountWithDescendants();
747 // This potentially overestimates the number of actual descendants
748 // but we just want to be conservative to avoid doing too much
749 // work.
750 if (nConflictingCount <= maxDescendantsToVisit) {
751 // If not too many to replace, then calculate the set of
752 // transactions that would have to be evicted
753 for (CTxMemPool::txiter it : setIterConflicting) {
754 pool.CalculateDescendants(it, allConflicting);
756 for (CTxMemPool::txiter it : allConflicting) {
757 nConflictingFees += it->GetModifiedFee();
758 nConflictingSize += it->GetTxSize();
760 } else {
761 return state.DoS(0, false,
762 REJECT_NONSTANDARD, "too many potential replacements", false,
763 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
764 hash.ToString(),
765 nConflictingCount,
766 maxDescendantsToVisit));
769 for (unsigned int j = 0; j < tx.vin.size(); j++)
771 // We don't want to accept replacements that require low
772 // feerate junk to be mined first. Ideally we'd keep track of
773 // the ancestor feerates and make the decision based on that,
774 // but for now requiring all new inputs to be confirmed works.
775 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
777 // Rather than check the UTXO set - potentially expensive -
778 // it's cheaper to just check if the new input refers to a
779 // tx that's in the mempool.
780 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
781 return state.DoS(0, false,
782 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
783 strprintf("replacement %s adds unconfirmed input, idx %d",
784 hash.ToString(), j));
788 // The replacement must pay greater fees than the transactions it
789 // replaces - if we did the bandwidth used by those conflicting
790 // transactions would not be paid for.
791 if (nModifiedFees < nConflictingFees)
793 return state.DoS(0, false,
794 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
795 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
796 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
799 // Finally in addition to paying more fees than the conflicts the
800 // new transaction must pay for its own bandwidth.
801 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
802 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
804 return state.DoS(0, false,
805 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
806 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
807 hash.ToString(),
808 FormatMoney(nDeltaFees),
809 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
813 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
814 if (!chainparams.RequireStandard()) {
815 scriptVerifyFlags = gArgs.GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
818 // Check against previous transactions
819 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
820 PrecomputedTransactionData txdata(tx);
821 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, txdata)) {
822 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
823 // need to turn both off, and compare against just turning off CLEANSTACK
824 // to see if the failure is specifically due to witness validation.
825 CValidationState stateDummy; // Want reported failures to be from first CheckInputs
826 if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
827 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
828 // Only the witness is missing, so the transaction itself may be fine.
829 state.SetCorruptionPossible();
831 return false; // state filled in by CheckInputs
834 // Check again against the current block tip's script verification
835 // flags to cache our script execution flags. This is, of course,
836 // useless if the next block has different script flags from the
837 // previous one, but because the cache tracks script flags for us it
838 // will auto-invalidate and we'll just have a few blocks of extra
839 // misses on soft-fork activation.
841 // This is also useful in case of bugs in the standard flags that cause
842 // transactions to pass as valid when they're actually invalid. For
843 // instance the STRICTENC flag was incorrectly allowing certain
844 // CHECKSIG NOT scripts to pass, even though they were invalid.
846 // There is a similar check in CreateNewBlock() to prevent creating
847 // invalid blocks (using TestBlockValidity), however allowing such
848 // transactions into the mempool can be exploited as a DoS attack.
849 unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus());
850 if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata))
852 // If we're using promiscuousmempoolflags, we may hit this normally
853 // Check if current block has some flags that scriptVerifyFlags
854 // does not before printing an ominous warning
855 if (!(~scriptVerifyFlags & currentBlockScriptVerifyFlags)) {
856 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against latest-block but not STANDARD flags %s, %s",
857 __func__, hash.ToString(), FormatStateMessage(state));
858 } else {
859 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, false, txdata)) {
860 return error("%s: ConnectInputs failed against MANDATORY but not STANDARD flags due to promiscuous mempool %s, %s",
861 __func__, hash.ToString(), FormatStateMessage(state));
862 } else {
863 LogPrintf("Warning: -promiscuousmempool flags set to not include currently enforced soft forks, this may break mining or otherwise cause instability!\n");
868 // Remove conflicting transactions from the mempool
869 for (const CTxMemPool::txiter it : allConflicting)
871 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
872 it->GetTx().GetHash().ToString(),
873 hash.ToString(),
874 FormatMoney(nModifiedFees - nConflictingFees),
875 (int)nSize - (int)nConflictingSize);
876 if (plTxnReplaced)
877 plTxnReplaced->push_back(it->GetSharedTx());
879 pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
881 // This transaction should only count for fee estimation if:
882 // - it isn't a BIP 125 replacement transaction (may not be widely supported)
883 // - it's not being readded during a reorg which bypasses typical mempool fee limits
884 // - the node is not behind
885 // - the transaction is not dependent on any other transactions in the mempool
886 bool validForFeeEstimation = !fReplacementTransaction && !bypass_limits && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
888 // Store transaction in memory
889 pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
891 // trim mempool and check if tx was trimmed
892 if (!bypass_limits) {
893 LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
894 if (!pool.exists(hash))
895 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
899 GetMainSignals().TransactionAddedToMempool(ptx);
901 return true;
904 /** (try to) add transaction to memory pool with a specified acceptance time **/
905 static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
906 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
907 bool bypass_limits, const CAmount nAbsurdFee)
909 std::vector<COutPoint> coins_to_uncache;
910 bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, pfMissingInputs, nAcceptTime, plTxnReplaced, bypass_limits, nAbsurdFee, coins_to_uncache);
911 if (!res) {
912 for (const COutPoint& hashTx : coins_to_uncache)
913 pcoinsTip->Uncache(hashTx);
915 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
916 CValidationState stateDummy;
917 FlushStateToDisk(chainparams, stateDummy, FLUSH_STATE_PERIODIC);
918 return res;
921 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
922 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
923 bool bypass_limits, const CAmount nAbsurdFee)
925 const CChainParams& chainparams = Params();
926 return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, pfMissingInputs, GetTime(), plTxnReplaced, bypass_limits, nAbsurdFee);
929 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
930 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
932 CBlockIndex *pindexSlow = nullptr;
934 LOCK(cs_main);
936 CTransactionRef ptx = mempool.get(hash);
937 if (ptx)
939 txOut = ptx;
940 return true;
943 if (fTxIndex) {
944 CDiskTxPos postx;
945 if (pblocktree->ReadTxIndex(hash, postx)) {
946 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
947 if (file.IsNull())
948 return error("%s: OpenBlockFile failed", __func__);
949 CBlockHeader header;
950 try {
951 file >> header;
952 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
953 file >> txOut;
954 } catch (const std::exception& e) {
955 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
957 hashBlock = header.GetHash();
958 if (txOut->GetHash() != hash)
959 return error("%s: txid mismatch", __func__);
960 return true;
963 // transaction not found in index, nothing more can be done
964 return false;
967 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
968 const Coin& coin = AccessByTxid(*pcoinsTip, hash);
969 if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
972 if (pindexSlow) {
973 CBlock block;
974 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
975 for (const auto& tx : block.vtx) {
976 if (tx->GetHash() == hash) {
977 txOut = tx;
978 hashBlock = pindexSlow->GetBlockHash();
979 return true;
985 return false;
993 //////////////////////////////////////////////////////////////////////////////
995 // CBlock and CBlockIndex
998 static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1000 // Open history file to append
1001 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1002 if (fileout.IsNull())
1003 return error("WriteBlockToDisk: OpenBlockFile failed");
1005 // Write index header
1006 unsigned int nSize = GetSerializeSize(fileout, block);
1007 fileout << FLATDATA(messageStart) << nSize;
1009 // Write block
1010 long fileOutPos = ftell(fileout.Get());
1011 if (fileOutPos < 0)
1012 return error("WriteBlockToDisk: ftell failed");
1013 pos.nPos = (unsigned int)fileOutPos;
1014 fileout << block;
1016 return true;
1019 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
1021 block.SetNull();
1023 // Open history file to read
1024 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1025 if (filein.IsNull())
1026 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1028 // Read block
1029 try {
1030 filein >> block;
1032 catch (const std::exception& e) {
1033 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1036 // Check the header
1037 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1038 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1040 return true;
1043 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1045 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1046 return false;
1047 if (block.GetHash() != pindex->GetBlockHash())
1048 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1049 pindex->ToString(), pindex->GetBlockPos().ToString());
1050 return true;
1053 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1055 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1056 // Force block reward to zero when right shift is undefined.
1057 if (halvings >= 64)
1058 return 0;
1060 CAmount nSubsidy = 50 * COIN;
1061 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1062 nSubsidy >>= halvings;
1063 return nSubsidy;
1066 bool IsInitialBlockDownload()
1068 // Once this function has returned false, it must remain false.
1069 static std::atomic<bool> latchToFalse{false};
1070 // Optimization: pre-test latch before taking the lock.
1071 if (latchToFalse.load(std::memory_order_relaxed))
1072 return false;
1074 LOCK(cs_main);
1075 if (latchToFalse.load(std::memory_order_relaxed))
1076 return false;
1077 if (fImporting || fReindex)
1078 return true;
1079 if (chainActive.Tip() == nullptr)
1080 return true;
1081 if (chainActive.Tip()->nChainWork < nMinimumChainWork)
1082 return true;
1083 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1084 return true;
1085 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1086 latchToFalse.store(true, std::memory_order_relaxed);
1087 return false;
1090 CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
1092 static void AlertNotify(const std::string& strMessage)
1094 uiInterface.NotifyAlertChanged();
1095 std::string strCmd = gArgs.GetArg("-alertnotify", "");
1096 if (strCmd.empty()) return;
1098 // Alert text should be plain ascii coming from a trusted source, but to
1099 // be safe we first strip anything not in safeChars, then add single quotes around
1100 // the whole string before passing it to the shell:
1101 std::string singleQuote("'");
1102 std::string safeStatus = SanitizeString(strMessage);
1103 safeStatus = singleQuote+safeStatus+singleQuote;
1104 boost::replace_all(strCmd, "%s", safeStatus);
1106 boost::thread t(runCommand, strCmd); // thread runs free
1109 static void CheckForkWarningConditions()
1111 AssertLockHeld(cs_main);
1112 // Before we get past initial download, we cannot reliably alert about forks
1113 // (we assume we don't get stuck on a fork before finishing our initial sync)
1114 if (IsInitialBlockDownload())
1115 return;
1117 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1118 // of our head, drop it
1119 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1120 pindexBestForkTip = nullptr;
1122 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1124 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
1126 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1127 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1128 AlertNotify(warning);
1130 if (pindexBestForkTip && pindexBestForkBase)
1132 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__,
1133 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1134 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1135 SetfLargeWorkForkFound(true);
1137 else
1139 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1140 SetfLargeWorkInvalidChainFound(true);
1143 else
1145 SetfLargeWorkForkFound(false);
1146 SetfLargeWorkInvalidChainFound(false);
1150 static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1152 AssertLockHeld(cs_main);
1153 // If we are on a fork that is sufficiently large, set a warning flag
1154 CBlockIndex* pfork = pindexNewForkTip;
1155 CBlockIndex* plonger = chainActive.Tip();
1156 while (pfork && pfork != plonger)
1158 while (plonger && plonger->nHeight > pfork->nHeight)
1159 plonger = plonger->pprev;
1160 if (pfork == plonger)
1161 break;
1162 pfork = pfork->pprev;
1165 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1166 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1167 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1168 // hash rate operating on the fork.
1169 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1170 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1171 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1172 if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
1173 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1174 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1176 pindexBestForkTip = pindexNewForkTip;
1177 pindexBestForkBase = pfork;
1180 CheckForkWarningConditions();
1183 void static InvalidChainFound(CBlockIndex* pindexNew)
1185 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1186 pindexBestInvalid = pindexNew;
1188 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1189 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1190 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1191 pindexNew->GetBlockTime()));
1192 CBlockIndex *tip = chainActive.Tip();
1193 assert (tip);
1194 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1195 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1196 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1197 CheckForkWarningConditions();
1200 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1201 if (!state.CorruptionPossible()) {
1202 pindex->nStatus |= BLOCK_FAILED_VALID;
1203 g_failed_blocks.insert(pindex);
1204 setDirtyBlockIndex.insert(pindex);
1205 setBlockIndexCandidates.erase(pindex);
1206 InvalidChainFound(pindex);
1210 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1212 // mark inputs spent
1213 if (!tx.IsCoinBase()) {
1214 txundo.vprevout.reserve(tx.vin.size());
1215 for (const CTxIn &txin : tx.vin) {
1216 txundo.vprevout.emplace_back();
1217 bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1218 assert(is_spent);
1221 // add outputs
1222 AddCoins(inputs, tx, nHeight);
1225 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1227 CTxUndo txundo;
1228 UpdateCoins(tx, inputs, txundo, nHeight);
1231 bool CScriptCheck::operator()() {
1232 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1233 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1234 return VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *txdata), &error);
1237 int GetSpendHeight(const CCoinsViewCache& inputs)
1239 LOCK(cs_main);
1240 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1241 return pindexPrev->nHeight + 1;
1245 static CuckooCache::cache<uint256, SignatureCacheHasher> scriptExecutionCache;
1246 static uint256 scriptExecutionCacheNonce(GetRandHash());
1248 void InitScriptExecutionCache() {
1249 // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1250 // setup_bytes creates the minimum possible cache (2 elements).
1251 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);
1252 size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
1253 LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1254 (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1258 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
1259 * This does not modify the UTXO set.
1261 * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
1262 * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
1263 * not pushed onto pvChecks/run.
1265 * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
1266 * which are matched. This is useful for checking blocks where we will likely never need the cache
1267 * entry again.
1269 * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
1271 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)
1273 if (!tx.IsCoinBase())
1275 if (pvChecks)
1276 pvChecks->reserve(tx.vin.size());
1278 // The first loop above does all the inexpensive checks.
1279 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1280 // Helps prevent CPU exhaustion attacks.
1282 // Skip script verification when connecting blocks under the
1283 // assumevalid block. Assuming the assumevalid block is valid this
1284 // is safe because block merkle hashes are still computed and checked,
1285 // Of course, if an assumed valid block is invalid due to false scriptSigs
1286 // this optimization would allow an invalid chain to be accepted.
1287 if (fScriptChecks) {
1288 // First check if script executions have been cached with the same
1289 // flags. Note that this assumes that the inputs provided are
1290 // correct (ie that the transaction hash which is in tx's prevouts
1291 // properly commits to the scriptPubKey in the inputs view of that
1292 // transaction).
1293 uint256 hashCacheEntry;
1294 // We only use the first 19 bytes of nonce to avoid a second SHA
1295 // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
1296 static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
1297 CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1298 AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1299 if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1300 return true;
1303 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1304 const COutPoint &prevout = tx.vin[i].prevout;
1305 const Coin& coin = inputs.AccessCoin(prevout);
1306 assert(!coin.IsSpent());
1308 // We very carefully only pass in things to CScriptCheck which
1309 // are clearly committed to by tx' witness hash. This provides
1310 // a sanity check that our caching is not introducing consensus
1311 // failures through additional data in, eg, the coins being
1312 // spent being checked as a part of CScriptCheck.
1314 // Verify signature
1315 CScriptCheck check(coin.out, tx, i, flags, cacheSigStore, &txdata);
1316 if (pvChecks) {
1317 pvChecks->push_back(CScriptCheck());
1318 check.swap(pvChecks->back());
1319 } else if (!check()) {
1320 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1321 // Check whether the failure was caused by a
1322 // non-mandatory script verification check, such as
1323 // non-standard DER encodings or non-null dummy
1324 // arguments; if so, don't trigger DoS protection to
1325 // avoid splitting the network between upgraded and
1326 // non-upgraded nodes.
1327 CScriptCheck check2(coin.out, tx, i,
1328 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1329 if (check2())
1330 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1332 // Failures of other flags indicate a transaction that is
1333 // invalid in new blocks, e.g. an invalid P2SH. We DoS ban
1334 // such nodes as they are not following the protocol. That
1335 // said during an upgrade careful thought should be taken
1336 // as to the correct behavior - we may want to continue
1337 // peering with non-upgraded nodes even after soft-fork
1338 // super-majority signaling has occurred.
1339 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1343 if (cacheFullScriptStore && !pvChecks) {
1344 // We executed all of the provided scripts, and were told to
1345 // cache the result. Do so now.
1346 scriptExecutionCache.insert(hashCacheEntry);
1351 return true;
1354 namespace {
1356 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1358 // Open history file to append
1359 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1360 if (fileout.IsNull())
1361 return error("%s: OpenUndoFile failed", __func__);
1363 // Write index header
1364 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1365 fileout << FLATDATA(messageStart) << nSize;
1367 // Write undo data
1368 long fileOutPos = ftell(fileout.Get());
1369 if (fileOutPos < 0)
1370 return error("%s: ftell failed", __func__);
1371 pos.nPos = (unsigned int)fileOutPos;
1372 fileout << blockundo;
1374 // calculate & write checksum
1375 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1376 hasher << hashBlock;
1377 hasher << blockundo;
1378 fileout << hasher.GetHash();
1380 return true;
1383 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1385 // Open history file to read
1386 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1387 if (filein.IsNull())
1388 return error("%s: OpenUndoFile failed", __func__);
1390 // Read block
1391 uint256 hashChecksum;
1392 CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1393 try {
1394 verifier << hashBlock;
1395 verifier >> blockundo;
1396 filein >> hashChecksum;
1398 catch (const std::exception& e) {
1399 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1402 // Verify checksum
1403 if (hashChecksum != verifier.GetHash())
1404 return error("%s: Checksum mismatch", __func__);
1406 return true;
1409 /** Abort with a message */
1410 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1412 SetMiscWarning(strMessage);
1413 LogPrintf("*** %s\n", strMessage);
1414 uiInterface.ThreadSafeMessageBox(
1415 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1416 "", CClientUIInterface::MSG_ERROR);
1417 StartShutdown();
1418 return false;
1421 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1423 AbortNode(strMessage, userMessage);
1424 return state.Error(strMessage);
1427 } // namespace
1429 enum DisconnectResult
1431 DISCONNECT_OK, // All good.
1432 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
1433 DISCONNECT_FAILED // Something else went wrong.
1437 * Restore the UTXO in a Coin at a given COutPoint
1438 * @param undo The Coin to be restored.
1439 * @param view The coins view to which to apply the changes.
1440 * @param out The out point that corresponds to the tx input.
1441 * @return A DisconnectResult as an int
1443 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1445 bool fClean = true;
1447 if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1449 if (undo.nHeight == 0) {
1450 // Missing undo metadata (height and coinbase). Older versions included this
1451 // information only in undo records for the last spend of a transactions'
1452 // outputs. This implies that it must be present for some other output of the same tx.
1453 const Coin& alternate = AccessByTxid(view, out.hash);
1454 if (!alternate.IsSpent()) {
1455 undo.nHeight = alternate.nHeight;
1456 undo.fCoinBase = alternate.fCoinBase;
1457 } else {
1458 return DISCONNECT_FAILED; // adding output for transaction without known metadata
1461 // The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
1462 // sure that the coin did not already exist in the cache. As we have queried for that above
1463 // using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
1464 // it is an overwrite.
1465 view.AddCoin(out, std::move(undo), !fClean);
1467 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1470 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1471 * When FAILED is returned, view is left in an indeterminate state. */
1472 static DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1474 bool fClean = true;
1476 CBlockUndo blockUndo;
1477 CDiskBlockPos pos = pindex->GetUndoPos();
1478 if (pos.IsNull()) {
1479 error("DisconnectBlock(): no undo data available");
1480 return DISCONNECT_FAILED;
1482 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) {
1483 error("DisconnectBlock(): failure reading undo data");
1484 return DISCONNECT_FAILED;
1487 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1488 error("DisconnectBlock(): block and undo data inconsistent");
1489 return DISCONNECT_FAILED;
1492 // undo transactions in reverse order
1493 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1494 const CTransaction &tx = *(block.vtx[i]);
1495 uint256 hash = tx.GetHash();
1496 bool is_coinbase = tx.IsCoinBase();
1498 // Check that all outputs are available and match the outputs in the block itself
1499 // exactly.
1500 for (size_t o = 0; o < tx.vout.size(); o++) {
1501 if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1502 COutPoint out(hash, o);
1503 Coin coin;
1504 bool is_spent = view.SpendCoin(out, &coin);
1505 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1506 fClean = false; // transaction output mismatch
1511 // restore inputs
1512 if (i > 0) { // not coinbases
1513 CTxUndo &txundo = blockUndo.vtxundo[i-1];
1514 if (txundo.vprevout.size() != tx.vin.size()) {
1515 error("DisconnectBlock(): transaction and undo data inconsistent");
1516 return DISCONNECT_FAILED;
1518 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1519 const COutPoint &out = tx.vin[j].prevout;
1520 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1521 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1522 fClean = fClean && res != DISCONNECT_UNCLEAN;
1524 // At this point, all of txundo.vprevout should have been moved out.
1528 // move best block pointer to prevout block
1529 view.SetBestBlock(pindex->pprev->GetBlockHash());
1531 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1534 void static FlushBlockFile(bool fFinalize = false)
1536 LOCK(cs_LastBlockFile);
1538 CDiskBlockPos posOld(nLastBlockFile, 0);
1540 FILE *fileOld = OpenBlockFile(posOld);
1541 if (fileOld) {
1542 if (fFinalize)
1543 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1544 FileCommit(fileOld);
1545 fclose(fileOld);
1548 fileOld = OpenUndoFile(posOld);
1549 if (fileOld) {
1550 if (fFinalize)
1551 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1552 FileCommit(fileOld);
1553 fclose(fileOld);
1557 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1559 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1561 void ThreadScriptCheck() {
1562 RenameThread("bitcoin-scriptch");
1563 scriptcheckqueue.Thread();
1566 // Protected by cs_main
1567 VersionBitsCache versionbitscache;
1569 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1571 LOCK(cs_main);
1572 int32_t nVersion = VERSIONBITS_TOP_BITS;
1574 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1575 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1576 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1577 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1581 return nVersion;
1585 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1587 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1589 private:
1590 int bit;
1592 public:
1593 explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1595 int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1596 int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1597 int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1598 int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1600 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1602 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1603 ((pindex->nVersion >> bit) & 1) != 0 &&
1604 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1608 // Protected by cs_main
1609 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1611 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) {
1612 AssertLockHeld(cs_main);
1614 unsigned int flags = SCRIPT_VERIFY_NONE;
1616 // Start enforcing P2SH (BIP16)
1617 if (pindex->nHeight >= consensusparams.BIP16Height) {
1618 flags |= SCRIPT_VERIFY_P2SH;
1621 // Start enforcing the DERSIG (BIP66) rule
1622 if (pindex->nHeight >= consensusparams.BIP66Height) {
1623 flags |= SCRIPT_VERIFY_DERSIG;
1626 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1627 if (pindex->nHeight >= consensusparams.BIP65Height) {
1628 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1631 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1632 if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1633 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1636 // Start enforcing WITNESS rules using versionbits logic.
1637 if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
1638 flags |= SCRIPT_VERIFY_WITNESS;
1639 flags |= SCRIPT_VERIFY_NULLDUMMY;
1642 return flags;
1647 static int64_t nTimeCheck = 0;
1648 static int64_t nTimeForks = 0;
1649 static int64_t nTimeVerify = 0;
1650 static int64_t nTimeConnect = 0;
1651 static int64_t nTimeIndex = 0;
1652 static int64_t nTimeCallbacks = 0;
1653 static int64_t nTimeTotal = 0;
1654 static int64_t nBlocksTotal = 0;
1656 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1657 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1658 * can fail if those validity checks fail (among other reasons). */
1659 static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1660 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false)
1662 AssertLockHeld(cs_main);
1663 assert(pindex);
1664 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1665 assert((pindex->phashBlock == nullptr) ||
1666 (*pindex->phashBlock == block.GetHash()));
1667 int64_t nTimeStart = GetTimeMicros();
1669 // Check it again in case a previous version let a bad block in
1670 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1671 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1673 // verify that the view's current state corresponds to the previous block
1674 uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
1675 assert(hashPrevBlock == view.GetBestBlock());
1677 // Special case for the genesis block, skipping connection of its transactions
1678 // (its coinbase is unspendable)
1679 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1680 if (!fJustCheck)
1681 view.SetBestBlock(pindex->GetBlockHash());
1682 return true;
1685 nBlocksTotal++;
1687 bool fScriptChecks = true;
1688 if (!hashAssumeValid.IsNull()) {
1689 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1690 // A suitable default value is included with the software and updated from time to time. Because validity
1691 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1692 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1693 // effectively caching the result of part of the verification.
1694 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1695 if (it != mapBlockIndex.end()) {
1696 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1697 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1698 pindexBestHeader->nChainWork >= nMinimumChainWork) {
1699 // This block is a member of the assumed verified chain and an ancestor of the best header.
1700 // The equivalent time check discourages hash power from extorting the network via DOS attack
1701 // into accepting an invalid block through telling users they must manually set assumevalid.
1702 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1703 // it hard to hide the implication of the demand. This also avoids having release candidates
1704 // that are hardly doing any signature verification at all in testing without having to
1705 // artificially set the default assumed verified block further back.
1706 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1707 // least as good as the expected chain.
1708 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1713 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1714 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
1716 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1717 // unless those are already completely spent.
1718 // If such overwrites are allowed, coinbases and transactions depending upon those
1719 // can be duplicated to remove the ability to spend the first instance -- even after
1720 // being sent to another address.
1721 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1722 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1723 // already refuses previously-known transaction ids entirely.
1724 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1725 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1726 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1727 // initial block download.
1728 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1729 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1730 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1732 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1733 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1734 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1735 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1736 // duplicate transactions descending from the known pairs either.
1737 // 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.
1738 assert(pindex->pprev);
1739 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1740 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1741 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1743 if (fEnforceBIP30) {
1744 for (const auto& tx : block.vtx) {
1745 for (size_t o = 0; o < tx->vout.size(); o++) {
1746 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
1747 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1748 REJECT_INVALID, "bad-txns-BIP30");
1754 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1755 int nLockTimeFlags = 0;
1756 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1757 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1760 // Get the script flags for this block
1761 unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
1763 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1764 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
1766 CBlockUndo blockundo;
1768 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
1770 std::vector<int> prevheights;
1771 CAmount nFees = 0;
1772 int nInputs = 0;
1773 int64_t nSigOpsCost = 0;
1774 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1775 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1776 vPos.reserve(block.vtx.size());
1777 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1778 std::vector<PrecomputedTransactionData> txdata;
1779 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1780 for (unsigned int i = 0; i < block.vtx.size(); i++)
1782 const CTransaction &tx = *(block.vtx[i]);
1784 nInputs += tx.vin.size();
1786 if (!tx.IsCoinBase())
1788 CAmount txfee = 0;
1789 if (!Consensus::CheckTxInputs(tx, state, view, pindex->nHeight, txfee)) {
1790 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
1792 nFees += txfee;
1793 if (!MoneyRange(nFees)) {
1794 return state.DoS(100, error("%s: accumulated fee in the block out of range.", __func__),
1795 REJECT_INVALID, "bad-txns-accumulated-fee-outofrange");
1798 // Check that transaction is BIP68 final
1799 // BIP68 lock checks (as opposed to nLockTime checks) must
1800 // be in ConnectBlock because they require the UTXO set
1801 prevheights.resize(tx.vin.size());
1802 for (size_t j = 0; j < tx.vin.size(); j++) {
1803 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
1806 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1807 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1808 REJECT_INVALID, "bad-txns-nonfinal");
1812 // GetTransactionSigOpCost counts 3 types of sigops:
1813 // * legacy (always)
1814 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1815 // * witness (when witness enabled in flags and excludes coinbase)
1816 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1817 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1818 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1819 REJECT_INVALID, "bad-blk-sigops");
1821 txdata.emplace_back(tx);
1822 if (!tx.IsCoinBase())
1824 std::vector<CScriptCheck> vChecks;
1825 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1826 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr))
1827 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1828 tx.GetHash().ToString(), FormatStateMessage(state));
1829 control.Add(vChecks);
1832 CTxUndo undoDummy;
1833 if (i > 0) {
1834 blockundo.vtxundo.push_back(CTxUndo());
1836 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1838 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1839 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1841 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1842 LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(), MILLI * (nTime3 - nTime2), MILLI * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : MILLI * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * MICRO, nTimeConnect * MILLI / nBlocksTotal);
1844 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1845 if (block.vtx[0]->GetValueOut() > blockReward)
1846 return state.DoS(100,
1847 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1848 block.vtx[0]->GetValueOut(), blockReward),
1849 REJECT_INVALID, "bad-cb-amount");
1851 if (!control.Wait())
1852 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1853 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1854 LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1, MILLI * (nTime4 - nTime2), nInputs <= 1 ? 0 : MILLI * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * MICRO, nTimeVerify * MILLI / nBlocksTotal);
1856 if (fJustCheck)
1857 return true;
1859 // Write undo information to disk
1860 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1862 if (pindex->GetUndoPos().IsNull()) {
1863 CDiskBlockPos _pos;
1864 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1865 return error("ConnectBlock(): FindUndoPos failed");
1866 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1867 return AbortNode(state, "Failed to write undo data");
1869 // update nUndoPos in block index
1870 pindex->nUndoPos = _pos.nPos;
1871 pindex->nStatus |= BLOCK_HAVE_UNDO;
1874 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1875 setDirtyBlockIndex.insert(pindex);
1878 if (fTxIndex)
1879 if (!pblocktree->WriteTxIndex(vPos))
1880 return AbortNode(state, "Failed to write transaction index");
1882 assert(pindex->phashBlock);
1883 // add this block to the view's block chain
1884 view.SetBestBlock(pindex->GetBlockHash());
1886 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1887 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
1889 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1890 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
1892 return true;
1896 * Update the on-disk chain state.
1897 * The caches and indexes are flushed depending on the mode we're called with
1898 * if they're too large, if it's been a while since the last write,
1899 * or always and in all cases if we're in prune mode and are deleting files.
1901 bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
1902 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
1903 LOCK(cs_main);
1904 static int64_t nLastWrite = 0;
1905 static int64_t nLastFlush = 0;
1906 static int64_t nLastSetChain = 0;
1907 std::set<int> setFilesToPrune;
1908 bool fFlushForPrune = false;
1909 bool fDoFullFlush = false;
1910 int64_t nNow = 0;
1911 try {
1913 LOCK(cs_LastBlockFile);
1914 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1915 if (nManualPruneHeight > 0) {
1916 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
1917 } else {
1918 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1919 fCheckForPruning = false;
1921 if (!setFilesToPrune.empty()) {
1922 fFlushForPrune = true;
1923 if (!fHavePruned) {
1924 pblocktree->WriteFlag("prunedblockfiles", true);
1925 fHavePruned = true;
1929 nNow = GetTimeMicros();
1930 // Avoid writing/flushing immediately after startup.
1931 if (nLastWrite == 0) {
1932 nLastWrite = nNow;
1934 if (nLastFlush == 0) {
1935 nLastFlush = nNow;
1937 if (nLastSetChain == 0) {
1938 nLastSetChain = nNow;
1940 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1941 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1942 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
1943 // 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).
1944 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
1945 // The cache is over the limit, we have to write now.
1946 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
1947 // 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.
1948 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1949 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1950 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1951 // Combine all conditions that result in a full cache flush.
1952 fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1953 // Write blocks and block index to disk.
1954 if (fDoFullFlush || fPeriodicWrite) {
1955 // Depend on nMinDiskSpace to ensure we can write block index
1956 if (!CheckDiskSpace(0))
1957 return state.Error("out of disk space");
1958 // First make sure all block and undo data is flushed to disk.
1959 FlushBlockFile();
1960 // Then update all block file information (which may refer to block and undo files).
1962 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1963 vFiles.reserve(setDirtyFileInfo.size());
1964 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1965 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
1966 setDirtyFileInfo.erase(it++);
1968 std::vector<const CBlockIndex*> vBlocks;
1969 vBlocks.reserve(setDirtyBlockIndex.size());
1970 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1971 vBlocks.push_back(*it);
1972 setDirtyBlockIndex.erase(it++);
1974 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1975 return AbortNode(state, "Failed to write to block index database");
1978 // Finally remove any pruned files
1979 if (fFlushForPrune)
1980 UnlinkPrunedFiles(setFilesToPrune);
1981 nLastWrite = nNow;
1983 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1984 if (fDoFullFlush) {
1985 // Typical Coin structures on disk are around 48 bytes in size.
1986 // Pushing a new one to the database can cause it to be written
1987 // twice (once in the log, and once in the tables). This is already
1988 // an overestimation, as most will delete an existing entry or
1989 // overwrite one. Still, use a conservative safety factor of 2.
1990 if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
1991 return state.Error("out of disk space");
1992 // Flush the chainstate (which may refer to block index entries).
1993 if (!pcoinsTip->Flush())
1994 return AbortNode(state, "Failed to write to coin database");
1995 nLastFlush = nNow;
1998 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
1999 // Update best block in wallet (so we can detect restored wallets).
2000 GetMainSignals().SetBestChain(chainActive.GetLocator());
2001 nLastSetChain = nNow;
2003 } catch (const std::runtime_error& e) {
2004 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2006 return true;
2009 void FlushStateToDisk() {
2010 CValidationState state;
2011 const CChainParams& chainparams = Params();
2012 FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
2015 void PruneAndFlush() {
2016 CValidationState state;
2017 fCheckForPruning = true;
2018 const CChainParams& chainparams = Params();
2019 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
2022 static void DoWarning(const std::string& strWarning)
2024 static bool fWarned = false;
2025 SetMiscWarning(strWarning);
2026 if (!fWarned) {
2027 AlertNotify(strWarning);
2028 fWarned = true;
2032 /** Update chainActive and related internal data structures. */
2033 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
2034 chainActive.SetTip(pindexNew);
2036 // New best block
2037 mempool.AddTransactionsUpdated(1);
2039 cvBlockChange.notify_all();
2041 std::vector<std::string> warningMessages;
2042 if (!IsInitialBlockDownload())
2044 int nUpgraded = 0;
2045 const CBlockIndex* pindex = chainActive.Tip();
2046 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2047 WarningBitsConditionChecker checker(bit);
2048 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2049 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2050 const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2051 if (state == THRESHOLD_ACTIVE) {
2052 DoWarning(strWarning);
2053 } else {
2054 warningMessages.push_back(strWarning);
2058 // Check the version of the last 100 blocks to see if we need to upgrade:
2059 for (int i = 0; i < 100 && pindex != nullptr; i++)
2061 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2062 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2063 ++nUpgraded;
2064 pindex = pindex->pprev;
2066 if (nUpgraded > 0)
2067 warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
2068 if (nUpgraded > 100/2)
2070 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2071 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2072 DoWarning(strWarning);
2075 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
2076 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
2077 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2078 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2079 GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2080 if (!warningMessages.empty())
2081 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2082 LogPrintf("\n");
2086 /** Disconnect chainActive's tip.
2087 * After calling, the mempool will be in an inconsistent state, with
2088 * transactions from disconnected blocks being added to disconnectpool. You
2089 * should make the mempool consistent again by calling UpdateMempoolForReorg.
2090 * with cs_main held.
2092 * If disconnectpool is nullptr, then no disconnected transactions are added to
2093 * disconnectpool (note that the caller is responsible for mempool consistency
2094 * in any case).
2096 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
2098 CBlockIndex *pindexDelete = chainActive.Tip();
2099 assert(pindexDelete);
2100 // Read block from disk.
2101 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2102 CBlock& block = *pblock;
2103 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2104 return AbortNode(state, "Failed to read block");
2105 // Apply the block atomically to the chain state.
2106 int64_t nStart = GetTimeMicros();
2108 CCoinsViewCache view(pcoinsTip.get());
2109 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2110 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2111 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2112 bool flushed = view.Flush();
2113 assert(flushed);
2115 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
2116 // Write the chain state to disk, if necessary.
2117 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2118 return false;
2120 if (disconnectpool) {
2121 // Save transactions to re-add to mempool at end of reorg
2122 for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2123 disconnectpool->addTransaction(*it);
2125 while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2126 // Drop the earliest entry, and remove its children from the mempool.
2127 auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2128 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
2129 disconnectpool->removeEntry(it);
2133 // Update chainActive and related variables.
2134 UpdateTip(pindexDelete->pprev, chainparams);
2135 // Let wallets know transactions went from 1-confirmed to
2136 // 0-confirmed or conflicted:
2137 GetMainSignals().BlockDisconnected(pblock);
2138 return true;
2141 static int64_t nTimeReadFromDisk = 0;
2142 static int64_t nTimeConnectTotal = 0;
2143 static int64_t nTimeFlush = 0;
2144 static int64_t nTimeChainState = 0;
2145 static int64_t nTimePostConnect = 0;
2147 struct PerBlockConnectTrace {
2148 CBlockIndex* pindex = nullptr;
2149 std::shared_ptr<const CBlock> pblock;
2150 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
2151 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
2154 * Used to track blocks whose transactions were applied to the UTXO state as a
2155 * part of a single ActivateBestChainStep call.
2157 * This class also tracks transactions that are removed from the mempool as
2158 * conflicts (per block) and can be used to pass all those transactions
2159 * through SyncTransaction.
2161 * This class assumes (and asserts) that the conflicted transactions for a given
2162 * block are added via mempool callbacks prior to the BlockConnected() associated
2163 * with those transactions. If any transactions are marked conflicted, it is
2164 * assumed that an associated block will always be added.
2166 * This class is single-use, once you call GetBlocksConnected() you have to throw
2167 * it away and make a new one.
2169 class ConnectTrace {
2170 private:
2171 std::vector<PerBlockConnectTrace> blocksConnected;
2172 CTxMemPool &pool;
2174 public:
2175 explicit ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
2176 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2179 ~ConnectTrace() {
2180 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2183 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2184 assert(!blocksConnected.back().pindex);
2185 assert(pindex);
2186 assert(pblock);
2187 blocksConnected.back().pindex = pindex;
2188 blocksConnected.back().pblock = std::move(pblock);
2189 blocksConnected.emplace_back();
2192 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2193 // We always keep one extra block at the end of our list because
2194 // blocks are added after all the conflicted transactions have
2195 // been filled in. Thus, the last entry should always be an empty
2196 // one waiting for the transactions from the next block. We pop
2197 // the last entry here to make sure the list we return is sane.
2198 assert(!blocksConnected.back().pindex);
2199 assert(blocksConnected.back().conflictedTxs->empty());
2200 blocksConnected.pop_back();
2201 return blocksConnected;
2204 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
2205 assert(!blocksConnected.back().pindex);
2206 if (reason == MemPoolRemovalReason::CONFLICT) {
2207 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2213 * Connect a new block to chainActive. pblock is either nullptr or a pointer to a CBlock
2214 * corresponding to pindexNew, to bypass loading it again from disk.
2216 * The block is added to connectTrace if connection succeeds.
2218 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
2220 assert(pindexNew->pprev == chainActive.Tip());
2221 // Read block from disk.
2222 int64_t nTime1 = GetTimeMicros();
2223 std::shared_ptr<const CBlock> pthisBlock;
2224 if (!pblock) {
2225 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2226 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2227 return AbortNode(state, "Failed to read block");
2228 pthisBlock = pblockNew;
2229 } else {
2230 pthisBlock = pblock;
2232 const CBlock& blockConnecting = *pthisBlock;
2233 // Apply the block atomically to the chain state.
2234 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2235 int64_t nTime3;
2236 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
2238 CCoinsViewCache view(pcoinsTip.get());
2239 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2240 GetMainSignals().BlockChecked(blockConnecting, state);
2241 if (!rv) {
2242 if (state.IsInvalid())
2243 InvalidBlockFound(pindexNew, state);
2244 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2246 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2247 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
2248 bool flushed = view.Flush();
2249 assert(flushed);
2251 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2252 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
2253 // Write the chain state to disk, if necessary.
2254 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2255 return false;
2256 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2257 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
2258 // Remove conflicting transactions from the mempool.;
2259 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2260 disconnectpool.removeForBlock(blockConnecting.vtx);
2261 // Update chainActive & related variables.
2262 UpdateTip(pindexNew, chainparams);
2264 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2265 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
2266 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
2268 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2269 return true;
2273 * Return the tip of the chain with the most work in it, that isn't
2274 * known to be invalid (it's however far from certain to be valid).
2276 static CBlockIndex* FindMostWorkChain() {
2277 do {
2278 CBlockIndex *pindexNew = nullptr;
2280 // Find the best candidate header.
2282 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2283 if (it == setBlockIndexCandidates.rend())
2284 return nullptr;
2285 pindexNew = *it;
2288 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2289 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2290 CBlockIndex *pindexTest = pindexNew;
2291 bool fInvalidAncestor = false;
2292 while (pindexTest && !chainActive.Contains(pindexTest)) {
2293 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2295 // Pruned nodes may have entries in setBlockIndexCandidates for
2296 // which block files have been deleted. Remove those as candidates
2297 // for the most work chain if we come across them; we can't switch
2298 // to a chain unless we have all the non-active-chain parent blocks.
2299 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2300 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2301 if (fFailedChain || fMissingData) {
2302 // Candidate chain is not usable (either invalid or missing data)
2303 if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2304 pindexBestInvalid = pindexNew;
2305 CBlockIndex *pindexFailed = pindexNew;
2306 // Remove the entire chain from the set.
2307 while (pindexTest != pindexFailed) {
2308 if (fFailedChain) {
2309 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2310 } else if (fMissingData) {
2311 // If we're missing data, then add back to mapBlocksUnlinked,
2312 // so that if the block arrives in the future we can try adding
2313 // to setBlockIndexCandidates again.
2314 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2316 setBlockIndexCandidates.erase(pindexFailed);
2317 pindexFailed = pindexFailed->pprev;
2319 setBlockIndexCandidates.erase(pindexTest);
2320 fInvalidAncestor = true;
2321 break;
2323 pindexTest = pindexTest->pprev;
2325 if (!fInvalidAncestor)
2326 return pindexNew;
2327 } while(true);
2330 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2331 static void PruneBlockIndexCandidates() {
2332 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2333 // reorganization to a better block fails.
2334 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2335 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2336 setBlockIndexCandidates.erase(it++);
2338 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2339 assert(!setBlockIndexCandidates.empty());
2343 * Try to make some progress towards making pindexMostWork the active block.
2344 * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
2346 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2348 AssertLockHeld(cs_main);
2349 const CBlockIndex *pindexOldTip = chainActive.Tip();
2350 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2352 // Disconnect active blocks which are no longer in the best chain.
2353 bool fBlocksDisconnected = false;
2354 DisconnectedBlockTransactions disconnectpool;
2355 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2356 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2357 // This is likely a fatal error, but keep the mempool consistent,
2358 // just in case. Only remove from the mempool in this case.
2359 UpdateMempoolForReorg(disconnectpool, false);
2360 return false;
2362 fBlocksDisconnected = true;
2365 // Build list of new blocks to connect.
2366 std::vector<CBlockIndex*> vpindexToConnect;
2367 bool fContinue = true;
2368 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2369 while (fContinue && nHeight != pindexMostWork->nHeight) {
2370 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2371 // a few blocks along the way.
2372 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2373 vpindexToConnect.clear();
2374 vpindexToConnect.reserve(nTargetHeight - nHeight);
2375 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2376 while (pindexIter && pindexIter->nHeight != nHeight) {
2377 vpindexToConnect.push_back(pindexIter);
2378 pindexIter = pindexIter->pprev;
2380 nHeight = nTargetHeight;
2382 // Connect new blocks.
2383 for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
2384 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2385 if (state.IsInvalid()) {
2386 // The block violates a consensus rule.
2387 if (!state.CorruptionPossible())
2388 InvalidChainFound(vpindexToConnect.back());
2389 state = CValidationState();
2390 fInvalidFound = true;
2391 fContinue = false;
2392 break;
2393 } else {
2394 // A system error occurred (disk space, database error, ...).
2395 // Make the mempool consistent with the current tip, just in case
2396 // any observers try to use it before shutdown.
2397 UpdateMempoolForReorg(disconnectpool, false);
2398 return false;
2400 } else {
2401 PruneBlockIndexCandidates();
2402 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2403 // We're in a better position than we were. Return temporarily to release the lock.
2404 fContinue = false;
2405 break;
2411 if (fBlocksDisconnected) {
2412 // If any blocks were disconnected, disconnectpool may be non empty. Add
2413 // any disconnected transactions back to the mempool.
2414 UpdateMempoolForReorg(disconnectpool, true);
2416 mempool.check(pcoinsTip.get());
2418 // Callbacks/notifications for a new best chain.
2419 if (fInvalidFound)
2420 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2421 else
2422 CheckForkWarningConditions();
2424 return true;
2427 static void NotifyHeaderTip() {
2428 bool fNotify = false;
2429 bool fInitialBlockDownload = false;
2430 static CBlockIndex* pindexHeaderOld = nullptr;
2431 CBlockIndex* pindexHeader = nullptr;
2433 LOCK(cs_main);
2434 pindexHeader = pindexBestHeader;
2436 if (pindexHeader != pindexHeaderOld) {
2437 fNotify = true;
2438 fInitialBlockDownload = IsInitialBlockDownload();
2439 pindexHeaderOld = pindexHeader;
2442 // Send block tip changed notifications without cs_main
2443 if (fNotify) {
2444 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2449 * Make the best chain active, in multiple steps. The result is either failure
2450 * or an activated best chain. pblock is either nullptr or a pointer to a block
2451 * that is already loaded (to avoid loading it again from disk).
2453 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2454 // Note that while we're often called here from ProcessNewBlock, this is
2455 // far from a guarantee. Things in the P2P/RPC will often end up calling
2456 // us in the middle of ProcessNewBlock - do not assume pblock is set
2457 // sanely for performance or correctness!
2459 CBlockIndex *pindexMostWork = nullptr;
2460 CBlockIndex *pindexNewTip = nullptr;
2461 int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2462 do {
2463 boost::this_thread::interruption_point();
2464 if (ShutdownRequested())
2465 break;
2467 const CBlockIndex *pindexFork;
2468 bool fInitialDownload;
2470 LOCK(cs_main);
2471 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2473 CBlockIndex *pindexOldTip = chainActive.Tip();
2474 if (pindexMostWork == nullptr) {
2475 pindexMostWork = FindMostWorkChain();
2478 // Whether we have anything to do at all.
2479 if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip())
2480 return true;
2482 bool fInvalidFound = false;
2483 std::shared_ptr<const CBlock> nullBlockPtr;
2484 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2485 return false;
2487 if (fInvalidFound) {
2488 // Wipe cache, we may need another branch now.
2489 pindexMostWork = nullptr;
2491 pindexNewTip = chainActive.Tip();
2492 pindexFork = chainActive.FindFork(pindexOldTip);
2493 fInitialDownload = IsInitialBlockDownload();
2495 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2496 assert(trace.pblock && trace.pindex);
2497 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, trace.conflictedTxs);
2500 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2502 // Notifications/callbacks that can run without cs_main
2504 // Notify external listeners about the new tip.
2505 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2507 // Always notify the UI if a new block tip was connected
2508 if (pindexFork != pindexNewTip) {
2509 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2512 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2513 } while (pindexNewTip != pindexMostWork);
2514 CheckBlockIndex(chainparams.GetConsensus());
2516 // Write changes periodically to disk, after relay.
2517 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
2518 return false;
2521 return true;
2525 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2528 LOCK(cs_main);
2529 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2530 // Nothing to do, this block is not at the tip.
2531 return true;
2533 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2534 // The chain has been extended since the last call, reset the counter.
2535 nBlockReverseSequenceId = -1;
2537 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2538 setBlockIndexCandidates.erase(pindex);
2539 pindex->nSequenceId = nBlockReverseSequenceId;
2540 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2541 // We can't keep reducing the counter if somebody really wants to
2542 // call preciousblock 2**31-1 times on the same set of tips...
2543 nBlockReverseSequenceId--;
2545 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2546 setBlockIndexCandidates.insert(pindex);
2547 PruneBlockIndexCandidates();
2551 return ActivateBestChain(state, params);
2554 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2556 AssertLockHeld(cs_main);
2558 // We first disconnect backwards and then mark the blocks as invalid.
2559 // This prevents a case where pruned nodes may fail to invalidateblock
2560 // and be left unable to start as they have no tip candidates (as there
2561 // are no blocks that meet the "have data and are not invalid per
2562 // nStatus" criteria for inclusion in setBlockIndexCandidates).
2564 bool pindex_was_in_chain = false;
2565 CBlockIndex *invalid_walk_tip = chainActive.Tip();
2567 DisconnectedBlockTransactions disconnectpool;
2568 while (chainActive.Contains(pindex)) {
2569 pindex_was_in_chain = true;
2570 // ActivateBestChain considers blocks already in chainActive
2571 // unconditionally valid already, so force disconnect away from it.
2572 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2573 // It's probably hopeless to try to make the mempool consistent
2574 // here if DisconnectTip failed, but we can try.
2575 UpdateMempoolForReorg(disconnectpool, false);
2576 return false;
2580 // Now mark the blocks we just disconnected as descendants invalid
2581 // (note this may not be all descendants).
2582 while (pindex_was_in_chain && invalid_walk_tip != pindex) {
2583 invalid_walk_tip->nStatus |= BLOCK_FAILED_CHILD;
2584 setDirtyBlockIndex.insert(invalid_walk_tip);
2585 setBlockIndexCandidates.erase(invalid_walk_tip);
2586 invalid_walk_tip = invalid_walk_tip->pprev;
2589 // Mark the block itself as invalid.
2590 pindex->nStatus |= BLOCK_FAILED_VALID;
2591 setDirtyBlockIndex.insert(pindex);
2592 setBlockIndexCandidates.erase(pindex);
2593 g_failed_blocks.insert(pindex);
2595 // DisconnectTip will add transactions to disconnectpool; try to add these
2596 // back to the mempool.
2597 UpdateMempoolForReorg(disconnectpool, true);
2599 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2600 // add it again.
2601 BlockMap::iterator it = mapBlockIndex.begin();
2602 while (it != mapBlockIndex.end()) {
2603 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2604 setBlockIndexCandidates.insert(it->second);
2606 it++;
2609 InvalidChainFound(pindex);
2610 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2611 return true;
2614 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2615 AssertLockHeld(cs_main);
2617 int nHeight = pindex->nHeight;
2619 // Remove the invalidity flag from this block and all its descendants.
2620 BlockMap::iterator it = mapBlockIndex.begin();
2621 while (it != mapBlockIndex.end()) {
2622 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2623 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2624 setDirtyBlockIndex.insert(it->second);
2625 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2626 setBlockIndexCandidates.insert(it->second);
2628 if (it->second == pindexBestInvalid) {
2629 // Reset invalid block marker if it was pointing to one of those.
2630 pindexBestInvalid = nullptr;
2632 g_failed_blocks.erase(it->second);
2634 it++;
2637 // Remove the invalidity flag from all ancestors too.
2638 while (pindex != nullptr) {
2639 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2640 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2641 setDirtyBlockIndex.insert(pindex);
2643 pindex = pindex->pprev;
2645 return true;
2648 static CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2650 // Check for duplicate
2651 uint256 hash = block.GetHash();
2652 BlockMap::iterator it = mapBlockIndex.find(hash);
2653 if (it != mapBlockIndex.end())
2654 return it->second;
2656 // Construct new block index object
2657 CBlockIndex* pindexNew = new CBlockIndex(block);
2658 // We assign the sequence id to blocks only when the full data is available,
2659 // to avoid miners withholding blocks but broadcasting headers, to get a
2660 // competitive advantage.
2661 pindexNew->nSequenceId = 0;
2662 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2663 pindexNew->phashBlock = &((*mi).first);
2664 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2665 if (miPrev != mapBlockIndex.end())
2667 pindexNew->pprev = (*miPrev).second;
2668 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2669 pindexNew->BuildSkip();
2671 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2672 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2673 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2674 if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2675 pindexBestHeader = pindexNew;
2677 setDirtyBlockIndex.insert(pindexNew);
2679 return pindexNew;
2682 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2683 static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2685 pindexNew->nTx = block.vtx.size();
2686 pindexNew->nChainTx = 0;
2687 pindexNew->nFile = pos.nFile;
2688 pindexNew->nDataPos = pos.nPos;
2689 pindexNew->nUndoPos = 0;
2690 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2691 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2692 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2694 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2695 setDirtyBlockIndex.insert(pindexNew);
2697 if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
2698 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2699 std::deque<CBlockIndex*> queue;
2700 queue.push_back(pindexNew);
2702 // Recursively process any descendant blocks that now may be eligible to be connected.
2703 while (!queue.empty()) {
2704 CBlockIndex *pindex = queue.front();
2705 queue.pop_front();
2706 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2708 LOCK(cs_nBlockSequenceId);
2709 pindex->nSequenceId = nBlockSequenceId++;
2711 if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2712 setBlockIndexCandidates.insert(pindex);
2714 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2715 while (range.first != range.second) {
2716 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2717 queue.push_back(it->second);
2718 range.first++;
2719 mapBlocksUnlinked.erase(it);
2722 } else {
2723 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2724 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2728 return true;
2731 static bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2733 LOCK(cs_LastBlockFile);
2735 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2736 if (vinfoBlockFile.size() <= nFile) {
2737 vinfoBlockFile.resize(nFile + 1);
2740 if (!fKnown) {
2741 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2742 nFile++;
2743 if (vinfoBlockFile.size() <= nFile) {
2744 vinfoBlockFile.resize(nFile + 1);
2747 pos.nFile = nFile;
2748 pos.nPos = vinfoBlockFile[nFile].nSize;
2751 if ((int)nFile != nLastBlockFile) {
2752 if (!fKnown) {
2753 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2755 FlushBlockFile(!fKnown);
2756 nLastBlockFile = nFile;
2759 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2760 if (fKnown)
2761 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2762 else
2763 vinfoBlockFile[nFile].nSize += nAddSize;
2765 if (!fKnown) {
2766 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2767 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2768 if (nNewChunks > nOldChunks) {
2769 if (fPruneMode)
2770 fCheckForPruning = true;
2771 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2772 FILE *file = OpenBlockFile(pos);
2773 if (file) {
2774 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2775 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2776 fclose(file);
2779 else
2780 return state.Error("out of disk space");
2784 setDirtyFileInfo.insert(nFile);
2785 return true;
2788 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2790 pos.nFile = nFile;
2792 LOCK(cs_LastBlockFile);
2794 unsigned int nNewSize;
2795 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2796 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2797 setDirtyFileInfo.insert(nFile);
2799 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2800 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2801 if (nNewChunks > nOldChunks) {
2802 if (fPruneMode)
2803 fCheckForPruning = true;
2804 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2805 FILE *file = OpenUndoFile(pos);
2806 if (file) {
2807 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2808 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2809 fclose(file);
2812 else
2813 return state.Error("out of disk space");
2816 return true;
2819 static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
2821 // Check proof of work matches claimed amount
2822 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2823 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2825 return true;
2828 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2830 // These are checks that are independent of context.
2832 if (block.fChecked)
2833 return true;
2835 // Check that the header is valid (particularly PoW). This is mostly
2836 // redundant with the call in AcceptBlockHeader.
2837 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2838 return false;
2840 // Check the merkle root.
2841 if (fCheckMerkleRoot) {
2842 bool mutated;
2843 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2844 if (block.hashMerkleRoot != hashMerkleRoot2)
2845 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2847 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2848 // of transactions in a block without affecting the merkle root of a block,
2849 // while still invalidating it.
2850 if (mutated)
2851 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2854 // All potential-corruption validation must be done before we do any
2855 // transaction validation, as otherwise we may mark the header as invalid
2856 // because we receive the wrong transactions for it.
2857 // Note that witness malleability is checked in ContextualCheckBlock, so no
2858 // checks that use witness data may be performed here.
2860 // Size limits
2861 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)
2862 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2864 // First transaction must be coinbase, the rest must not be
2865 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2866 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2867 for (unsigned int i = 1; i < block.vtx.size(); i++)
2868 if (block.vtx[i]->IsCoinBase())
2869 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2871 // Check transactions
2872 for (const auto& tx : block.vtx)
2873 if (!CheckTransaction(*tx, state, false))
2874 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2875 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2877 unsigned int nSigOps = 0;
2878 for (const auto& tx : block.vtx)
2880 nSigOps += GetLegacySigOpCount(*tx);
2882 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2883 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2885 if (fCheckPOW && fCheckMerkleRoot)
2886 block.fChecked = true;
2888 return true;
2891 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2893 LOCK(cs_main);
2894 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2897 // Compute at which vout of the block's coinbase transaction the witness
2898 // commitment occurs, or -1 if not found.
2899 static int GetWitnessCommitmentIndex(const CBlock& block)
2901 int commitpos = -1;
2902 if (!block.vtx.empty()) {
2903 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2904 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) {
2905 commitpos = o;
2909 return commitpos;
2912 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2914 int commitpos = GetWitnessCommitmentIndex(block);
2915 static const std::vector<unsigned char> nonce(32, 0x00);
2916 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2917 CMutableTransaction tx(*block.vtx[0]);
2918 tx.vin[0].scriptWitness.stack.resize(1);
2919 tx.vin[0].scriptWitness.stack[0] = nonce;
2920 block.vtx[0] = MakeTransactionRef(std::move(tx));
2924 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2926 std::vector<unsigned char> commitment;
2927 int commitpos = GetWitnessCommitmentIndex(block);
2928 std::vector<unsigned char> ret(32, 0x00);
2929 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2930 if (commitpos == -1) {
2931 uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
2932 CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
2933 CTxOut out;
2934 out.nValue = 0;
2935 out.scriptPubKey.resize(38);
2936 out.scriptPubKey[0] = OP_RETURN;
2937 out.scriptPubKey[1] = 0x24;
2938 out.scriptPubKey[2] = 0xaa;
2939 out.scriptPubKey[3] = 0x21;
2940 out.scriptPubKey[4] = 0xa9;
2941 out.scriptPubKey[5] = 0xed;
2942 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2943 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2944 CMutableTransaction tx(*block.vtx[0]);
2945 tx.vout.push_back(out);
2946 block.vtx[0] = MakeTransactionRef(std::move(tx));
2949 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2950 return commitment;
2953 /** Context-dependent validity checks.
2954 * By "context", we mean only the previous block headers, but not the UTXO
2955 * set; UTXO-related validity checks are done in ConnectBlock(). */
2956 static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2958 assert(pindexPrev != nullptr);
2959 const int nHeight = pindexPrev->nHeight + 1;
2961 // Check proof of work
2962 const Consensus::Params& consensusParams = params.GetConsensus();
2963 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2964 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2966 // Check against checkpoints
2967 if (fCheckpointsEnabled) {
2968 // Don't accept any forks from the main chain prior to last checkpoint.
2969 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
2970 // MapBlockIndex.
2971 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(params.Checkpoints());
2972 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2973 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
2976 // Check timestamp against prev
2977 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2978 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2980 // Check timestamp
2981 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
2982 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
2984 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2985 // check for version 2, 3 and 4 upgrades
2986 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
2987 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
2988 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
2989 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
2990 strprintf("rejected nVersion=0x%08x block", block.nVersion));
2992 return true;
2995 static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
2997 const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
2999 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
3000 int nLockTimeFlags = 0;
3001 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
3002 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
3005 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3006 ? pindexPrev->GetMedianTimePast()
3007 : block.GetBlockTime();
3009 // Check that all transactions are finalized
3010 for (const auto& tx : block.vtx) {
3011 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
3012 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
3016 // Enforce rule that the coinbase starts with serialized block height
3017 if (nHeight >= consensusParams.BIP34Height)
3019 CScript expect = CScript() << nHeight;
3020 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
3021 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
3022 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
3026 // Validation for witness commitments.
3027 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
3028 // coinbase (where 0x0000....0000 is used instead).
3029 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
3030 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
3031 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
3032 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
3033 // multiple, the last one is used.
3034 bool fHaveWitness = false;
3035 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
3036 int commitpos = GetWitnessCommitmentIndex(block);
3037 if (commitpos != -1) {
3038 bool malleated = false;
3039 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
3040 // The malleation check is ignored; as the transaction tree itself
3041 // already does not permit it, it is impossible to trigger in the
3042 // witness tree.
3043 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3044 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
3046 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
3047 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3048 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
3050 fHaveWitness = true;
3054 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3055 if (!fHaveWitness) {
3056 for (const auto& tx : block.vtx) {
3057 if (tx->HasWitness()) {
3058 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
3063 // After the coinbase witness nonce and commitment are verified,
3064 // we can check if the block weight passes (before we've checked the
3065 // coinbase witness, it would be possible for the weight to be too
3066 // large by filling up the coinbase witness, which doesn't change
3067 // the block hash, so we couldn't mark the block as permanently
3068 // failed).
3069 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3070 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
3073 return true;
3076 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3078 AssertLockHeld(cs_main);
3079 // Check for duplicate
3080 uint256 hash = block.GetHash();
3081 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3082 CBlockIndex *pindex = nullptr;
3083 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3085 if (miSelf != mapBlockIndex.end()) {
3086 // Block header is already known.
3087 pindex = miSelf->second;
3088 if (ppindex)
3089 *ppindex = pindex;
3090 if (pindex->nStatus & BLOCK_FAILED_MASK)
3091 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3092 return true;
3095 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3096 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3098 // Get prev block index
3099 CBlockIndex* pindexPrev = nullptr;
3100 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3101 if (mi == mapBlockIndex.end())
3102 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
3103 pindexPrev = (*mi).second;
3104 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3105 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3106 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3107 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3109 if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
3110 for (const CBlockIndex* failedit : g_failed_blocks) {
3111 if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
3112 assert(failedit->nStatus & BLOCK_FAILED_VALID);
3113 CBlockIndex* invalid_walk = pindexPrev;
3114 while (invalid_walk != failedit) {
3115 invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
3116 setDirtyBlockIndex.insert(invalid_walk);
3117 invalid_walk = invalid_walk->pprev;
3119 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3124 if (pindex == nullptr)
3125 pindex = AddToBlockIndex(block);
3127 if (ppindex)
3128 *ppindex = pindex;
3130 CheckBlockIndex(chainparams.GetConsensus());
3132 return true;
3135 // Exposed wrapper for AcceptBlockHeader
3136 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex, CBlockHeader *first_invalid)
3138 if (first_invalid != nullptr) first_invalid->SetNull();
3140 LOCK(cs_main);
3141 for (const CBlockHeader& header : headers) {
3142 CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3143 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
3144 if (first_invalid) *first_invalid = header;
3145 return false;
3147 if (ppindex) {
3148 *ppindex = pindex;
3152 NotifyHeaderTip();
3153 return true;
3156 /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
3157 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3159 const CBlock& block = *pblock;
3161 if (fNewBlock) *fNewBlock = false;
3162 AssertLockHeld(cs_main);
3164 CBlockIndex *pindexDummy = nullptr;
3165 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3167 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3168 return false;
3170 // Try to process all requested blocks that we don't have, but only
3171 // process an unrequested block if it's new and has enough work to
3172 // advance our tip, and isn't too many blocks ahead.
3173 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3174 bool fHasMoreOrSameWork = (chainActive.Tip() ? pindex->nChainWork >= chainActive.Tip()->nChainWork : true);
3175 // Blocks that are too out-of-order needlessly limit the effectiveness of
3176 // pruning, because pruning will not delete block files that contain any
3177 // blocks which are too close in height to the tip. Apply this test
3178 // regardless of whether pruning is enabled; it should generally be safe to
3179 // not process unrequested blocks.
3180 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3182 // TODO: Decouple this function from the block download logic by removing fRequested
3183 // This requires some new chain data structure to efficiently look up if a
3184 // block is in a chain leading to a candidate for best tip, despite not
3185 // being such a candidate itself.
3187 // TODO: deal better with return value and error conditions for duplicate
3188 // and unrequested blocks.
3189 if (fAlreadyHave) return true;
3190 if (!fRequested) { // If we didn't ask for it:
3191 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3192 if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
3193 if (fTooFarAhead) return true; // Block height is too high
3195 // Protect against DoS attacks from low-work chains.
3196 // If our tip is behind, a peer could try to send us
3197 // low-work blocks on a fake chain that we would never
3198 // request; don't process these.
3199 if (pindex->nChainWork < nMinimumChainWork) return true;
3201 if (fNewBlock) *fNewBlock = true;
3203 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3204 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3205 if (state.IsInvalid() && !state.CorruptionPossible()) {
3206 pindex->nStatus |= BLOCK_FAILED_VALID;
3207 setDirtyBlockIndex.insert(pindex);
3209 return error("%s: %s", __func__, FormatStateMessage(state));
3212 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3213 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3214 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3215 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3217 int nHeight = pindex->nHeight;
3219 // Write block to history file
3220 try {
3221 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3222 CDiskBlockPos blockPos;
3223 if (dbp != nullptr)
3224 blockPos = *dbp;
3225 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr))
3226 return error("AcceptBlock(): FindBlockPos failed");
3227 if (dbp == nullptr)
3228 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3229 AbortNode(state, "Failed to write block");
3230 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3231 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3232 } catch (const std::runtime_error& e) {
3233 return AbortNode(state, std::string("System error: ") + e.what());
3236 if (fCheckForPruning)
3237 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3239 return true;
3242 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3245 CBlockIndex *pindex = nullptr;
3246 if (fNewBlock) *fNewBlock = false;
3247 CValidationState state;
3248 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3249 // belt-and-suspenders.
3250 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3252 LOCK(cs_main);
3254 if (ret) {
3255 // Store to disk
3256 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
3258 CheckBlockIndex(chainparams.GetConsensus());
3259 if (!ret) {
3260 GetMainSignals().BlockChecked(*pblock, state);
3261 return error("%s: AcceptBlock FAILED (%s)", __func__, state.GetDebugMessage());
3265 NotifyHeaderTip();
3267 CValidationState state; // Only used to report errors, not invalidity - ignore it
3268 if (!ActivateBestChain(state, chainparams, pblock))
3269 return error("%s: ActivateBestChain failed", __func__);
3271 return true;
3274 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3276 AssertLockHeld(cs_main);
3277 assert(pindexPrev && pindexPrev == chainActive.Tip());
3278 CCoinsViewCache viewNew(pcoinsTip.get());
3279 CBlockIndex indexDummy(block);
3280 indexDummy.pprev = pindexPrev;
3281 indexDummy.nHeight = pindexPrev->nHeight + 1;
3283 // NOTE: CheckBlockHeader is called by CheckBlock
3284 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3285 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3286 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3287 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3288 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3289 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3290 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3291 return false;
3292 assert(state.IsValid());
3294 return true;
3298 * BLOCK PRUNING CODE
3301 /* Calculate the amount of disk space the block & undo files currently use */
3302 uint64_t CalculateCurrentUsage()
3304 LOCK(cs_LastBlockFile);
3306 uint64_t retval = 0;
3307 for (const CBlockFileInfo &file : vinfoBlockFile) {
3308 retval += file.nSize + file.nUndoSize;
3310 return retval;
3313 /* Prune a block file (modify associated database entries)*/
3314 void PruneOneBlockFile(const int fileNumber)
3316 LOCK(cs_LastBlockFile);
3318 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3319 CBlockIndex* pindex = it->second;
3320 if (pindex->nFile == fileNumber) {
3321 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3322 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3323 pindex->nFile = 0;
3324 pindex->nDataPos = 0;
3325 pindex->nUndoPos = 0;
3326 setDirtyBlockIndex.insert(pindex);
3328 // Prune from mapBlocksUnlinked -- any block we prune would have
3329 // to be downloaded again in order to consider its chain, at which
3330 // point it would be considered as a candidate for
3331 // mapBlocksUnlinked or setBlockIndexCandidates.
3332 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3333 while (range.first != range.second) {
3334 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3335 range.first++;
3336 if (_it->second == pindex) {
3337 mapBlocksUnlinked.erase(_it);
3343 vinfoBlockFile[fileNumber].SetNull();
3344 setDirtyFileInfo.insert(fileNumber);
3348 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3350 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3351 CDiskBlockPos pos(*it, 0);
3352 fs::remove(GetBlockPosFilename(pos, "blk"));
3353 fs::remove(GetBlockPosFilename(pos, "rev"));
3354 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3358 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3359 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3361 assert(fPruneMode && nManualPruneHeight > 0);
3363 LOCK2(cs_main, cs_LastBlockFile);
3364 if (chainActive.Tip() == nullptr)
3365 return;
3367 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3368 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3369 int count=0;
3370 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3371 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3372 continue;
3373 PruneOneBlockFile(fileNumber);
3374 setFilesToPrune.insert(fileNumber);
3375 count++;
3377 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3380 /* This function is called from the RPC code for pruneblockchain */
3381 void PruneBlockFilesManual(int nManualPruneHeight)
3383 CValidationState state;
3384 const CChainParams& chainparams = Params();
3385 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
3389 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
3390 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
3391 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
3392 * (which in this case means the blockchain must be re-downloaded.)
3394 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
3395 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
3396 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
3397 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
3398 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
3399 * A db flag records the fact that at least some block files have been pruned.
3401 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
3403 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3405 LOCK2(cs_main, cs_LastBlockFile);
3406 if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
3407 return;
3409 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3410 return;
3413 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3414 uint64_t nCurrentUsage = CalculateCurrentUsage();
3415 // We don't check to prune until after we've allocated new space for files
3416 // So we should leave a buffer under our target to account for another allocation
3417 // before the next pruning.
3418 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3419 uint64_t nBytesToPrune;
3420 int count=0;
3422 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3423 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3424 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3426 if (vinfoBlockFile[fileNumber].nSize == 0)
3427 continue;
3429 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3430 break;
3432 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3433 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3434 continue;
3436 PruneOneBlockFile(fileNumber);
3437 // Queue up the files for removal
3438 setFilesToPrune.insert(fileNumber);
3439 nCurrentUsage -= nBytesToPrune;
3440 count++;
3444 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3445 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3446 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3447 nLastBlockWeCanPrune, count);
3450 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3452 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3454 // Check for nMinDiskSpace bytes (currently 50MB)
3455 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3456 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3458 return true;
3461 static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3463 if (pos.IsNull())
3464 return nullptr;
3465 fs::path path = GetBlockPosFilename(pos, prefix);
3466 fs::create_directories(path.parent_path());
3467 FILE* file = fsbridge::fopen(path, "rb+");
3468 if (!file && !fReadOnly)
3469 file = fsbridge::fopen(path, "wb+");
3470 if (!file) {
3471 LogPrintf("Unable to open file %s\n", path.string());
3472 return nullptr;
3474 if (pos.nPos) {
3475 if (fseek(file, pos.nPos, SEEK_SET)) {
3476 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3477 fclose(file);
3478 return nullptr;
3481 return file;
3484 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3485 return OpenDiskFile(pos, "blk", fReadOnly);
3488 /** Open an undo file (rev?????.dat) */
3489 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3490 return OpenDiskFile(pos, "rev", fReadOnly);
3493 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3495 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3498 CBlockIndex * InsertBlockIndex(uint256 hash)
3500 if (hash.IsNull())
3501 return nullptr;
3503 // Return existing
3504 BlockMap::iterator mi = mapBlockIndex.find(hash);
3505 if (mi != mapBlockIndex.end())
3506 return (*mi).second;
3508 // Create new
3509 CBlockIndex* pindexNew = new CBlockIndex();
3510 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3511 pindexNew->phashBlock = &((*mi).first);
3513 return pindexNew;
3516 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3518 if (!pblocktree->LoadBlockIndexGuts(chainparams.GetConsensus(), InsertBlockIndex))
3519 return false;
3521 boost::this_thread::interruption_point();
3523 // Calculate nChainWork
3524 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3525 vSortedByHeight.reserve(mapBlockIndex.size());
3526 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3528 CBlockIndex* pindex = item.second;
3529 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3531 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3532 for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
3534 CBlockIndex* pindex = item.second;
3535 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3536 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3537 // We can link the chain of blocks for which we've received transactions at some point.
3538 // Pruned nodes may have deleted the block.
3539 if (pindex->nTx > 0) {
3540 if (pindex->pprev) {
3541 if (pindex->pprev->nChainTx) {
3542 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3543 } else {
3544 pindex->nChainTx = 0;
3545 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3547 } else {
3548 pindex->nChainTx = pindex->nTx;
3551 if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
3552 pindex->nStatus |= BLOCK_FAILED_CHILD;
3553 setDirtyBlockIndex.insert(pindex);
3555 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
3556 setBlockIndexCandidates.insert(pindex);
3557 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3558 pindexBestInvalid = pindex;
3559 if (pindex->pprev)
3560 pindex->BuildSkip();
3561 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3562 pindexBestHeader = pindex;
3565 // Load block file info
3566 pblocktree->ReadLastBlockFile(nLastBlockFile);
3567 vinfoBlockFile.resize(nLastBlockFile + 1);
3568 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3569 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3570 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3572 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3573 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3574 CBlockFileInfo info;
3575 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3576 vinfoBlockFile.push_back(info);
3577 } else {
3578 break;
3582 // Check presence of blk files
3583 LogPrintf("Checking all blk files are present...\n");
3584 std::set<int> setBlkDataFiles;
3585 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3587 CBlockIndex* pindex = item.second;
3588 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3589 setBlkDataFiles.insert(pindex->nFile);
3592 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3594 CDiskBlockPos pos(*it, 0);
3595 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3596 return false;
3600 // Check whether we have ever pruned block & undo files
3601 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3602 if (fHavePruned)
3603 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3605 // Check whether we need to continue reindexing
3606 bool fReindexing = false;
3607 pblocktree->ReadReindexing(fReindexing);
3608 if(fReindexing) fReindex = true;
3610 // Check whether we have a transaction index
3611 pblocktree->ReadFlag("txindex", fTxIndex);
3612 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3614 return true;
3617 bool LoadChainTip(const CChainParams& chainparams)
3619 if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
3621 if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
3622 // In case we just added the genesis block, connect it now, so
3623 // that we always have a chainActive.Tip() when we return.
3624 LogPrintf("%s: Connecting genesis block...\n", __func__);
3625 CValidationState state;
3626 if (!ActivateBestChain(state, chainparams)) {
3627 return false;
3631 // Load pointer to end of best chain
3632 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3633 if (it == mapBlockIndex.end())
3634 return false;
3635 chainActive.SetTip(it->second);
3637 PruneBlockIndexCandidates();
3639 LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
3640 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3641 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3642 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3643 return true;
3646 CVerifyDB::CVerifyDB()
3648 uiInterface.ShowProgress(_("Verifying blocks..."), 0, false);
3651 CVerifyDB::~CVerifyDB()
3653 uiInterface.ShowProgress("", 100, false);
3656 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3658 LOCK(cs_main);
3659 if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
3660 return true;
3662 // Verify blocks in the best chain
3663 if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height())
3664 nCheckDepth = chainActive.Height();
3665 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3666 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3667 CCoinsViewCache coins(coinsview);
3668 CBlockIndex* pindexState = chainActive.Tip();
3669 CBlockIndex* pindexFailure = nullptr;
3670 int nGoodTransactions = 0;
3671 CValidationState state;
3672 int reportDone = 0;
3673 LogPrintf("[0%%]...");
3674 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3676 boost::this_thread::interruption_point();
3677 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3678 if (reportDone < percentageDone/10) {
3679 // report every 10% step
3680 LogPrintf("[%d%%]...", percentageDone);
3681 reportDone = percentageDone/10;
3683 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false);
3684 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3685 break;
3686 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3687 // If pruning, only go back as far as we have data.
3688 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3689 break;
3691 CBlock block;
3692 // check level 0: read from disk
3693 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3694 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3695 // check level 1: verify block validity
3696 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3697 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3698 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3699 // check level 2: verify undo validity
3700 if (nCheckLevel >= 2 && pindex) {
3701 CBlockUndo undo;
3702 CDiskBlockPos pos = pindex->GetUndoPos();
3703 if (!pos.IsNull()) {
3704 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3705 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3708 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3709 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3710 assert(coins.GetBestBlock() == pindex->GetBlockHash());
3711 DisconnectResult res = DisconnectBlock(block, pindex, coins);
3712 if (res == DISCONNECT_FAILED) {
3713 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3715 pindexState = pindex->pprev;
3716 if (res == DISCONNECT_UNCLEAN) {
3717 nGoodTransactions = 0;
3718 pindexFailure = pindex;
3719 } else {
3720 nGoodTransactions += block.vtx.size();
3723 if (ShutdownRequested())
3724 return true;
3726 if (pindexFailure)
3727 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3729 // check level 4: try reconnecting blocks
3730 if (nCheckLevel >= 4) {
3731 CBlockIndex *pindex = pindexState;
3732 while (pindex != chainActive.Tip()) {
3733 boost::this_thread::interruption_point();
3734 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))), false);
3735 pindex = chainActive.Next(pindex);
3736 CBlock block;
3737 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3738 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3739 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3740 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3744 LogPrintf("[DONE].\n");
3745 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3747 return true;
3750 /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
3751 static bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
3753 // TODO: merge with ConnectBlock
3754 CBlock block;
3755 if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
3756 return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3759 for (const CTransactionRef& tx : block.vtx) {
3760 if (!tx->IsCoinBase()) {
3761 for (const CTxIn &txin : tx->vin) {
3762 inputs.SpendCoin(txin.prevout);
3765 // Pass check = true as every addition may be an overwrite.
3766 AddCoins(inputs, *tx, pindex->nHeight, true);
3768 return true;
3771 bool ReplayBlocks(const CChainParams& params, CCoinsView* view)
3773 LOCK(cs_main);
3775 CCoinsViewCache cache(view);
3777 std::vector<uint256> hashHeads = view->GetHeadBlocks();
3778 if (hashHeads.empty()) return true; // We're already in a consistent state.
3779 if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
3781 uiInterface.ShowProgress(_("Replaying blocks..."), 0, false);
3782 LogPrintf("Replaying blocks\n");
3784 const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
3785 const CBlockIndex* pindexNew; // New tip during the interrupted flush.
3786 const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
3788 if (mapBlockIndex.count(hashHeads[0]) == 0) {
3789 return error("ReplayBlocks(): reorganization to unknown block requested");
3791 pindexNew = mapBlockIndex[hashHeads[0]];
3793 if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
3794 if (mapBlockIndex.count(hashHeads[1]) == 0) {
3795 return error("ReplayBlocks(): reorganization from unknown block requested");
3797 pindexOld = mapBlockIndex[hashHeads[1]];
3798 pindexFork = LastCommonAncestor(pindexOld, pindexNew);
3799 assert(pindexFork != nullptr);
3802 // Rollback along the old branch.
3803 while (pindexOld != pindexFork) {
3804 if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
3805 CBlock block;
3806 if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
3807 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3809 LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
3810 DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
3811 if (res == DISCONNECT_FAILED) {
3812 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3814 // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
3815 // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
3816 // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
3817 // the result is still a version of the UTXO set with the effects of that block undone.
3819 pindexOld = pindexOld->pprev;
3822 // Roll forward from the forking point to the new tip.
3823 int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
3824 for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
3825 const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
3826 LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
3827 if (!RollforwardBlock(pindex, cache, params)) return false;
3830 cache.SetBestBlock(pindexNew->GetBlockHash());
3831 cache.Flush();
3832 uiInterface.ShowProgress("", 100, false);
3833 return true;
3836 bool RewindBlockIndex(const CChainParams& params)
3838 LOCK(cs_main);
3840 // Note that during -reindex-chainstate we are called with an empty chainActive!
3842 int nHeight = 1;
3843 while (nHeight <= chainActive.Height()) {
3844 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3845 break;
3847 nHeight++;
3850 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3851 CValidationState state;
3852 CBlockIndex* pindex = chainActive.Tip();
3853 while (chainActive.Height() >= nHeight) {
3854 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3855 // If pruning, don't try rewinding past the HAVE_DATA point;
3856 // since older blocks can't be served anyway, there's
3857 // no need to walk further, and trying to DisconnectTip()
3858 // will fail (and require a needless reindex/redownload
3859 // of the blockchain).
3860 break;
3862 if (!DisconnectTip(state, params, nullptr)) {
3863 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3865 // Occasionally flush state to disk.
3866 if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
3867 return false;
3870 // Reduce validity flag and have-data flags.
3871 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3872 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3873 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3874 CBlockIndex* pindexIter = it->second;
3876 // Note: If we encounter an insufficiently validated block that
3877 // is on chainActive, it must be because we are a pruning node, and
3878 // this block or some successor doesn't HAVE_DATA, so we were unable to
3879 // rewind all the way. Blocks remaining on chainActive at this point
3880 // must not have their validity reduced.
3881 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3882 // Reduce validity
3883 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3884 // Remove have-data flags.
3885 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3886 // Remove storage location.
3887 pindexIter->nFile = 0;
3888 pindexIter->nDataPos = 0;
3889 pindexIter->nUndoPos = 0;
3890 // Remove various other things
3891 pindexIter->nTx = 0;
3892 pindexIter->nChainTx = 0;
3893 pindexIter->nSequenceId = 0;
3894 // Make sure it gets written.
3895 setDirtyBlockIndex.insert(pindexIter);
3896 // Update indexes
3897 setBlockIndexCandidates.erase(pindexIter);
3898 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3899 while (ret.first != ret.second) {
3900 if (ret.first->second == pindexIter) {
3901 mapBlocksUnlinked.erase(ret.first++);
3902 } else {
3903 ++ret.first;
3906 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3907 setBlockIndexCandidates.insert(pindexIter);
3911 if (chainActive.Tip() != nullptr) {
3912 // We can't prune block index candidates based on our tip if we have
3913 // no tip due to chainActive being empty!
3914 PruneBlockIndexCandidates();
3916 CheckBlockIndex(params.GetConsensus());
3918 // FlushStateToDisk can possibly read chainActive. Be conservative
3919 // and skip it here, we're about to -reindex-chainstate anyway, so
3920 // it'll get called a bunch real soon.
3921 if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
3922 return false;
3926 return true;
3929 // May NOT be used after any connections are up as much
3930 // of the peer-processing logic assumes a consistent
3931 // block index state
3932 void UnloadBlockIndex()
3934 LOCK(cs_main);
3935 setBlockIndexCandidates.clear();
3936 chainActive.SetTip(nullptr);
3937 pindexBestInvalid = nullptr;
3938 pindexBestHeader = nullptr;
3939 mempool.clear();
3940 mapBlocksUnlinked.clear();
3941 vinfoBlockFile.clear();
3942 nLastBlockFile = 0;
3943 nBlockSequenceId = 1;
3944 setDirtyBlockIndex.clear();
3945 g_failed_blocks.clear();
3946 setDirtyFileInfo.clear();
3947 versionbitscache.Clear();
3948 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3949 warningcache[b].clear();
3952 for (BlockMap::value_type& entry : mapBlockIndex) {
3953 delete entry.second;
3955 mapBlockIndex.clear();
3956 fHavePruned = false;
3959 bool LoadBlockIndex(const CChainParams& chainparams)
3961 // Load block index from databases
3962 bool needs_init = fReindex;
3963 if (!fReindex) {
3964 bool ret = LoadBlockIndexDB(chainparams);
3965 if (!ret) return false;
3966 needs_init = mapBlockIndex.empty();
3969 if (needs_init) {
3970 // Everything here is for *new* reindex/DBs. Thus, though
3971 // LoadBlockIndexDB may have set fReindex if we shut down
3972 // mid-reindex previously, we don't check fReindex and
3973 // instead only check it prior to LoadBlockIndexDB to set
3974 // needs_init.
3976 LogPrintf("Initializing databases...\n");
3977 // Use the provided setting for -txindex in the new database
3978 fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
3979 pblocktree->WriteFlag("txindex", fTxIndex);
3981 return true;
3984 bool LoadGenesisBlock(const CChainParams& chainparams)
3986 LOCK(cs_main);
3988 // Check whether we're already initialized by checking for genesis in
3989 // mapBlockIndex. Note that we can't use chainActive here, since it is
3990 // set based on the coins db, not the block index db, which is the only
3991 // thing loaded at this point.
3992 if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
3993 return true;
3995 try {
3996 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3997 // Start new block file
3998 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3999 CDiskBlockPos blockPos;
4000 CValidationState state;
4001 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
4002 return error("%s: FindBlockPos failed", __func__);
4003 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
4004 return error("%s: writing genesis block to disk failed", __func__);
4005 CBlockIndex *pindex = AddToBlockIndex(block);
4006 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
4007 return error("%s: genesis block not accepted", __func__);
4008 } catch (const std::runtime_error& e) {
4009 return error("%s: failed to write genesis block: %s", __func__, e.what());
4012 return true;
4015 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
4017 // Map of disk positions for blocks with unknown parent (only used for reindex)
4018 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4019 int64_t nStart = GetTimeMillis();
4021 int nLoaded = 0;
4022 try {
4023 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4024 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
4025 uint64_t nRewind = blkdat.GetPos();
4026 while (!blkdat.eof()) {
4027 boost::this_thread::interruption_point();
4029 blkdat.SetPos(nRewind);
4030 nRewind++; // start one byte further next time, in case of failure
4031 blkdat.SetLimit(); // remove former limit
4032 unsigned int nSize = 0;
4033 try {
4034 // locate a header
4035 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
4036 blkdat.FindByte(chainparams.MessageStart()[0]);
4037 nRewind = blkdat.GetPos()+1;
4038 blkdat >> FLATDATA(buf);
4039 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
4040 continue;
4041 // read size
4042 blkdat >> nSize;
4043 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
4044 continue;
4045 } catch (const std::exception&) {
4046 // no valid block header found; don't complain
4047 break;
4049 try {
4050 // read block
4051 uint64_t nBlockPos = blkdat.GetPos();
4052 if (dbp)
4053 dbp->nPos = nBlockPos;
4054 blkdat.SetLimit(nBlockPos + nSize);
4055 blkdat.SetPos(nBlockPos);
4056 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4057 CBlock& block = *pblock;
4058 blkdat >> block;
4059 nRewind = blkdat.GetPos();
4061 // detect out of order blocks, and store them for later
4062 uint256 hash = block.GetHash();
4063 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4064 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4065 block.hashPrevBlock.ToString());
4066 if (dbp)
4067 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4068 continue;
4071 // process in case the block isn't known yet
4072 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4073 LOCK(cs_main);
4074 CValidationState state;
4075 if (AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
4076 nLoaded++;
4077 if (state.IsError())
4078 break;
4079 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4080 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4083 // Activate the genesis block so normal node progress can continue
4084 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
4085 CValidationState state;
4086 if (!ActivateBestChain(state, chainparams)) {
4087 break;
4091 NotifyHeaderTip();
4093 // Recursively process earlier encountered successors of this block
4094 std::deque<uint256> queue;
4095 queue.push_back(hash);
4096 while (!queue.empty()) {
4097 uint256 head = queue.front();
4098 queue.pop_front();
4099 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4100 while (range.first != range.second) {
4101 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4102 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4103 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
4105 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4106 head.ToString());
4107 LOCK(cs_main);
4108 CValidationState dummy;
4109 if (AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
4111 nLoaded++;
4112 queue.push_back(pblockrecursive->GetHash());
4115 range.first++;
4116 mapBlocksUnknownParent.erase(it);
4117 NotifyHeaderTip();
4120 } catch (const std::exception& e) {
4121 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4124 } catch (const std::runtime_error& e) {
4125 AbortNode(std::string("System error: ") + e.what());
4127 if (nLoaded > 0)
4128 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4129 return nLoaded > 0;
4132 void static CheckBlockIndex(const Consensus::Params& consensusParams)
4134 if (!fCheckBlockIndex) {
4135 return;
4138 LOCK(cs_main);
4140 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4141 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4142 // iterating the block tree require that chainActive has been initialized.)
4143 if (chainActive.Height() < 0) {
4144 assert(mapBlockIndex.size() <= 1);
4145 return;
4148 // Build forward-pointing map of the entire block tree.
4149 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4150 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4151 forward.insert(std::make_pair(it->second->pprev, it->second));
4154 assert(forward.size() == mapBlockIndex.size());
4156 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4157 CBlockIndex *pindex = rangeGenesis.first->second;
4158 rangeGenesis.first++;
4159 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4161 // Iterate over the entire block tree, using depth-first search.
4162 // Along the way, remember whether there are blocks on the path from genesis
4163 // block being explored which are the first to have certain properties.
4164 size_t nNodes = 0;
4165 int nHeight = 0;
4166 CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4167 CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4168 CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4169 CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4170 CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4171 CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4172 CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4173 while (pindex != nullptr) {
4174 nNodes++;
4175 if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4176 if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4177 if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4178 if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4179 if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4180 if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4181 if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4183 // Begin: actual consistency checks.
4184 if (pindex->pprev == nullptr) {
4185 // Genesis block checks.
4186 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4187 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4189 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)
4190 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4191 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4192 if (!fHavePruned) {
4193 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4194 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4195 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4196 } else {
4197 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4198 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4200 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4201 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4202 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4203 assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4204 assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
4205 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4206 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.
4207 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4208 assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
4209 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4210 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4211 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4212 if (pindexFirstInvalid == nullptr) {
4213 // Checks for not-invalid blocks.
4214 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4216 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
4217 if (pindexFirstInvalid == nullptr) {
4218 // If this block sorts at least as good as the current tip and
4219 // is valid and we have all data for its parents, it must be in
4220 // setBlockIndexCandidates. chainActive.Tip() must also be there
4221 // even if some data has been pruned.
4222 if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
4223 assert(setBlockIndexCandidates.count(pindex));
4225 // If some parent is missing, then it could be that this block was in
4226 // setBlockIndexCandidates but had to be removed because of the missing data.
4227 // In this case it must be in mapBlocksUnlinked -- see test below.
4229 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4230 assert(setBlockIndexCandidates.count(pindex) == 0);
4232 // Check whether this block is in mapBlocksUnlinked.
4233 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4234 bool foundInUnlinked = false;
4235 while (rangeUnlinked.first != rangeUnlinked.second) {
4236 assert(rangeUnlinked.first->first == pindex->pprev);
4237 if (rangeUnlinked.first->second == pindex) {
4238 foundInUnlinked = true;
4239 break;
4241 rangeUnlinked.first++;
4243 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4244 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4245 assert(foundInUnlinked);
4247 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4248 if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4249 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4250 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4251 assert(fHavePruned); // We must have pruned.
4252 // This block may have entered mapBlocksUnlinked if:
4253 // - it has a descendant that at some point had more work than the
4254 // tip, and
4255 // - we tried switching to that descendant but were missing
4256 // data for some intermediate block between chainActive and the
4257 // tip.
4258 // So if this block is itself better than chainActive.Tip() and it wasn't in
4259 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4260 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4261 if (pindexFirstInvalid == nullptr) {
4262 assert(foundInUnlinked);
4266 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4267 // End: actual consistency checks.
4269 // Try descending into the first subnode.
4270 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4271 if (range.first != range.second) {
4272 // A subnode was found.
4273 pindex = range.first->second;
4274 nHeight++;
4275 continue;
4277 // This is a leaf node.
4278 // Move upwards until we reach a node of which we have not yet visited the last child.
4279 while (pindex) {
4280 // We are going to either move to a parent or a sibling of pindex.
4281 // If pindex was the first with a certain property, unset the corresponding variable.
4282 if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4283 if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4284 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4285 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4286 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4287 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4288 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4289 // Find our parent.
4290 CBlockIndex* pindexPar = pindex->pprev;
4291 // Find which child we just visited.
4292 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4293 while (rangePar.first->second != pindex) {
4294 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4295 rangePar.first++;
4297 // Proceed to the next one.
4298 rangePar.first++;
4299 if (rangePar.first != rangePar.second) {
4300 // Move to the sibling.
4301 pindex = rangePar.first->second;
4302 break;
4303 } else {
4304 // Move up further.
4305 pindex = pindexPar;
4306 nHeight--;
4307 continue;
4312 // Check that we actually traversed the entire map.
4313 assert(nNodes == forward.size());
4316 std::string CBlockFileInfo::ToString() const
4318 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));
4321 CBlockFileInfo* GetBlockFileInfo(size_t n)
4323 LOCK(cs_LastBlockFile);
4325 return &vinfoBlockFile.at(n);
4328 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
4330 LOCK(cs_main);
4331 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4334 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
4336 LOCK(cs_main);
4337 return VersionBitsStatistics(chainActive.Tip(), params, pos);
4340 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
4342 LOCK(cs_main);
4343 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
4346 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4348 bool LoadMempool(void)
4350 const CChainParams& chainparams = Params();
4351 int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4352 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4353 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4354 if (file.IsNull()) {
4355 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4356 return false;
4359 int64_t count = 0;
4360 int64_t expired = 0;
4361 int64_t failed = 0;
4362 int64_t already_there = 0;
4363 int64_t nNow = GetTime();
4365 try {
4366 uint64_t version;
4367 file >> version;
4368 if (version != MEMPOOL_DUMP_VERSION) {
4369 return false;
4371 uint64_t num;
4372 file >> num;
4373 while (num--) {
4374 CTransactionRef tx;
4375 int64_t nTime;
4376 int64_t nFeeDelta;
4377 file >> tx;
4378 file >> nTime;
4379 file >> nFeeDelta;
4381 CAmount amountdelta = nFeeDelta;
4382 if (amountdelta) {
4383 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4385 CValidationState state;
4386 if (nTime + nExpiryTimeout > nNow) {
4387 LOCK(cs_main);
4388 AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, nullptr /* pfMissingInputs */, nTime,
4389 nullptr /* plTxnReplaced */, false /* bypass_limits */, 0 /* nAbsurdFee */);
4390 if (state.IsValid()) {
4391 ++count;
4392 } else {
4393 // mempool may contain the transaction already, e.g. from
4394 // wallet(s) having loaded it while we were processing
4395 // mempool transactions; consider these as valid, instead of
4396 // failed, but mark them as 'already there'
4397 if (mempool.exists(tx->GetHash())) {
4398 ++already_there;
4399 } else {
4400 ++failed;
4403 } else {
4404 ++expired;
4406 if (ShutdownRequested())
4407 return false;
4409 std::map<uint256, CAmount> mapDeltas;
4410 file >> mapDeltas;
4412 for (const auto& i : mapDeltas) {
4413 mempool.PrioritiseTransaction(i.first, i.second);
4415 } catch (const std::exception& e) {
4416 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4417 return false;
4420 LogPrintf("Imported mempool transactions from disk: %i succeeded, %i failed, %i expired, %i already there\n", count, failed, expired, already_there);
4421 return true;
4424 bool DumpMempool(void)
4426 int64_t start = GetTimeMicros();
4428 std::map<uint256, CAmount> mapDeltas;
4429 std::vector<TxMempoolInfo> vinfo;
4432 LOCK(mempool.cs);
4433 for (const auto &i : mempool.mapDeltas) {
4434 mapDeltas[i.first] = i.second;
4436 vinfo = mempool.infoAll();
4439 int64_t mid = GetTimeMicros();
4441 try {
4442 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4443 if (!filestr) {
4444 return false;
4447 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4449 uint64_t version = MEMPOOL_DUMP_VERSION;
4450 file << version;
4452 file << (uint64_t)vinfo.size();
4453 for (const auto& i : vinfo) {
4454 file << *(i.tx);
4455 file << (int64_t)i.nTime;
4456 file << (int64_t)i.nFeeDelta;
4457 mapDeltas.erase(i.tx->GetHash());
4460 file << mapDeltas;
4461 FileCommit(file.Get());
4462 file.fclose();
4463 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4464 int64_t last = GetTimeMicros();
4465 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
4466 } catch (const std::exception& e) {
4467 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4468 return false;
4470 return true;
4473 //! Guess how far we are in the verification process at the given block index
4474 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4475 if (pindex == nullptr)
4476 return 0.0;
4478 int64_t nNow = time(nullptr);
4480 double fTxTotal;
4482 if (pindex->nChainTx <= data.nTxCount) {
4483 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4484 } else {
4485 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4488 return pindex->nChainTx / fTxTotal;
4491 class CMainCleanup
4493 public:
4494 CMainCleanup() {}
4495 ~CMainCleanup() {
4496 // block headers
4497 BlockMap::iterator it1 = mapBlockIndex.begin();
4498 for (; it1 != mapBlockIndex.end(); it1++)
4499 delete (*it1).second;
4500 mapBlockIndex.clear();
4502 } instance_of_cmaincleanup;