Merge #11737: Document partial validation in ConnectBlock()
[bitcoinplatinum.git] / src / validation.cpp
blobd598a6994c8d54f07b2c21b7cd5ae19725247b13
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 // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
1671 // ContextualCheckBlockHeader() here. This means that if we add a new
1672 // consensus rule that is enforced in one of those two functions, then we
1673 // may have let in a block that violates the rule prior to updating the
1674 // software, and we would NOT be enforcing the rule here. Fully solving
1675 // upgrade from one software version to the next after a consensus rule
1676 // change is potentially tricky and issue-specific (see RewindBlockIndex()
1677 // for one general approach that was used for BIP 141 deployment).
1678 // Also, currently the rule against blocks more than 2 hours in the future
1679 // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
1680 // re-enforce that rule here (at least until we make it impossible for
1681 // GetAdjustedTime() to go backward).
1682 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1683 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1685 // verify that the view's current state corresponds to the previous block
1686 uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
1687 assert(hashPrevBlock == view.GetBestBlock());
1689 // Special case for the genesis block, skipping connection of its transactions
1690 // (its coinbase is unspendable)
1691 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1692 if (!fJustCheck)
1693 view.SetBestBlock(pindex->GetBlockHash());
1694 return true;
1697 nBlocksTotal++;
1699 bool fScriptChecks = true;
1700 if (!hashAssumeValid.IsNull()) {
1701 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1702 // A suitable default value is included with the software and updated from time to time. Because validity
1703 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1704 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1705 // effectively caching the result of part of the verification.
1706 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1707 if (it != mapBlockIndex.end()) {
1708 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1709 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1710 pindexBestHeader->nChainWork >= nMinimumChainWork) {
1711 // This block is a member of the assumed verified chain and an ancestor of the best header.
1712 // The equivalent time check discourages hash power from extorting the network via DOS attack
1713 // into accepting an invalid block through telling users they must manually set assumevalid.
1714 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1715 // it hard to hide the implication of the demand. This also avoids having release candidates
1716 // that are hardly doing any signature verification at all in testing without having to
1717 // artificially set the default assumed verified block further back.
1718 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1719 // least as good as the expected chain.
1720 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1725 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1726 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
1728 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1729 // unless those are already completely spent.
1730 // If such overwrites are allowed, coinbases and transactions depending upon those
1731 // can be duplicated to remove the ability to spend the first instance -- even after
1732 // being sent to another address.
1733 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1734 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1735 // already refuses previously-known transaction ids entirely.
1736 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1737 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1738 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1739 // initial block download.
1740 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1741 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1742 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1744 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1745 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1746 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1747 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1748 // duplicate transactions descending from the known pairs either.
1749 // 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.
1750 assert(pindex->pprev);
1751 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1752 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1753 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1755 if (fEnforceBIP30) {
1756 for (const auto& tx : block.vtx) {
1757 for (size_t o = 0; o < tx->vout.size(); o++) {
1758 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
1759 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1760 REJECT_INVALID, "bad-txns-BIP30");
1766 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1767 int nLockTimeFlags = 0;
1768 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1769 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1772 // Get the script flags for this block
1773 unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
1775 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1776 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
1778 CBlockUndo blockundo;
1780 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
1782 std::vector<int> prevheights;
1783 CAmount nFees = 0;
1784 int nInputs = 0;
1785 int64_t nSigOpsCost = 0;
1786 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1787 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1788 vPos.reserve(block.vtx.size());
1789 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1790 std::vector<PrecomputedTransactionData> txdata;
1791 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1792 for (unsigned int i = 0; i < block.vtx.size(); i++)
1794 const CTransaction &tx = *(block.vtx[i]);
1796 nInputs += tx.vin.size();
1798 if (!tx.IsCoinBase())
1800 CAmount txfee = 0;
1801 if (!Consensus::CheckTxInputs(tx, state, view, pindex->nHeight, txfee)) {
1802 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
1804 nFees += txfee;
1805 if (!MoneyRange(nFees)) {
1806 return state.DoS(100, error("%s: accumulated fee in the block out of range.", __func__),
1807 REJECT_INVALID, "bad-txns-accumulated-fee-outofrange");
1810 // Check that transaction is BIP68 final
1811 // BIP68 lock checks (as opposed to nLockTime checks) must
1812 // be in ConnectBlock because they require the UTXO set
1813 prevheights.resize(tx.vin.size());
1814 for (size_t j = 0; j < tx.vin.size(); j++) {
1815 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
1818 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1819 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1820 REJECT_INVALID, "bad-txns-nonfinal");
1824 // GetTransactionSigOpCost counts 3 types of sigops:
1825 // * legacy (always)
1826 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1827 // * witness (when witness enabled in flags and excludes coinbase)
1828 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1829 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1830 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1831 REJECT_INVALID, "bad-blk-sigops");
1833 txdata.emplace_back(tx);
1834 if (!tx.IsCoinBase())
1836 std::vector<CScriptCheck> vChecks;
1837 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1838 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr))
1839 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1840 tx.GetHash().ToString(), FormatStateMessage(state));
1841 control.Add(vChecks);
1844 CTxUndo undoDummy;
1845 if (i > 0) {
1846 blockundo.vtxundo.push_back(CTxUndo());
1848 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1850 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1851 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1853 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1854 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);
1856 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1857 if (block.vtx[0]->GetValueOut() > blockReward)
1858 return state.DoS(100,
1859 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1860 block.vtx[0]->GetValueOut(), blockReward),
1861 REJECT_INVALID, "bad-cb-amount");
1863 if (!control.Wait())
1864 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1865 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1866 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);
1868 if (fJustCheck)
1869 return true;
1871 // Write undo information to disk
1872 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1874 if (pindex->GetUndoPos().IsNull()) {
1875 CDiskBlockPos _pos;
1876 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1877 return error("ConnectBlock(): FindUndoPos failed");
1878 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1879 return AbortNode(state, "Failed to write undo data");
1881 // update nUndoPos in block index
1882 pindex->nUndoPos = _pos.nPos;
1883 pindex->nStatus |= BLOCK_HAVE_UNDO;
1886 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1887 setDirtyBlockIndex.insert(pindex);
1890 if (fTxIndex)
1891 if (!pblocktree->WriteTxIndex(vPos))
1892 return AbortNode(state, "Failed to write transaction index");
1894 assert(pindex->phashBlock);
1895 // add this block to the view's block chain
1896 view.SetBestBlock(pindex->GetBlockHash());
1898 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1899 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
1901 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1902 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
1904 return true;
1908 * Update the on-disk chain state.
1909 * The caches and indexes are flushed depending on the mode we're called with
1910 * if they're too large, if it's been a while since the last write,
1911 * or always and in all cases if we're in prune mode and are deleting files.
1913 bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
1914 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
1915 LOCK(cs_main);
1916 static int64_t nLastWrite = 0;
1917 static int64_t nLastFlush = 0;
1918 static int64_t nLastSetChain = 0;
1919 std::set<int> setFilesToPrune;
1920 bool fFlushForPrune = false;
1921 bool fDoFullFlush = false;
1922 int64_t nNow = 0;
1923 try {
1925 LOCK(cs_LastBlockFile);
1926 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1927 if (nManualPruneHeight > 0) {
1928 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
1929 } else {
1930 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1931 fCheckForPruning = false;
1933 if (!setFilesToPrune.empty()) {
1934 fFlushForPrune = true;
1935 if (!fHavePruned) {
1936 pblocktree->WriteFlag("prunedblockfiles", true);
1937 fHavePruned = true;
1941 nNow = GetTimeMicros();
1942 // Avoid writing/flushing immediately after startup.
1943 if (nLastWrite == 0) {
1944 nLastWrite = nNow;
1946 if (nLastFlush == 0) {
1947 nLastFlush = nNow;
1949 if (nLastSetChain == 0) {
1950 nLastSetChain = nNow;
1952 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1953 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1954 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
1955 // 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).
1956 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
1957 // The cache is over the limit, we have to write now.
1958 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
1959 // 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.
1960 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1961 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1962 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1963 // Combine all conditions that result in a full cache flush.
1964 fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1965 // Write blocks and block index to disk.
1966 if (fDoFullFlush || fPeriodicWrite) {
1967 // Depend on nMinDiskSpace to ensure we can write block index
1968 if (!CheckDiskSpace(0))
1969 return state.Error("out of disk space");
1970 // First make sure all block and undo data is flushed to disk.
1971 FlushBlockFile();
1972 // Then update all block file information (which may refer to block and undo files).
1974 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1975 vFiles.reserve(setDirtyFileInfo.size());
1976 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1977 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
1978 setDirtyFileInfo.erase(it++);
1980 std::vector<const CBlockIndex*> vBlocks;
1981 vBlocks.reserve(setDirtyBlockIndex.size());
1982 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1983 vBlocks.push_back(*it);
1984 setDirtyBlockIndex.erase(it++);
1986 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1987 return AbortNode(state, "Failed to write to block index database");
1990 // Finally remove any pruned files
1991 if (fFlushForPrune)
1992 UnlinkPrunedFiles(setFilesToPrune);
1993 nLastWrite = nNow;
1995 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1996 if (fDoFullFlush) {
1997 // Typical Coin structures on disk are around 48 bytes in size.
1998 // Pushing a new one to the database can cause it to be written
1999 // twice (once in the log, and once in the tables). This is already
2000 // an overestimation, as most will delete an existing entry or
2001 // overwrite one. Still, use a conservative safety factor of 2.
2002 if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
2003 return state.Error("out of disk space");
2004 // Flush the chainstate (which may refer to block index entries).
2005 if (!pcoinsTip->Flush())
2006 return AbortNode(state, "Failed to write to coin database");
2007 nLastFlush = nNow;
2010 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
2011 // Update best block in wallet (so we can detect restored wallets).
2012 GetMainSignals().SetBestChain(chainActive.GetLocator());
2013 nLastSetChain = nNow;
2015 } catch (const std::runtime_error& e) {
2016 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2018 return true;
2021 void FlushStateToDisk() {
2022 CValidationState state;
2023 const CChainParams& chainparams = Params();
2024 FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
2027 void PruneAndFlush() {
2028 CValidationState state;
2029 fCheckForPruning = true;
2030 const CChainParams& chainparams = Params();
2031 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
2034 static void DoWarning(const std::string& strWarning)
2036 static bool fWarned = false;
2037 SetMiscWarning(strWarning);
2038 if (!fWarned) {
2039 AlertNotify(strWarning);
2040 fWarned = true;
2044 /** Update chainActive and related internal data structures. */
2045 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
2046 chainActive.SetTip(pindexNew);
2048 // New best block
2049 mempool.AddTransactionsUpdated(1);
2051 cvBlockChange.notify_all();
2053 std::vector<std::string> warningMessages;
2054 if (!IsInitialBlockDownload())
2056 int nUpgraded = 0;
2057 const CBlockIndex* pindex = chainActive.Tip();
2058 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2059 WarningBitsConditionChecker checker(bit);
2060 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2061 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2062 const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2063 if (state == THRESHOLD_ACTIVE) {
2064 DoWarning(strWarning);
2065 } else {
2066 warningMessages.push_back(strWarning);
2070 // Check the version of the last 100 blocks to see if we need to upgrade:
2071 for (int i = 0; i < 100 && pindex != nullptr; i++)
2073 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2074 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2075 ++nUpgraded;
2076 pindex = pindex->pprev;
2078 if (nUpgraded > 0)
2079 warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
2080 if (nUpgraded > 100/2)
2082 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2083 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2084 DoWarning(strWarning);
2087 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
2088 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
2089 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2090 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2091 GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2092 if (!warningMessages.empty())
2093 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2094 LogPrintf("\n");
2098 /** Disconnect chainActive's tip.
2099 * After calling, the mempool will be in an inconsistent state, with
2100 * transactions from disconnected blocks being added to disconnectpool. You
2101 * should make the mempool consistent again by calling UpdateMempoolForReorg.
2102 * with cs_main held.
2104 * If disconnectpool is nullptr, then no disconnected transactions are added to
2105 * disconnectpool (note that the caller is responsible for mempool consistency
2106 * in any case).
2108 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
2110 CBlockIndex *pindexDelete = chainActive.Tip();
2111 assert(pindexDelete);
2112 // Read block from disk.
2113 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2114 CBlock& block = *pblock;
2115 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2116 return AbortNode(state, "Failed to read block");
2117 // Apply the block atomically to the chain state.
2118 int64_t nStart = GetTimeMicros();
2120 CCoinsViewCache view(pcoinsTip.get());
2121 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2122 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2123 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2124 bool flushed = view.Flush();
2125 assert(flushed);
2127 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
2128 // Write the chain state to disk, if necessary.
2129 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2130 return false;
2132 if (disconnectpool) {
2133 // Save transactions to re-add to mempool at end of reorg
2134 for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2135 disconnectpool->addTransaction(*it);
2137 while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2138 // Drop the earliest entry, and remove its children from the mempool.
2139 auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2140 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
2141 disconnectpool->removeEntry(it);
2145 // Update chainActive and related variables.
2146 UpdateTip(pindexDelete->pprev, chainparams);
2147 // Let wallets know transactions went from 1-confirmed to
2148 // 0-confirmed or conflicted:
2149 GetMainSignals().BlockDisconnected(pblock);
2150 return true;
2153 static int64_t nTimeReadFromDisk = 0;
2154 static int64_t nTimeConnectTotal = 0;
2155 static int64_t nTimeFlush = 0;
2156 static int64_t nTimeChainState = 0;
2157 static int64_t nTimePostConnect = 0;
2159 struct PerBlockConnectTrace {
2160 CBlockIndex* pindex = nullptr;
2161 std::shared_ptr<const CBlock> pblock;
2162 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
2163 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
2166 * Used to track blocks whose transactions were applied to the UTXO state as a
2167 * part of a single ActivateBestChainStep call.
2169 * This class also tracks transactions that are removed from the mempool as
2170 * conflicts (per block) and can be used to pass all those transactions
2171 * through SyncTransaction.
2173 * This class assumes (and asserts) that the conflicted transactions for a given
2174 * block are added via mempool callbacks prior to the BlockConnected() associated
2175 * with those transactions. If any transactions are marked conflicted, it is
2176 * assumed that an associated block will always be added.
2178 * This class is single-use, once you call GetBlocksConnected() you have to throw
2179 * it away and make a new one.
2181 class ConnectTrace {
2182 private:
2183 std::vector<PerBlockConnectTrace> blocksConnected;
2184 CTxMemPool &pool;
2186 public:
2187 explicit ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
2188 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2191 ~ConnectTrace() {
2192 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2195 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2196 assert(!blocksConnected.back().pindex);
2197 assert(pindex);
2198 assert(pblock);
2199 blocksConnected.back().pindex = pindex;
2200 blocksConnected.back().pblock = std::move(pblock);
2201 blocksConnected.emplace_back();
2204 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2205 // We always keep one extra block at the end of our list because
2206 // blocks are added after all the conflicted transactions have
2207 // been filled in. Thus, the last entry should always be an empty
2208 // one waiting for the transactions from the next block. We pop
2209 // the last entry here to make sure the list we return is sane.
2210 assert(!blocksConnected.back().pindex);
2211 assert(blocksConnected.back().conflictedTxs->empty());
2212 blocksConnected.pop_back();
2213 return blocksConnected;
2216 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
2217 assert(!blocksConnected.back().pindex);
2218 if (reason == MemPoolRemovalReason::CONFLICT) {
2219 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2225 * Connect a new block to chainActive. pblock is either nullptr or a pointer to a CBlock
2226 * corresponding to pindexNew, to bypass loading it again from disk.
2228 * The block is added to connectTrace if connection succeeds.
2230 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
2232 assert(pindexNew->pprev == chainActive.Tip());
2233 // Read block from disk.
2234 int64_t nTime1 = GetTimeMicros();
2235 std::shared_ptr<const CBlock> pthisBlock;
2236 if (!pblock) {
2237 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2238 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2239 return AbortNode(state, "Failed to read block");
2240 pthisBlock = pblockNew;
2241 } else {
2242 pthisBlock = pblock;
2244 const CBlock& blockConnecting = *pthisBlock;
2245 // Apply the block atomically to the chain state.
2246 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2247 int64_t nTime3;
2248 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
2250 CCoinsViewCache view(pcoinsTip.get());
2251 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2252 GetMainSignals().BlockChecked(blockConnecting, state);
2253 if (!rv) {
2254 if (state.IsInvalid())
2255 InvalidBlockFound(pindexNew, state);
2256 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2258 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2259 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
2260 bool flushed = view.Flush();
2261 assert(flushed);
2263 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2264 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
2265 // Write the chain state to disk, if necessary.
2266 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2267 return false;
2268 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2269 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
2270 // Remove conflicting transactions from the mempool.;
2271 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2272 disconnectpool.removeForBlock(blockConnecting.vtx);
2273 // Update chainActive & related variables.
2274 UpdateTip(pindexNew, chainparams);
2276 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2277 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
2278 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
2280 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2281 return true;
2285 * Return the tip of the chain with the most work in it, that isn't
2286 * known to be invalid (it's however far from certain to be valid).
2288 static CBlockIndex* FindMostWorkChain() {
2289 do {
2290 CBlockIndex *pindexNew = nullptr;
2292 // Find the best candidate header.
2294 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2295 if (it == setBlockIndexCandidates.rend())
2296 return nullptr;
2297 pindexNew = *it;
2300 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2301 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2302 CBlockIndex *pindexTest = pindexNew;
2303 bool fInvalidAncestor = false;
2304 while (pindexTest && !chainActive.Contains(pindexTest)) {
2305 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2307 // Pruned nodes may have entries in setBlockIndexCandidates for
2308 // which block files have been deleted. Remove those as candidates
2309 // for the most work chain if we come across them; we can't switch
2310 // to a chain unless we have all the non-active-chain parent blocks.
2311 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2312 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2313 if (fFailedChain || fMissingData) {
2314 // Candidate chain is not usable (either invalid or missing data)
2315 if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2316 pindexBestInvalid = pindexNew;
2317 CBlockIndex *pindexFailed = pindexNew;
2318 // Remove the entire chain from the set.
2319 while (pindexTest != pindexFailed) {
2320 if (fFailedChain) {
2321 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2322 } else if (fMissingData) {
2323 // If we're missing data, then add back to mapBlocksUnlinked,
2324 // so that if the block arrives in the future we can try adding
2325 // to setBlockIndexCandidates again.
2326 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2328 setBlockIndexCandidates.erase(pindexFailed);
2329 pindexFailed = pindexFailed->pprev;
2331 setBlockIndexCandidates.erase(pindexTest);
2332 fInvalidAncestor = true;
2333 break;
2335 pindexTest = pindexTest->pprev;
2337 if (!fInvalidAncestor)
2338 return pindexNew;
2339 } while(true);
2342 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2343 static void PruneBlockIndexCandidates() {
2344 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2345 // reorganization to a better block fails.
2346 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2347 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2348 setBlockIndexCandidates.erase(it++);
2350 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2351 assert(!setBlockIndexCandidates.empty());
2355 * Try to make some progress towards making pindexMostWork the active block.
2356 * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
2358 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2360 AssertLockHeld(cs_main);
2361 const CBlockIndex *pindexOldTip = chainActive.Tip();
2362 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2364 // Disconnect active blocks which are no longer in the best chain.
2365 bool fBlocksDisconnected = false;
2366 DisconnectedBlockTransactions disconnectpool;
2367 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2368 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2369 // This is likely a fatal error, but keep the mempool consistent,
2370 // just in case. Only remove from the mempool in this case.
2371 UpdateMempoolForReorg(disconnectpool, false);
2372 return false;
2374 fBlocksDisconnected = true;
2377 // Build list of new blocks to connect.
2378 std::vector<CBlockIndex*> vpindexToConnect;
2379 bool fContinue = true;
2380 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2381 while (fContinue && nHeight != pindexMostWork->nHeight) {
2382 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2383 // a few blocks along the way.
2384 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2385 vpindexToConnect.clear();
2386 vpindexToConnect.reserve(nTargetHeight - nHeight);
2387 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2388 while (pindexIter && pindexIter->nHeight != nHeight) {
2389 vpindexToConnect.push_back(pindexIter);
2390 pindexIter = pindexIter->pprev;
2392 nHeight = nTargetHeight;
2394 // Connect new blocks.
2395 for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
2396 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2397 if (state.IsInvalid()) {
2398 // The block violates a consensus rule.
2399 if (!state.CorruptionPossible())
2400 InvalidChainFound(vpindexToConnect.back());
2401 state = CValidationState();
2402 fInvalidFound = true;
2403 fContinue = false;
2404 break;
2405 } else {
2406 // A system error occurred (disk space, database error, ...).
2407 // Make the mempool consistent with the current tip, just in case
2408 // any observers try to use it before shutdown.
2409 UpdateMempoolForReorg(disconnectpool, false);
2410 return false;
2412 } else {
2413 PruneBlockIndexCandidates();
2414 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2415 // We're in a better position than we were. Return temporarily to release the lock.
2416 fContinue = false;
2417 break;
2423 if (fBlocksDisconnected) {
2424 // If any blocks were disconnected, disconnectpool may be non empty. Add
2425 // any disconnected transactions back to the mempool.
2426 UpdateMempoolForReorg(disconnectpool, true);
2428 mempool.check(pcoinsTip.get());
2430 // Callbacks/notifications for a new best chain.
2431 if (fInvalidFound)
2432 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2433 else
2434 CheckForkWarningConditions();
2436 return true;
2439 static void NotifyHeaderTip() {
2440 bool fNotify = false;
2441 bool fInitialBlockDownload = false;
2442 static CBlockIndex* pindexHeaderOld = nullptr;
2443 CBlockIndex* pindexHeader = nullptr;
2445 LOCK(cs_main);
2446 pindexHeader = pindexBestHeader;
2448 if (pindexHeader != pindexHeaderOld) {
2449 fNotify = true;
2450 fInitialBlockDownload = IsInitialBlockDownload();
2451 pindexHeaderOld = pindexHeader;
2454 // Send block tip changed notifications without cs_main
2455 if (fNotify) {
2456 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2461 * Make the best chain active, in multiple steps. The result is either failure
2462 * or an activated best chain. pblock is either nullptr or a pointer to a block
2463 * that is already loaded (to avoid loading it again from disk).
2465 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2466 // Note that while we're often called here from ProcessNewBlock, this is
2467 // far from a guarantee. Things in the P2P/RPC will often end up calling
2468 // us in the middle of ProcessNewBlock - do not assume pblock is set
2469 // sanely for performance or correctness!
2471 CBlockIndex *pindexMostWork = nullptr;
2472 CBlockIndex *pindexNewTip = nullptr;
2473 int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2474 do {
2475 boost::this_thread::interruption_point();
2476 if (ShutdownRequested())
2477 break;
2479 const CBlockIndex *pindexFork;
2480 bool fInitialDownload;
2482 LOCK(cs_main);
2483 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2485 CBlockIndex *pindexOldTip = chainActive.Tip();
2486 if (pindexMostWork == nullptr) {
2487 pindexMostWork = FindMostWorkChain();
2490 // Whether we have anything to do at all.
2491 if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip())
2492 return true;
2494 bool fInvalidFound = false;
2495 std::shared_ptr<const CBlock> nullBlockPtr;
2496 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2497 return false;
2499 if (fInvalidFound) {
2500 // Wipe cache, we may need another branch now.
2501 pindexMostWork = nullptr;
2503 pindexNewTip = chainActive.Tip();
2504 pindexFork = chainActive.FindFork(pindexOldTip);
2505 fInitialDownload = IsInitialBlockDownload();
2507 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2508 assert(trace.pblock && trace.pindex);
2509 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, trace.conflictedTxs);
2512 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2514 // Notifications/callbacks that can run without cs_main
2516 // Notify external listeners about the new tip.
2517 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2519 // Always notify the UI if a new block tip was connected
2520 if (pindexFork != pindexNewTip) {
2521 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2524 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2525 } while (pindexNewTip != pindexMostWork);
2526 CheckBlockIndex(chainparams.GetConsensus());
2528 // Write changes periodically to disk, after relay.
2529 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
2530 return false;
2533 return true;
2537 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2540 LOCK(cs_main);
2541 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2542 // Nothing to do, this block is not at the tip.
2543 return true;
2545 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2546 // The chain has been extended since the last call, reset the counter.
2547 nBlockReverseSequenceId = -1;
2549 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2550 setBlockIndexCandidates.erase(pindex);
2551 pindex->nSequenceId = nBlockReverseSequenceId;
2552 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2553 // We can't keep reducing the counter if somebody really wants to
2554 // call preciousblock 2**31-1 times on the same set of tips...
2555 nBlockReverseSequenceId--;
2557 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2558 setBlockIndexCandidates.insert(pindex);
2559 PruneBlockIndexCandidates();
2563 return ActivateBestChain(state, params);
2566 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2568 AssertLockHeld(cs_main);
2570 // We first disconnect backwards and then mark the blocks as invalid.
2571 // This prevents a case where pruned nodes may fail to invalidateblock
2572 // and be left unable to start as they have no tip candidates (as there
2573 // are no blocks that meet the "have data and are not invalid per
2574 // nStatus" criteria for inclusion in setBlockIndexCandidates).
2576 bool pindex_was_in_chain = false;
2577 CBlockIndex *invalid_walk_tip = chainActive.Tip();
2579 DisconnectedBlockTransactions disconnectpool;
2580 while (chainActive.Contains(pindex)) {
2581 pindex_was_in_chain = true;
2582 // ActivateBestChain considers blocks already in chainActive
2583 // unconditionally valid already, so force disconnect away from it.
2584 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2585 // It's probably hopeless to try to make the mempool consistent
2586 // here if DisconnectTip failed, but we can try.
2587 UpdateMempoolForReorg(disconnectpool, false);
2588 return false;
2592 // Now mark the blocks we just disconnected as descendants invalid
2593 // (note this may not be all descendants).
2594 while (pindex_was_in_chain && invalid_walk_tip != pindex) {
2595 invalid_walk_tip->nStatus |= BLOCK_FAILED_CHILD;
2596 setDirtyBlockIndex.insert(invalid_walk_tip);
2597 setBlockIndexCandidates.erase(invalid_walk_tip);
2598 invalid_walk_tip = invalid_walk_tip->pprev;
2601 // Mark the block itself as invalid.
2602 pindex->nStatus |= BLOCK_FAILED_VALID;
2603 setDirtyBlockIndex.insert(pindex);
2604 setBlockIndexCandidates.erase(pindex);
2605 g_failed_blocks.insert(pindex);
2607 // DisconnectTip will add transactions to disconnectpool; try to add these
2608 // back to the mempool.
2609 UpdateMempoolForReorg(disconnectpool, true);
2611 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2612 // add it again.
2613 BlockMap::iterator it = mapBlockIndex.begin();
2614 while (it != mapBlockIndex.end()) {
2615 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2616 setBlockIndexCandidates.insert(it->second);
2618 it++;
2621 InvalidChainFound(pindex);
2622 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2623 return true;
2626 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2627 AssertLockHeld(cs_main);
2629 int nHeight = pindex->nHeight;
2631 // Remove the invalidity flag from this block and all its descendants.
2632 BlockMap::iterator it = mapBlockIndex.begin();
2633 while (it != mapBlockIndex.end()) {
2634 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2635 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2636 setDirtyBlockIndex.insert(it->second);
2637 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2638 setBlockIndexCandidates.insert(it->second);
2640 if (it->second == pindexBestInvalid) {
2641 // Reset invalid block marker if it was pointing to one of those.
2642 pindexBestInvalid = nullptr;
2644 g_failed_blocks.erase(it->second);
2646 it++;
2649 // Remove the invalidity flag from all ancestors too.
2650 while (pindex != nullptr) {
2651 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2652 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2653 setDirtyBlockIndex.insert(pindex);
2655 pindex = pindex->pprev;
2657 return true;
2660 static CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2662 // Check for duplicate
2663 uint256 hash = block.GetHash();
2664 BlockMap::iterator it = mapBlockIndex.find(hash);
2665 if (it != mapBlockIndex.end())
2666 return it->second;
2668 // Construct new block index object
2669 CBlockIndex* pindexNew = new CBlockIndex(block);
2670 // We assign the sequence id to blocks only when the full data is available,
2671 // to avoid miners withholding blocks but broadcasting headers, to get a
2672 // competitive advantage.
2673 pindexNew->nSequenceId = 0;
2674 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2675 pindexNew->phashBlock = &((*mi).first);
2676 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2677 if (miPrev != mapBlockIndex.end())
2679 pindexNew->pprev = (*miPrev).second;
2680 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2681 pindexNew->BuildSkip();
2683 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2684 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2685 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2686 if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2687 pindexBestHeader = pindexNew;
2689 setDirtyBlockIndex.insert(pindexNew);
2691 return pindexNew;
2694 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2695 static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2697 pindexNew->nTx = block.vtx.size();
2698 pindexNew->nChainTx = 0;
2699 pindexNew->nFile = pos.nFile;
2700 pindexNew->nDataPos = pos.nPos;
2701 pindexNew->nUndoPos = 0;
2702 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2703 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2704 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2706 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2707 setDirtyBlockIndex.insert(pindexNew);
2709 if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
2710 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2711 std::deque<CBlockIndex*> queue;
2712 queue.push_back(pindexNew);
2714 // Recursively process any descendant blocks that now may be eligible to be connected.
2715 while (!queue.empty()) {
2716 CBlockIndex *pindex = queue.front();
2717 queue.pop_front();
2718 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2720 LOCK(cs_nBlockSequenceId);
2721 pindex->nSequenceId = nBlockSequenceId++;
2723 if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2724 setBlockIndexCandidates.insert(pindex);
2726 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2727 while (range.first != range.second) {
2728 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2729 queue.push_back(it->second);
2730 range.first++;
2731 mapBlocksUnlinked.erase(it);
2734 } else {
2735 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2736 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2740 return true;
2743 static bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2745 LOCK(cs_LastBlockFile);
2747 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2748 if (vinfoBlockFile.size() <= nFile) {
2749 vinfoBlockFile.resize(nFile + 1);
2752 if (!fKnown) {
2753 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2754 nFile++;
2755 if (vinfoBlockFile.size() <= nFile) {
2756 vinfoBlockFile.resize(nFile + 1);
2759 pos.nFile = nFile;
2760 pos.nPos = vinfoBlockFile[nFile].nSize;
2763 if ((int)nFile != nLastBlockFile) {
2764 if (!fKnown) {
2765 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2767 FlushBlockFile(!fKnown);
2768 nLastBlockFile = nFile;
2771 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2772 if (fKnown)
2773 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2774 else
2775 vinfoBlockFile[nFile].nSize += nAddSize;
2777 if (!fKnown) {
2778 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2779 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2780 if (nNewChunks > nOldChunks) {
2781 if (fPruneMode)
2782 fCheckForPruning = true;
2783 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2784 FILE *file = OpenBlockFile(pos);
2785 if (file) {
2786 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2787 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2788 fclose(file);
2791 else
2792 return state.Error("out of disk space");
2796 setDirtyFileInfo.insert(nFile);
2797 return true;
2800 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2802 pos.nFile = nFile;
2804 LOCK(cs_LastBlockFile);
2806 unsigned int nNewSize;
2807 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2808 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2809 setDirtyFileInfo.insert(nFile);
2811 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2812 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2813 if (nNewChunks > nOldChunks) {
2814 if (fPruneMode)
2815 fCheckForPruning = true;
2816 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2817 FILE *file = OpenUndoFile(pos);
2818 if (file) {
2819 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2820 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2821 fclose(file);
2824 else
2825 return state.Error("out of disk space");
2828 return true;
2831 static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
2833 // Check proof of work matches claimed amount
2834 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2835 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2837 return true;
2840 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2842 // These are checks that are independent of context.
2844 if (block.fChecked)
2845 return true;
2847 // Check that the header is valid (particularly PoW). This is mostly
2848 // redundant with the call in AcceptBlockHeader.
2849 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2850 return false;
2852 // Check the merkle root.
2853 if (fCheckMerkleRoot) {
2854 bool mutated;
2855 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2856 if (block.hashMerkleRoot != hashMerkleRoot2)
2857 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2859 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2860 // of transactions in a block without affecting the merkle root of a block,
2861 // while still invalidating it.
2862 if (mutated)
2863 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2866 // All potential-corruption validation must be done before we do any
2867 // transaction validation, as otherwise we may mark the header as invalid
2868 // because we receive the wrong transactions for it.
2869 // Note that witness malleability is checked in ContextualCheckBlock, so no
2870 // checks that use witness data may be performed here.
2872 // Size limits
2873 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)
2874 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2876 // First transaction must be coinbase, the rest must not be
2877 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2878 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2879 for (unsigned int i = 1; i < block.vtx.size(); i++)
2880 if (block.vtx[i]->IsCoinBase())
2881 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2883 // Check transactions
2884 for (const auto& tx : block.vtx)
2885 if (!CheckTransaction(*tx, state, false))
2886 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2887 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2889 unsigned int nSigOps = 0;
2890 for (const auto& tx : block.vtx)
2892 nSigOps += GetLegacySigOpCount(*tx);
2894 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2895 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2897 if (fCheckPOW && fCheckMerkleRoot)
2898 block.fChecked = true;
2900 return true;
2903 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2905 LOCK(cs_main);
2906 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2909 // Compute at which vout of the block's coinbase transaction the witness
2910 // commitment occurs, or -1 if not found.
2911 static int GetWitnessCommitmentIndex(const CBlock& block)
2913 int commitpos = -1;
2914 if (!block.vtx.empty()) {
2915 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2916 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) {
2917 commitpos = o;
2921 return commitpos;
2924 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2926 int commitpos = GetWitnessCommitmentIndex(block);
2927 static const std::vector<unsigned char> nonce(32, 0x00);
2928 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2929 CMutableTransaction tx(*block.vtx[0]);
2930 tx.vin[0].scriptWitness.stack.resize(1);
2931 tx.vin[0].scriptWitness.stack[0] = nonce;
2932 block.vtx[0] = MakeTransactionRef(std::move(tx));
2936 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2938 std::vector<unsigned char> commitment;
2939 int commitpos = GetWitnessCommitmentIndex(block);
2940 std::vector<unsigned char> ret(32, 0x00);
2941 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2942 if (commitpos == -1) {
2943 uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
2944 CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
2945 CTxOut out;
2946 out.nValue = 0;
2947 out.scriptPubKey.resize(38);
2948 out.scriptPubKey[0] = OP_RETURN;
2949 out.scriptPubKey[1] = 0x24;
2950 out.scriptPubKey[2] = 0xaa;
2951 out.scriptPubKey[3] = 0x21;
2952 out.scriptPubKey[4] = 0xa9;
2953 out.scriptPubKey[5] = 0xed;
2954 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2955 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2956 CMutableTransaction tx(*block.vtx[0]);
2957 tx.vout.push_back(out);
2958 block.vtx[0] = MakeTransactionRef(std::move(tx));
2961 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2962 return commitment;
2965 /** Context-dependent validity checks.
2966 * By "context", we mean only the previous block headers, but not the UTXO
2967 * set; UTXO-related validity checks are done in ConnectBlock().
2968 * NOTE: This function is not currently invoked by ConnectBlock(), so we
2969 * should consider upgrade issues if we change which consensus rules are
2970 * enforced in this function (eg by adding a new consensus rule). See comment
2971 * in ConnectBlock().
2972 * Note that -reindex-chainstate skips the validation that happens here!
2974 static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2976 assert(pindexPrev != nullptr);
2977 const int nHeight = pindexPrev->nHeight + 1;
2979 // Check proof of work
2980 const Consensus::Params& consensusParams = params.GetConsensus();
2981 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2982 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2984 // Check against checkpoints
2985 if (fCheckpointsEnabled) {
2986 // Don't accept any forks from the main chain prior to last checkpoint.
2987 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
2988 // MapBlockIndex.
2989 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(params.Checkpoints());
2990 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2991 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
2994 // Check timestamp against prev
2995 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2996 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2998 // Check timestamp
2999 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
3000 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
3002 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
3003 // check for version 2, 3 and 4 upgrades
3004 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
3005 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
3006 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
3007 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
3008 strprintf("rejected nVersion=0x%08x block", block.nVersion));
3010 return true;
3013 /** NOTE: This function is not currently invoked by ConnectBlock(), so we
3014 * should consider upgrade issues if we change which consensus rules are
3015 * enforced in this function (eg by adding a new consensus rule). See comment
3016 * in ConnectBlock().
3017 * Note that -reindex-chainstate skips the validation that happens here!
3019 static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
3021 const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
3023 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
3024 int nLockTimeFlags = 0;
3025 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
3026 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
3029 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3030 ? pindexPrev->GetMedianTimePast()
3031 : block.GetBlockTime();
3033 // Check that all transactions are finalized
3034 for (const auto& tx : block.vtx) {
3035 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
3036 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
3040 // Enforce rule that the coinbase starts with serialized block height
3041 if (nHeight >= consensusParams.BIP34Height)
3043 CScript expect = CScript() << nHeight;
3044 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
3045 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
3046 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
3050 // Validation for witness commitments.
3051 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
3052 // coinbase (where 0x0000....0000 is used instead).
3053 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
3054 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
3055 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
3056 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
3057 // multiple, the last one is used.
3058 bool fHaveWitness = false;
3059 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
3060 int commitpos = GetWitnessCommitmentIndex(block);
3061 if (commitpos != -1) {
3062 bool malleated = false;
3063 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
3064 // The malleation check is ignored; as the transaction tree itself
3065 // already does not permit it, it is impossible to trigger in the
3066 // witness tree.
3067 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3068 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
3070 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
3071 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3072 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
3074 fHaveWitness = true;
3078 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3079 if (!fHaveWitness) {
3080 for (const auto& tx : block.vtx) {
3081 if (tx->HasWitness()) {
3082 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
3087 // After the coinbase witness nonce and commitment are verified,
3088 // we can check if the block weight passes (before we've checked the
3089 // coinbase witness, it would be possible for the weight to be too
3090 // large by filling up the coinbase witness, which doesn't change
3091 // the block hash, so we couldn't mark the block as permanently
3092 // failed).
3093 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3094 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
3097 return true;
3100 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3102 AssertLockHeld(cs_main);
3103 // Check for duplicate
3104 uint256 hash = block.GetHash();
3105 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3106 CBlockIndex *pindex = nullptr;
3107 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3109 if (miSelf != mapBlockIndex.end()) {
3110 // Block header is already known.
3111 pindex = miSelf->second;
3112 if (ppindex)
3113 *ppindex = pindex;
3114 if (pindex->nStatus & BLOCK_FAILED_MASK)
3115 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3116 return true;
3119 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3120 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3122 // Get prev block index
3123 CBlockIndex* pindexPrev = nullptr;
3124 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3125 if (mi == mapBlockIndex.end())
3126 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
3127 pindexPrev = (*mi).second;
3128 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3129 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3130 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3131 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3133 if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
3134 for (const CBlockIndex* failedit : g_failed_blocks) {
3135 if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
3136 assert(failedit->nStatus & BLOCK_FAILED_VALID);
3137 CBlockIndex* invalid_walk = pindexPrev;
3138 while (invalid_walk != failedit) {
3139 invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
3140 setDirtyBlockIndex.insert(invalid_walk);
3141 invalid_walk = invalid_walk->pprev;
3143 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3148 if (pindex == nullptr)
3149 pindex = AddToBlockIndex(block);
3151 if (ppindex)
3152 *ppindex = pindex;
3154 CheckBlockIndex(chainparams.GetConsensus());
3156 return true;
3159 // Exposed wrapper for AcceptBlockHeader
3160 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex, CBlockHeader *first_invalid)
3162 if (first_invalid != nullptr) first_invalid->SetNull();
3164 LOCK(cs_main);
3165 for (const CBlockHeader& header : headers) {
3166 CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3167 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
3168 if (first_invalid) *first_invalid = header;
3169 return false;
3171 if (ppindex) {
3172 *ppindex = pindex;
3176 NotifyHeaderTip();
3177 return true;
3180 /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
3181 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3183 const CBlock& block = *pblock;
3185 if (fNewBlock) *fNewBlock = false;
3186 AssertLockHeld(cs_main);
3188 CBlockIndex *pindexDummy = nullptr;
3189 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3191 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3192 return false;
3194 // Try to process all requested blocks that we don't have, but only
3195 // process an unrequested block if it's new and has enough work to
3196 // advance our tip, and isn't too many blocks ahead.
3197 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3198 bool fHasMoreOrSameWork = (chainActive.Tip() ? pindex->nChainWork >= chainActive.Tip()->nChainWork : true);
3199 // Blocks that are too out-of-order needlessly limit the effectiveness of
3200 // pruning, because pruning will not delete block files that contain any
3201 // blocks which are too close in height to the tip. Apply this test
3202 // regardless of whether pruning is enabled; it should generally be safe to
3203 // not process unrequested blocks.
3204 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3206 // TODO: Decouple this function from the block download logic by removing fRequested
3207 // This requires some new chain data structure to efficiently look up if a
3208 // block is in a chain leading to a candidate for best tip, despite not
3209 // being such a candidate itself.
3211 // TODO: deal better with return value and error conditions for duplicate
3212 // and unrequested blocks.
3213 if (fAlreadyHave) return true;
3214 if (!fRequested) { // If we didn't ask for it:
3215 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3216 if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
3217 if (fTooFarAhead) return true; // Block height is too high
3219 // Protect against DoS attacks from low-work chains.
3220 // If our tip is behind, a peer could try to send us
3221 // low-work blocks on a fake chain that we would never
3222 // request; don't process these.
3223 if (pindex->nChainWork < nMinimumChainWork) return true;
3225 if (fNewBlock) *fNewBlock = true;
3227 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3228 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3229 if (state.IsInvalid() && !state.CorruptionPossible()) {
3230 pindex->nStatus |= BLOCK_FAILED_VALID;
3231 setDirtyBlockIndex.insert(pindex);
3233 return error("%s: %s", __func__, FormatStateMessage(state));
3236 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3237 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3238 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3239 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3241 int nHeight = pindex->nHeight;
3243 // Write block to history file
3244 try {
3245 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3246 CDiskBlockPos blockPos;
3247 if (dbp != nullptr)
3248 blockPos = *dbp;
3249 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr))
3250 return error("AcceptBlock(): FindBlockPos failed");
3251 if (dbp == nullptr)
3252 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3253 AbortNode(state, "Failed to write block");
3254 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3255 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3256 } catch (const std::runtime_error& e) {
3257 return AbortNode(state, std::string("System error: ") + e.what());
3260 if (fCheckForPruning)
3261 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3263 return true;
3266 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3269 CBlockIndex *pindex = nullptr;
3270 if (fNewBlock) *fNewBlock = false;
3271 CValidationState state;
3272 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3273 // belt-and-suspenders.
3274 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3276 LOCK(cs_main);
3278 if (ret) {
3279 // Store to disk
3280 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
3282 CheckBlockIndex(chainparams.GetConsensus());
3283 if (!ret) {
3284 GetMainSignals().BlockChecked(*pblock, state);
3285 return error("%s: AcceptBlock FAILED (%s)", __func__, state.GetDebugMessage());
3289 NotifyHeaderTip();
3291 CValidationState state; // Only used to report errors, not invalidity - ignore it
3292 if (!ActivateBestChain(state, chainparams, pblock))
3293 return error("%s: ActivateBestChain failed", __func__);
3295 return true;
3298 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3300 AssertLockHeld(cs_main);
3301 assert(pindexPrev && pindexPrev == chainActive.Tip());
3302 CCoinsViewCache viewNew(pcoinsTip.get());
3303 CBlockIndex indexDummy(block);
3304 indexDummy.pprev = pindexPrev;
3305 indexDummy.nHeight = pindexPrev->nHeight + 1;
3307 // NOTE: CheckBlockHeader is called by CheckBlock
3308 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3309 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3310 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3311 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3312 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3313 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3314 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3315 return false;
3316 assert(state.IsValid());
3318 return true;
3322 * BLOCK PRUNING CODE
3325 /* Calculate the amount of disk space the block & undo files currently use */
3326 uint64_t CalculateCurrentUsage()
3328 LOCK(cs_LastBlockFile);
3330 uint64_t retval = 0;
3331 for (const CBlockFileInfo &file : vinfoBlockFile) {
3332 retval += file.nSize + file.nUndoSize;
3334 return retval;
3337 /* Prune a block file (modify associated database entries)*/
3338 void PruneOneBlockFile(const int fileNumber)
3340 LOCK(cs_LastBlockFile);
3342 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3343 CBlockIndex* pindex = it->second;
3344 if (pindex->nFile == fileNumber) {
3345 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3346 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3347 pindex->nFile = 0;
3348 pindex->nDataPos = 0;
3349 pindex->nUndoPos = 0;
3350 setDirtyBlockIndex.insert(pindex);
3352 // Prune from mapBlocksUnlinked -- any block we prune would have
3353 // to be downloaded again in order to consider its chain, at which
3354 // point it would be considered as a candidate for
3355 // mapBlocksUnlinked or setBlockIndexCandidates.
3356 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3357 while (range.first != range.second) {
3358 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3359 range.first++;
3360 if (_it->second == pindex) {
3361 mapBlocksUnlinked.erase(_it);
3367 vinfoBlockFile[fileNumber].SetNull();
3368 setDirtyFileInfo.insert(fileNumber);
3372 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3374 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3375 CDiskBlockPos pos(*it, 0);
3376 fs::remove(GetBlockPosFilename(pos, "blk"));
3377 fs::remove(GetBlockPosFilename(pos, "rev"));
3378 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3382 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3383 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3385 assert(fPruneMode && nManualPruneHeight > 0);
3387 LOCK2(cs_main, cs_LastBlockFile);
3388 if (chainActive.Tip() == nullptr)
3389 return;
3391 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3392 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3393 int count=0;
3394 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3395 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3396 continue;
3397 PruneOneBlockFile(fileNumber);
3398 setFilesToPrune.insert(fileNumber);
3399 count++;
3401 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3404 /* This function is called from the RPC code for pruneblockchain */
3405 void PruneBlockFilesManual(int nManualPruneHeight)
3407 CValidationState state;
3408 const CChainParams& chainparams = Params();
3409 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
3413 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
3414 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
3415 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
3416 * (which in this case means the blockchain must be re-downloaded.)
3418 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
3419 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
3420 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
3421 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
3422 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
3423 * A db flag records the fact that at least some block files have been pruned.
3425 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
3427 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3429 LOCK2(cs_main, cs_LastBlockFile);
3430 if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
3431 return;
3433 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3434 return;
3437 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3438 uint64_t nCurrentUsage = CalculateCurrentUsage();
3439 // We don't check to prune until after we've allocated new space for files
3440 // So we should leave a buffer under our target to account for another allocation
3441 // before the next pruning.
3442 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3443 uint64_t nBytesToPrune;
3444 int count=0;
3446 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3447 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3448 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3450 if (vinfoBlockFile[fileNumber].nSize == 0)
3451 continue;
3453 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3454 break;
3456 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3457 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3458 continue;
3460 PruneOneBlockFile(fileNumber);
3461 // Queue up the files for removal
3462 setFilesToPrune.insert(fileNumber);
3463 nCurrentUsage -= nBytesToPrune;
3464 count++;
3468 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3469 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3470 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3471 nLastBlockWeCanPrune, count);
3474 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3476 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3478 // Check for nMinDiskSpace bytes (currently 50MB)
3479 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3480 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3482 return true;
3485 static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3487 if (pos.IsNull())
3488 return nullptr;
3489 fs::path path = GetBlockPosFilename(pos, prefix);
3490 fs::create_directories(path.parent_path());
3491 FILE* file = fsbridge::fopen(path, fReadOnly ? "rb": "rb+");
3492 if (!file && !fReadOnly)
3493 file = fsbridge::fopen(path, "wb+");
3494 if (!file) {
3495 LogPrintf("Unable to open file %s\n", path.string());
3496 return nullptr;
3498 if (pos.nPos) {
3499 if (fseek(file, pos.nPos, SEEK_SET)) {
3500 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3501 fclose(file);
3502 return nullptr;
3505 return file;
3508 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3509 return OpenDiskFile(pos, "blk", fReadOnly);
3512 /** Open an undo file (rev?????.dat) */
3513 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3514 return OpenDiskFile(pos, "rev", fReadOnly);
3517 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3519 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3522 CBlockIndex * InsertBlockIndex(uint256 hash)
3524 if (hash.IsNull())
3525 return nullptr;
3527 // Return existing
3528 BlockMap::iterator mi = mapBlockIndex.find(hash);
3529 if (mi != mapBlockIndex.end())
3530 return (*mi).second;
3532 // Create new
3533 CBlockIndex* pindexNew = new CBlockIndex();
3534 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3535 pindexNew->phashBlock = &((*mi).first);
3537 return pindexNew;
3540 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3542 if (!pblocktree->LoadBlockIndexGuts(chainparams.GetConsensus(), InsertBlockIndex))
3543 return false;
3545 boost::this_thread::interruption_point();
3547 // Calculate nChainWork
3548 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3549 vSortedByHeight.reserve(mapBlockIndex.size());
3550 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3552 CBlockIndex* pindex = item.second;
3553 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3555 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3556 for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
3558 CBlockIndex* pindex = item.second;
3559 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3560 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3561 // We can link the chain of blocks for which we've received transactions at some point.
3562 // Pruned nodes may have deleted the block.
3563 if (pindex->nTx > 0) {
3564 if (pindex->pprev) {
3565 if (pindex->pprev->nChainTx) {
3566 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3567 } else {
3568 pindex->nChainTx = 0;
3569 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3571 } else {
3572 pindex->nChainTx = pindex->nTx;
3575 if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
3576 pindex->nStatus |= BLOCK_FAILED_CHILD;
3577 setDirtyBlockIndex.insert(pindex);
3579 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
3580 setBlockIndexCandidates.insert(pindex);
3581 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3582 pindexBestInvalid = pindex;
3583 if (pindex->pprev)
3584 pindex->BuildSkip();
3585 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3586 pindexBestHeader = pindex;
3589 // Load block file info
3590 pblocktree->ReadLastBlockFile(nLastBlockFile);
3591 vinfoBlockFile.resize(nLastBlockFile + 1);
3592 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3593 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3594 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3596 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3597 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3598 CBlockFileInfo info;
3599 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3600 vinfoBlockFile.push_back(info);
3601 } else {
3602 break;
3606 // Check presence of blk files
3607 LogPrintf("Checking all blk files are present...\n");
3608 std::set<int> setBlkDataFiles;
3609 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3611 CBlockIndex* pindex = item.second;
3612 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3613 setBlkDataFiles.insert(pindex->nFile);
3616 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3618 CDiskBlockPos pos(*it, 0);
3619 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3620 return false;
3624 // Check whether we have ever pruned block & undo files
3625 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3626 if (fHavePruned)
3627 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3629 // Check whether we need to continue reindexing
3630 bool fReindexing = false;
3631 pblocktree->ReadReindexing(fReindexing);
3632 if(fReindexing) fReindex = true;
3634 // Check whether we have a transaction index
3635 pblocktree->ReadFlag("txindex", fTxIndex);
3636 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3638 return true;
3641 bool LoadChainTip(const CChainParams& chainparams)
3643 if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
3645 if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
3646 // In case we just added the genesis block, connect it now, so
3647 // that we always have a chainActive.Tip() when we return.
3648 LogPrintf("%s: Connecting genesis block...\n", __func__);
3649 CValidationState state;
3650 if (!ActivateBestChain(state, chainparams)) {
3651 return false;
3655 // Load pointer to end of best chain
3656 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3657 if (it == mapBlockIndex.end())
3658 return false;
3659 chainActive.SetTip(it->second);
3661 PruneBlockIndexCandidates();
3663 LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
3664 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3665 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3666 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3667 return true;
3670 CVerifyDB::CVerifyDB()
3672 uiInterface.ShowProgress(_("Verifying blocks..."), 0, false);
3675 CVerifyDB::~CVerifyDB()
3677 uiInterface.ShowProgress("", 100, false);
3680 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3682 LOCK(cs_main);
3683 if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
3684 return true;
3686 // Verify blocks in the best chain
3687 if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height())
3688 nCheckDepth = chainActive.Height();
3689 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3690 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3691 CCoinsViewCache coins(coinsview);
3692 CBlockIndex* pindexState = chainActive.Tip();
3693 CBlockIndex* pindexFailure = nullptr;
3694 int nGoodTransactions = 0;
3695 CValidationState state;
3696 int reportDone = 0;
3697 LogPrintf("[0%%]...");
3698 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3700 boost::this_thread::interruption_point();
3701 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3702 if (reportDone < percentageDone/10) {
3703 // report every 10% step
3704 LogPrintf("[%d%%]...", percentageDone);
3705 reportDone = percentageDone/10;
3707 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false);
3708 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3709 break;
3710 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3711 // If pruning, only go back as far as we have data.
3712 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3713 break;
3715 CBlock block;
3716 // check level 0: read from disk
3717 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3718 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3719 // check level 1: verify block validity
3720 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3721 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3722 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3723 // check level 2: verify undo validity
3724 if (nCheckLevel >= 2 && pindex) {
3725 CBlockUndo undo;
3726 CDiskBlockPos pos = pindex->GetUndoPos();
3727 if (!pos.IsNull()) {
3728 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3729 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3732 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3733 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3734 assert(coins.GetBestBlock() == pindex->GetBlockHash());
3735 DisconnectResult res = DisconnectBlock(block, pindex, coins);
3736 if (res == DISCONNECT_FAILED) {
3737 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3739 pindexState = pindex->pprev;
3740 if (res == DISCONNECT_UNCLEAN) {
3741 nGoodTransactions = 0;
3742 pindexFailure = pindex;
3743 } else {
3744 nGoodTransactions += block.vtx.size();
3747 if (ShutdownRequested())
3748 return true;
3750 if (pindexFailure)
3751 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3753 // check level 4: try reconnecting blocks
3754 if (nCheckLevel >= 4) {
3755 CBlockIndex *pindex = pindexState;
3756 while (pindex != chainActive.Tip()) {
3757 boost::this_thread::interruption_point();
3758 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))), false);
3759 pindex = chainActive.Next(pindex);
3760 CBlock block;
3761 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3762 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3763 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3764 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3768 LogPrintf("[DONE].\n");
3769 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3771 return true;
3774 /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
3775 static bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
3777 // TODO: merge with ConnectBlock
3778 CBlock block;
3779 if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
3780 return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3783 for (const CTransactionRef& tx : block.vtx) {
3784 if (!tx->IsCoinBase()) {
3785 for (const CTxIn &txin : tx->vin) {
3786 inputs.SpendCoin(txin.prevout);
3789 // Pass check = true as every addition may be an overwrite.
3790 AddCoins(inputs, *tx, pindex->nHeight, true);
3792 return true;
3795 bool ReplayBlocks(const CChainParams& params, CCoinsView* view)
3797 LOCK(cs_main);
3799 CCoinsViewCache cache(view);
3801 std::vector<uint256> hashHeads = view->GetHeadBlocks();
3802 if (hashHeads.empty()) return true; // We're already in a consistent state.
3803 if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
3805 uiInterface.ShowProgress(_("Replaying blocks..."), 0, false);
3806 LogPrintf("Replaying blocks\n");
3808 const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
3809 const CBlockIndex* pindexNew; // New tip during the interrupted flush.
3810 const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
3812 if (mapBlockIndex.count(hashHeads[0]) == 0) {
3813 return error("ReplayBlocks(): reorganization to unknown block requested");
3815 pindexNew = mapBlockIndex[hashHeads[0]];
3817 if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
3818 if (mapBlockIndex.count(hashHeads[1]) == 0) {
3819 return error("ReplayBlocks(): reorganization from unknown block requested");
3821 pindexOld = mapBlockIndex[hashHeads[1]];
3822 pindexFork = LastCommonAncestor(pindexOld, pindexNew);
3823 assert(pindexFork != nullptr);
3826 // Rollback along the old branch.
3827 while (pindexOld != pindexFork) {
3828 if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
3829 CBlock block;
3830 if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
3831 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3833 LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
3834 DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
3835 if (res == DISCONNECT_FAILED) {
3836 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3838 // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
3839 // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
3840 // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
3841 // the result is still a version of the UTXO set with the effects of that block undone.
3843 pindexOld = pindexOld->pprev;
3846 // Roll forward from the forking point to the new tip.
3847 int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
3848 for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
3849 const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
3850 LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
3851 if (!RollforwardBlock(pindex, cache, params)) return false;
3854 cache.SetBestBlock(pindexNew->GetBlockHash());
3855 cache.Flush();
3856 uiInterface.ShowProgress("", 100, false);
3857 return true;
3860 bool RewindBlockIndex(const CChainParams& params)
3862 LOCK(cs_main);
3864 // Note that during -reindex-chainstate we are called with an empty chainActive!
3866 int nHeight = 1;
3867 while (nHeight <= chainActive.Height()) {
3868 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3869 break;
3871 nHeight++;
3874 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3875 CValidationState state;
3876 CBlockIndex* pindex = chainActive.Tip();
3877 while (chainActive.Height() >= nHeight) {
3878 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3879 // If pruning, don't try rewinding past the HAVE_DATA point;
3880 // since older blocks can't be served anyway, there's
3881 // no need to walk further, and trying to DisconnectTip()
3882 // will fail (and require a needless reindex/redownload
3883 // of the blockchain).
3884 break;
3886 if (!DisconnectTip(state, params, nullptr)) {
3887 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3889 // Occasionally flush state to disk.
3890 if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
3891 return false;
3894 // Reduce validity flag and have-data flags.
3895 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3896 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3897 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3898 CBlockIndex* pindexIter = it->second;
3900 // Note: If we encounter an insufficiently validated block that
3901 // is on chainActive, it must be because we are a pruning node, and
3902 // this block or some successor doesn't HAVE_DATA, so we were unable to
3903 // rewind all the way. Blocks remaining on chainActive at this point
3904 // must not have their validity reduced.
3905 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3906 // Reduce validity
3907 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3908 // Remove have-data flags.
3909 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3910 // Remove storage location.
3911 pindexIter->nFile = 0;
3912 pindexIter->nDataPos = 0;
3913 pindexIter->nUndoPos = 0;
3914 // Remove various other things
3915 pindexIter->nTx = 0;
3916 pindexIter->nChainTx = 0;
3917 pindexIter->nSequenceId = 0;
3918 // Make sure it gets written.
3919 setDirtyBlockIndex.insert(pindexIter);
3920 // Update indexes
3921 setBlockIndexCandidates.erase(pindexIter);
3922 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3923 while (ret.first != ret.second) {
3924 if (ret.first->second == pindexIter) {
3925 mapBlocksUnlinked.erase(ret.first++);
3926 } else {
3927 ++ret.first;
3930 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3931 setBlockIndexCandidates.insert(pindexIter);
3935 if (chainActive.Tip() != nullptr) {
3936 // We can't prune block index candidates based on our tip if we have
3937 // no tip due to chainActive being empty!
3938 PruneBlockIndexCandidates();
3940 CheckBlockIndex(params.GetConsensus());
3942 // FlushStateToDisk can possibly read chainActive. Be conservative
3943 // and skip it here, we're about to -reindex-chainstate anyway, so
3944 // it'll get called a bunch real soon.
3945 if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
3946 return false;
3950 return true;
3953 // May NOT be used after any connections are up as much
3954 // of the peer-processing logic assumes a consistent
3955 // block index state
3956 void UnloadBlockIndex()
3958 LOCK(cs_main);
3959 setBlockIndexCandidates.clear();
3960 chainActive.SetTip(nullptr);
3961 pindexBestInvalid = nullptr;
3962 pindexBestHeader = nullptr;
3963 mempool.clear();
3964 mapBlocksUnlinked.clear();
3965 vinfoBlockFile.clear();
3966 nLastBlockFile = 0;
3967 nBlockSequenceId = 1;
3968 setDirtyBlockIndex.clear();
3969 g_failed_blocks.clear();
3970 setDirtyFileInfo.clear();
3971 versionbitscache.Clear();
3972 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3973 warningcache[b].clear();
3976 for (BlockMap::value_type& entry : mapBlockIndex) {
3977 delete entry.second;
3979 mapBlockIndex.clear();
3980 fHavePruned = false;
3983 bool LoadBlockIndex(const CChainParams& chainparams)
3985 // Load block index from databases
3986 bool needs_init = fReindex;
3987 if (!fReindex) {
3988 bool ret = LoadBlockIndexDB(chainparams);
3989 if (!ret) return false;
3990 needs_init = mapBlockIndex.empty();
3993 if (needs_init) {
3994 // Everything here is for *new* reindex/DBs. Thus, though
3995 // LoadBlockIndexDB may have set fReindex if we shut down
3996 // mid-reindex previously, we don't check fReindex and
3997 // instead only check it prior to LoadBlockIndexDB to set
3998 // needs_init.
4000 LogPrintf("Initializing databases...\n");
4001 // Use the provided setting for -txindex in the new database
4002 fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
4003 pblocktree->WriteFlag("txindex", fTxIndex);
4005 return true;
4008 bool LoadGenesisBlock(const CChainParams& chainparams)
4010 LOCK(cs_main);
4012 // Check whether we're already initialized by checking for genesis in
4013 // mapBlockIndex. Note that we can't use chainActive here, since it is
4014 // set based on the coins db, not the block index db, which is the only
4015 // thing loaded at this point.
4016 if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
4017 return true;
4019 try {
4020 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
4021 // Start new block file
4022 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4023 CDiskBlockPos blockPos;
4024 CValidationState state;
4025 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
4026 return error("%s: FindBlockPos failed", __func__);
4027 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
4028 return error("%s: writing genesis block to disk failed", __func__);
4029 CBlockIndex *pindex = AddToBlockIndex(block);
4030 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
4031 return error("%s: genesis block not accepted", __func__);
4032 } catch (const std::runtime_error& e) {
4033 return error("%s: failed to write genesis block: %s", __func__, e.what());
4036 return true;
4039 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
4041 // Map of disk positions for blocks with unknown parent (only used for reindex)
4042 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4043 int64_t nStart = GetTimeMillis();
4045 int nLoaded = 0;
4046 try {
4047 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4048 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
4049 uint64_t nRewind = blkdat.GetPos();
4050 while (!blkdat.eof()) {
4051 boost::this_thread::interruption_point();
4053 blkdat.SetPos(nRewind);
4054 nRewind++; // start one byte further next time, in case of failure
4055 blkdat.SetLimit(); // remove former limit
4056 unsigned int nSize = 0;
4057 try {
4058 // locate a header
4059 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
4060 blkdat.FindByte(chainparams.MessageStart()[0]);
4061 nRewind = blkdat.GetPos()+1;
4062 blkdat >> FLATDATA(buf);
4063 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
4064 continue;
4065 // read size
4066 blkdat >> nSize;
4067 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
4068 continue;
4069 } catch (const std::exception&) {
4070 // no valid block header found; don't complain
4071 break;
4073 try {
4074 // read block
4075 uint64_t nBlockPos = blkdat.GetPos();
4076 if (dbp)
4077 dbp->nPos = nBlockPos;
4078 blkdat.SetLimit(nBlockPos + nSize);
4079 blkdat.SetPos(nBlockPos);
4080 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4081 CBlock& block = *pblock;
4082 blkdat >> block;
4083 nRewind = blkdat.GetPos();
4085 // detect out of order blocks, and store them for later
4086 uint256 hash = block.GetHash();
4087 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4088 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4089 block.hashPrevBlock.ToString());
4090 if (dbp)
4091 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4092 continue;
4095 // process in case the block isn't known yet
4096 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4097 LOCK(cs_main);
4098 CValidationState state;
4099 if (AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
4100 nLoaded++;
4101 if (state.IsError())
4102 break;
4103 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4104 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4107 // Activate the genesis block so normal node progress can continue
4108 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
4109 CValidationState state;
4110 if (!ActivateBestChain(state, chainparams)) {
4111 break;
4115 NotifyHeaderTip();
4117 // Recursively process earlier encountered successors of this block
4118 std::deque<uint256> queue;
4119 queue.push_back(hash);
4120 while (!queue.empty()) {
4121 uint256 head = queue.front();
4122 queue.pop_front();
4123 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4124 while (range.first != range.second) {
4125 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4126 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4127 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
4129 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4130 head.ToString());
4131 LOCK(cs_main);
4132 CValidationState dummy;
4133 if (AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
4135 nLoaded++;
4136 queue.push_back(pblockrecursive->GetHash());
4139 range.first++;
4140 mapBlocksUnknownParent.erase(it);
4141 NotifyHeaderTip();
4144 } catch (const std::exception& e) {
4145 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4148 } catch (const std::runtime_error& e) {
4149 AbortNode(std::string("System error: ") + e.what());
4151 if (nLoaded > 0)
4152 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4153 return nLoaded > 0;
4156 void static CheckBlockIndex(const Consensus::Params& consensusParams)
4158 if (!fCheckBlockIndex) {
4159 return;
4162 LOCK(cs_main);
4164 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4165 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4166 // iterating the block tree require that chainActive has been initialized.)
4167 if (chainActive.Height() < 0) {
4168 assert(mapBlockIndex.size() <= 1);
4169 return;
4172 // Build forward-pointing map of the entire block tree.
4173 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4174 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4175 forward.insert(std::make_pair(it->second->pprev, it->second));
4178 assert(forward.size() == mapBlockIndex.size());
4180 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4181 CBlockIndex *pindex = rangeGenesis.first->second;
4182 rangeGenesis.first++;
4183 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4185 // Iterate over the entire block tree, using depth-first search.
4186 // Along the way, remember whether there are blocks on the path from genesis
4187 // block being explored which are the first to have certain properties.
4188 size_t nNodes = 0;
4189 int nHeight = 0;
4190 CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4191 CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4192 CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4193 CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4194 CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4195 CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4196 CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4197 while (pindex != nullptr) {
4198 nNodes++;
4199 if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4200 if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4201 if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4202 if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4203 if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4204 if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4205 if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4207 // Begin: actual consistency checks.
4208 if (pindex->pprev == nullptr) {
4209 // Genesis block checks.
4210 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4211 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4213 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)
4214 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4215 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4216 if (!fHavePruned) {
4217 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4218 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4219 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4220 } else {
4221 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4222 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4224 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4225 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4226 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4227 assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4228 assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
4229 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4230 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.
4231 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4232 assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
4233 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4234 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4235 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4236 if (pindexFirstInvalid == nullptr) {
4237 // Checks for not-invalid blocks.
4238 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4240 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
4241 if (pindexFirstInvalid == nullptr) {
4242 // If this block sorts at least as good as the current tip and
4243 // is valid and we have all data for its parents, it must be in
4244 // setBlockIndexCandidates. chainActive.Tip() must also be there
4245 // even if some data has been pruned.
4246 if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
4247 assert(setBlockIndexCandidates.count(pindex));
4249 // If some parent is missing, then it could be that this block was in
4250 // setBlockIndexCandidates but had to be removed because of the missing data.
4251 // In this case it must be in mapBlocksUnlinked -- see test below.
4253 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4254 assert(setBlockIndexCandidates.count(pindex) == 0);
4256 // Check whether this block is in mapBlocksUnlinked.
4257 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4258 bool foundInUnlinked = false;
4259 while (rangeUnlinked.first != rangeUnlinked.second) {
4260 assert(rangeUnlinked.first->first == pindex->pprev);
4261 if (rangeUnlinked.first->second == pindex) {
4262 foundInUnlinked = true;
4263 break;
4265 rangeUnlinked.first++;
4267 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4268 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4269 assert(foundInUnlinked);
4271 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4272 if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4273 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4274 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4275 assert(fHavePruned); // We must have pruned.
4276 // This block may have entered mapBlocksUnlinked if:
4277 // - it has a descendant that at some point had more work than the
4278 // tip, and
4279 // - we tried switching to that descendant but were missing
4280 // data for some intermediate block between chainActive and the
4281 // tip.
4282 // So if this block is itself better than chainActive.Tip() and it wasn't in
4283 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4284 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4285 if (pindexFirstInvalid == nullptr) {
4286 assert(foundInUnlinked);
4290 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4291 // End: actual consistency checks.
4293 // Try descending into the first subnode.
4294 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4295 if (range.first != range.second) {
4296 // A subnode was found.
4297 pindex = range.first->second;
4298 nHeight++;
4299 continue;
4301 // This is a leaf node.
4302 // Move upwards until we reach a node of which we have not yet visited the last child.
4303 while (pindex) {
4304 // We are going to either move to a parent or a sibling of pindex.
4305 // If pindex was the first with a certain property, unset the corresponding variable.
4306 if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4307 if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4308 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4309 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4310 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4311 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4312 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4313 // Find our parent.
4314 CBlockIndex* pindexPar = pindex->pprev;
4315 // Find which child we just visited.
4316 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4317 while (rangePar.first->second != pindex) {
4318 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4319 rangePar.first++;
4321 // Proceed to the next one.
4322 rangePar.first++;
4323 if (rangePar.first != rangePar.second) {
4324 // Move to the sibling.
4325 pindex = rangePar.first->second;
4326 break;
4327 } else {
4328 // Move up further.
4329 pindex = pindexPar;
4330 nHeight--;
4331 continue;
4336 // Check that we actually traversed the entire map.
4337 assert(nNodes == forward.size());
4340 std::string CBlockFileInfo::ToString() const
4342 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));
4345 CBlockFileInfo* GetBlockFileInfo(size_t n)
4347 LOCK(cs_LastBlockFile);
4349 return &vinfoBlockFile.at(n);
4352 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
4354 LOCK(cs_main);
4355 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4358 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
4360 LOCK(cs_main);
4361 return VersionBitsStatistics(chainActive.Tip(), params, pos);
4364 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
4366 LOCK(cs_main);
4367 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
4370 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4372 bool LoadMempool(void)
4374 const CChainParams& chainparams = Params();
4375 int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4376 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4377 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4378 if (file.IsNull()) {
4379 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4380 return false;
4383 int64_t count = 0;
4384 int64_t expired = 0;
4385 int64_t failed = 0;
4386 int64_t already_there = 0;
4387 int64_t nNow = GetTime();
4389 try {
4390 uint64_t version;
4391 file >> version;
4392 if (version != MEMPOOL_DUMP_VERSION) {
4393 return false;
4395 uint64_t num;
4396 file >> num;
4397 while (num--) {
4398 CTransactionRef tx;
4399 int64_t nTime;
4400 int64_t nFeeDelta;
4401 file >> tx;
4402 file >> nTime;
4403 file >> nFeeDelta;
4405 CAmount amountdelta = nFeeDelta;
4406 if (amountdelta) {
4407 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4409 CValidationState state;
4410 if (nTime + nExpiryTimeout > nNow) {
4411 LOCK(cs_main);
4412 AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, nullptr /* pfMissingInputs */, nTime,
4413 nullptr /* plTxnReplaced */, false /* bypass_limits */, 0 /* nAbsurdFee */);
4414 if (state.IsValid()) {
4415 ++count;
4416 } else {
4417 // mempool may contain the transaction already, e.g. from
4418 // wallet(s) having loaded it while we were processing
4419 // mempool transactions; consider these as valid, instead of
4420 // failed, but mark them as 'already there'
4421 if (mempool.exists(tx->GetHash())) {
4422 ++already_there;
4423 } else {
4424 ++failed;
4427 } else {
4428 ++expired;
4430 if (ShutdownRequested())
4431 return false;
4433 std::map<uint256, CAmount> mapDeltas;
4434 file >> mapDeltas;
4436 for (const auto& i : mapDeltas) {
4437 mempool.PrioritiseTransaction(i.first, i.second);
4439 } catch (const std::exception& e) {
4440 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4441 return false;
4444 LogPrintf("Imported mempool transactions from disk: %i succeeded, %i failed, %i expired, %i already there\n", count, failed, expired, already_there);
4445 return true;
4448 bool DumpMempool(void)
4450 int64_t start = GetTimeMicros();
4452 std::map<uint256, CAmount> mapDeltas;
4453 std::vector<TxMempoolInfo> vinfo;
4456 LOCK(mempool.cs);
4457 for (const auto &i : mempool.mapDeltas) {
4458 mapDeltas[i.first] = i.second;
4460 vinfo = mempool.infoAll();
4463 int64_t mid = GetTimeMicros();
4465 try {
4466 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4467 if (!filestr) {
4468 return false;
4471 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4473 uint64_t version = MEMPOOL_DUMP_VERSION;
4474 file << version;
4476 file << (uint64_t)vinfo.size();
4477 for (const auto& i : vinfo) {
4478 file << *(i.tx);
4479 file << (int64_t)i.nTime;
4480 file << (int64_t)i.nFeeDelta;
4481 mapDeltas.erase(i.tx->GetHash());
4484 file << mapDeltas;
4485 FileCommit(file.Get());
4486 file.fclose();
4487 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4488 int64_t last = GetTimeMicros();
4489 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
4490 } catch (const std::exception& e) {
4491 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4492 return false;
4494 return true;
4497 //! Guess how far we are in the verification process at the given block index
4498 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4499 if (pindex == nullptr)
4500 return 0.0;
4502 int64_t nNow = time(nullptr);
4504 double fTxTotal;
4506 if (pindex->nChainTx <= data.nTxCount) {
4507 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4508 } else {
4509 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4512 return pindex->nChainTx / fTxTotal;
4515 class CMainCleanup
4517 public:
4518 CMainCleanup() {}
4519 ~CMainCleanup() {
4520 // block headers
4521 BlockMap::iterator it1 = mapBlockIndex.begin();
4522 for (; it1 != mapBlockIndex.end(); it1++)
4523 delete (*it1).second;
4524 mapBlockIndex.clear();
4526 } instance_of_cmaincleanup;