Remove duplicate destination decoding
[bitcoinplatinum.git] / src / validation.cpp
blobd8788548ffad709201ce38d8645574ee4aeee0c0
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 bool fReindex = false;
73 bool fTxIndex = false;
74 bool fHavePruned = false;
75 bool fPruneMode = false;
76 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
77 bool fRequireStandard = true;
78 bool fCheckBlockIndex = false;
79 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
80 size_t nCoinCacheUsage = 5000 * 300;
81 uint64_t nPruneTarget = 0;
82 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
83 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
85 uint256 hashAssumeValid;
86 arith_uint256 nMinimumChainWork;
88 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
89 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
91 CBlockPolicyEstimator feeEstimator;
92 CTxMemPool mempool(&feeEstimator);
94 static void CheckBlockIndex(const Consensus::Params& consensusParams);
96 /** Constant stuff for coinbase transactions we create: */
97 CScript COINBASE_FLAGS;
99 const std::string strMessageMagic = "Bitcoin Signed Message:\n";
101 // Internal stuff
102 namespace {
104 struct CBlockIndexWorkComparator
106 bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
107 // First sort by most total work, ...
108 if (pa->nChainWork > pb->nChainWork) return false;
109 if (pa->nChainWork < pb->nChainWork) return true;
111 // ... then by earliest time received, ...
112 if (pa->nSequenceId < pb->nSequenceId) return false;
113 if (pa->nSequenceId > pb->nSequenceId) return true;
115 // Use pointer address as tie breaker (should only happen with blocks
116 // loaded from disk, as those all have id 0).
117 if (pa < pb) return false;
118 if (pa > pb) return true;
120 // Identical blocks.
121 return false;
125 CBlockIndex *pindexBestInvalid;
128 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
129 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
130 * missing the data for the block.
132 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
133 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
134 * Pruned nodes may have entries where B is missing data.
136 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
138 CCriticalSection cs_LastBlockFile;
139 std::vector<CBlockFileInfo> vinfoBlockFile;
140 int nLastBlockFile = 0;
141 /** Global flag to indicate we should check to see if there are
142 * block/undo files that should be deleted. Set on startup
143 * or if we allocate more file space when we're in prune mode
145 bool fCheckForPruning = false;
148 * Every received block is assigned a unique and increasing identifier, so we
149 * know which one to give priority in case of a fork.
151 CCriticalSection cs_nBlockSequenceId;
152 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
153 int32_t nBlockSequenceId = 1;
154 /** Decreasing counter (used by subsequent preciousblock calls). */
155 int32_t nBlockReverseSequenceId = -1;
156 /** chainwork for the last block that preciousblock has been applied to. */
157 arith_uint256 nLastPreciousChainwork = 0;
159 /** Dirty block index entries. */
160 std::set<CBlockIndex*> setDirtyBlockIndex;
162 /** Dirty block file entries. */
163 std::set<int> setDirtyFileInfo;
164 } // anon namespace
166 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
168 // Find the first block the caller has in the main chain
169 for (const uint256& hash : locator.vHave) {
170 BlockMap::iterator mi = mapBlockIndex.find(hash);
171 if (mi != mapBlockIndex.end())
173 CBlockIndex* pindex = (*mi).second;
174 if (chain.Contains(pindex))
175 return pindex;
176 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
177 return chain.Tip();
181 return chain.Genesis();
184 CCoinsViewDB *pcoinsdbview = nullptr;
185 CCoinsViewCache *pcoinsTip = nullptr;
186 CBlockTreeDB *pblocktree = nullptr;
188 enum FlushStateMode {
189 FLUSH_STATE_NONE,
190 FLUSH_STATE_IF_NEEDED,
191 FLUSH_STATE_PERIODIC,
192 FLUSH_STATE_ALWAYS
195 // See definition for documentation
196 static bool FlushStateToDisk(const CChainParams& chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
197 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
198 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
199 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks = nullptr);
200 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
202 bool CheckFinalTx(const CTransaction &tx, int flags)
204 AssertLockHeld(cs_main);
206 // By convention a negative value for flags indicates that the
207 // current network-enforced consensus rules should be used. In
208 // a future soft-fork scenario that would mean checking which
209 // rules would be enforced for the next block and setting the
210 // appropriate flags. At the present time no soft-forks are
211 // scheduled, so no flags are set.
212 flags = std::max(flags, 0);
214 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
215 // nLockTime because when IsFinalTx() is called within
216 // CBlock::AcceptBlock(), the height of the block *being*
217 // evaluated is what is used. Thus if we want to know if a
218 // transaction can be part of the *next* block, we need to call
219 // IsFinalTx() with one more than chainActive.Height().
220 const int nBlockHeight = chainActive.Height() + 1;
222 // BIP113 will require that time-locked transactions have nLockTime set to
223 // less than the median time of the previous block they're contained in.
224 // When the next block is created its previous block will be the current
225 // chain tip, so we use that to calculate the median time passed to
226 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
227 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
228 ? chainActive.Tip()->GetMedianTimePast()
229 : GetAdjustedTime();
231 return IsFinalTx(tx, nBlockHeight, nBlockTime);
234 bool TestLockPointValidity(const LockPoints* lp)
236 AssertLockHeld(cs_main);
237 assert(lp);
238 // If there are relative lock times then the maxInputBlock will be set
239 // If there are no relative lock times, the LockPoints don't depend on the chain
240 if (lp->maxInputBlock) {
241 // Check whether chainActive is an extension of the block at which the LockPoints
242 // calculation was valid. If not LockPoints are no longer valid
243 if (!chainActive.Contains(lp->maxInputBlock)) {
244 return false;
248 // LockPoints still valid
249 return true;
252 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
254 AssertLockHeld(cs_main);
255 AssertLockHeld(mempool.cs);
257 CBlockIndex* tip = chainActive.Tip();
258 assert(tip != nullptr);
260 CBlockIndex index;
261 index.pprev = tip;
262 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
263 // height based locks because when SequenceLocks() is called within
264 // ConnectBlock(), the height of the block *being*
265 // evaluated is what is used.
266 // Thus if we want to know if a transaction can be part of the
267 // *next* block, we need to use one more than chainActive.Height()
268 index.nHeight = tip->nHeight + 1;
270 std::pair<int, int64_t> lockPair;
271 if (useExistingLockPoints) {
272 assert(lp);
273 lockPair.first = lp->height;
274 lockPair.second = lp->time;
276 else {
277 // pcoinsTip contains the UTXO set for chainActive.Tip()
278 CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
279 std::vector<int> prevheights;
280 prevheights.resize(tx.vin.size());
281 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
282 const CTxIn& txin = tx.vin[txinIndex];
283 Coin coin;
284 if (!viewMemPool.GetCoin(txin.prevout, coin)) {
285 return error("%s: Missing input", __func__);
287 if (coin.nHeight == MEMPOOL_HEIGHT) {
288 // Assume all mempool transaction confirm in the next block
289 prevheights[txinIndex] = tip->nHeight + 1;
290 } else {
291 prevheights[txinIndex] = coin.nHeight;
294 lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
295 if (lp) {
296 lp->height = lockPair.first;
297 lp->time = lockPair.second;
298 // Also store the hash of the block with the highest height of
299 // all the blocks which have sequence locked prevouts.
300 // This hash needs to still be on the chain
301 // for these LockPoint calculations to be valid
302 // Note: It is impossible to correctly calculate a maxInputBlock
303 // if any of the sequence locked inputs depend on unconfirmed txs,
304 // except in the special case where the relative lock time/height
305 // is 0, which is equivalent to no sequence lock. Since we assume
306 // input height of tip+1 for mempool txs and test the resulting
307 // lockPair from CalculateSequenceLocks against tip+1. We know
308 // EvaluateSequenceLocks will fail if there was a non-zero sequence
309 // lock on a mempool input, so we can use the return value of
310 // CheckSequenceLocks to indicate the LockPoints validity
311 int maxInputHeight = 0;
312 for (int height : prevheights) {
313 // Can ignore mempool inputs since we'll fail if they had non-zero locks
314 if (height != tip->nHeight+1) {
315 maxInputHeight = std::max(maxInputHeight, height);
318 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
321 return EvaluateSequenceLocks(index, lockPair);
324 // Returns the script flags which should be checked for a given block
325 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
327 static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
328 int expired = pool.Expire(GetTime() - age);
329 if (expired != 0) {
330 LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
333 std::vector<COutPoint> vNoSpendsRemaining;
334 pool.TrimToSize(limit, &vNoSpendsRemaining);
335 for (const COutPoint& removed : vNoSpendsRemaining)
336 pcoinsTip->Uncache(removed);
339 /** Convert CValidationState to a human-readable message for logging */
340 std::string FormatStateMessage(const CValidationState &state)
342 return strprintf("%s%s (code %i)",
343 state.GetRejectReason(),
344 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
345 state.GetRejectCode());
348 static bool IsCurrentForFeeEstimation()
350 AssertLockHeld(cs_main);
351 if (IsInitialBlockDownload())
352 return false;
353 if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
354 return false;
355 if (chainActive.Height() < pindexBestHeader->nHeight - 1)
356 return false;
357 return true;
360 /* Make mempool consistent after a reorg, by re-adding or recursively erasing
361 * disconnected block transactions from the mempool, and also removing any
362 * other transactions from the mempool that are no longer valid given the new
363 * tip/height.
365 * Note: we assume that disconnectpool only contains transactions that are NOT
366 * confirmed in the current chain nor already in the mempool (otherwise,
367 * in-mempool descendants of such transactions would be removed).
369 * Passing fAddToMempool=false will skip trying to add the transactions back,
370 * and instead just erase from the mempool as needed.
373 void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
375 AssertLockHeld(cs_main);
376 std::vector<uint256> vHashUpdate;
377 // disconnectpool's insertion_order index sorts the entries from
378 // oldest to newest, but the oldest entry will be the last tx from the
379 // latest mined block that was disconnected.
380 // Iterate disconnectpool in reverse, so that we add transactions
381 // back to the mempool starting with the earliest transaction that had
382 // been previously seen in a block.
383 auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
384 while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
385 // ignore validation errors in resurrected transactions
386 CValidationState stateDummy;
387 if (!fAddToMempool || (*it)->IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, *it, false, nullptr, nullptr, true)) {
388 // If the transaction doesn't make it in to the mempool, remove any
389 // transactions that depend on it (which would now be orphans).
390 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
391 } else if (mempool.exists((*it)->GetHash())) {
392 vHashUpdate.push_back((*it)->GetHash());
394 ++it;
396 disconnectpool.queuedTx.clear();
397 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
398 // no in-mempool children, which is generally not true when adding
399 // previously-confirmed transactions back to the mempool.
400 // UpdateTransactionsFromBlock finds descendants of any transactions in
401 // the disconnectpool that were added back and cleans up the mempool state.
402 mempool.UpdateTransactionsFromBlock(vHashUpdate);
404 // We also need to remove any now-immature transactions
405 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
406 // Re-limit mempool size, in case we added any transactions
407 LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
410 // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
411 // were somehow broken and returning the wrong scriptPubKeys
412 static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool& pool,
413 unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) {
414 AssertLockHeld(cs_main);
416 // pool.cs should be locked already, but go ahead and re-take the lock here
417 // to enforce that mempool doesn't change between when we check the view
418 // and when we actually call through to CheckInputs
419 LOCK(pool.cs);
421 assert(!tx.IsCoinBase());
422 for (const CTxIn& txin : tx.vin) {
423 const Coin& coin = view.AccessCoin(txin.prevout);
425 // At this point we haven't actually checked if the coins are all
426 // available (or shouldn't assume we have, since CheckInputs does).
427 // So we just return failure if the inputs are not available here,
428 // and then only have to check equivalence for available inputs.
429 if (coin.IsSpent()) return false;
431 const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
432 if (txFrom) {
433 assert(txFrom->GetHash() == txin.prevout.hash);
434 assert(txFrom->vout.size() > txin.prevout.n);
435 assert(txFrom->vout[txin.prevout.n] == coin.out);
436 } else {
437 const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout);
438 assert(!coinFromDisk.IsSpent());
439 assert(coinFromDisk.out == coin.out);
443 return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata);
446 static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool fLimitFree,
447 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
448 bool fOverrideMempoolLimit, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache)
450 const CTransaction& tx = *ptx;
451 const uint256 hash = tx.GetHash();
452 AssertLockHeld(cs_main);
453 if (pfMissingInputs)
454 *pfMissingInputs = false;
456 if (!CheckTransaction(tx, state))
457 return false; // state filled in by CheckTransaction
459 // Coinbase is only valid in a block, not as a loose transaction
460 if (tx.IsCoinBase())
461 return state.DoS(100, false, REJECT_INVALID, "coinbase");
463 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
464 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), chainparams.GetConsensus());
465 if (!gArgs.GetBoolArg("-prematurewitness", false) && tx.HasWitness() && !witnessEnabled) {
466 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
469 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
470 std::string reason;
471 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
472 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
474 // Only accept nLockTime-using transactions that can be mined in the next
475 // block; we don't want our mempool filled up with transactions that can't
476 // be mined yet.
477 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
478 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
480 // is it already in the memory pool?
481 if (pool.exists(hash)) {
482 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool");
485 // Check for conflicts with in-memory transactions
486 std::set<uint256> setConflicts;
488 LOCK(pool.cs); // protect pool.mapNextTx
489 for (const CTxIn &txin : tx.vin)
491 auto itConflicting = pool.mapNextTx.find(txin.prevout);
492 if (itConflicting != pool.mapNextTx.end())
494 const CTransaction *ptxConflicting = itConflicting->second;
495 if (!setConflicts.count(ptxConflicting->GetHash()))
497 // Allow opt-out of transaction replacement by setting
498 // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
500 // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
501 // non-replaceable transactions. All inputs rather than just one
502 // is for the sake of multi-party protocols, where we don't
503 // want a single party to be able to disable replacement.
505 // The opt-out ignores descendants as anyone relying on
506 // first-seen mempool behavior should be checking all
507 // unconfirmed ancestors anyway; doing otherwise is hopelessly
508 // insecure.
509 bool fReplacementOptOut = true;
510 if (fEnableReplacement)
512 for (const CTxIn &_txin : ptxConflicting->vin)
514 if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
516 fReplacementOptOut = false;
517 break;
521 if (fReplacementOptOut) {
522 return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict");
525 setConflicts.insert(ptxConflicting->GetHash());
532 CCoinsView dummy;
533 CCoinsViewCache view(&dummy);
535 CAmount nValueIn = 0;
536 LockPoints lp;
538 LOCK(pool.cs);
539 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
540 view.SetBackend(viewMemPool);
542 // do all inputs exist?
543 for (const CTxIn txin : tx.vin) {
544 if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
545 coins_to_uncache.push_back(txin.prevout);
547 if (!view.HaveCoin(txin.prevout)) {
548 // Are inputs missing because we already have the tx?
549 for (size_t out = 0; out < tx.vout.size(); out++) {
550 // Optimistically just do efficient check of cache for outputs
551 if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
552 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
555 // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
556 if (pfMissingInputs) {
557 *pfMissingInputs = true;
559 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
563 // Bring the best block into scope
564 view.GetBestBlock();
566 nValueIn = view.GetValueIn(tx);
568 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
569 view.SetBackend(dummy);
571 // Only accept BIP68 sequence locked transactions that can be mined in the next
572 // block; we don't want our mempool filled up with transactions that can't
573 // be mined yet.
574 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
575 // CoinsViewCache instead of create its own
576 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
577 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
580 // Check for non-standard pay-to-script-hash in inputs
581 if (fRequireStandard && !AreInputsStandard(tx, view))
582 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
584 // Check for non-standard witness in P2WSH
585 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
586 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
588 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
590 CAmount nValueOut = tx.GetValueOut();
591 CAmount nFees = nValueIn-nValueOut;
592 // nModifiedFees includes any fee deltas from PrioritiseTransaction
593 CAmount nModifiedFees = nFees;
594 pool.ApplyDelta(hash, nModifiedFees);
596 // Keep track of transactions that spend a coinbase, which we re-scan
597 // during reorgs to ensure COINBASE_MATURITY is still met.
598 bool fSpendsCoinbase = false;
599 for (const CTxIn &txin : tx.vin) {
600 const Coin &coin = view.AccessCoin(txin.prevout);
601 if (coin.IsCoinBase()) {
602 fSpendsCoinbase = true;
603 break;
607 CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
608 fSpendsCoinbase, nSigOpsCost, lp);
609 unsigned int nSize = entry.GetTxSize();
611 // Check that the transaction doesn't have an excessive number of
612 // sigops, making it impossible to mine. Since the coinbase transaction
613 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
614 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
615 // merely non-standard transaction.
616 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
617 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
618 strprintf("%d", nSigOpsCost));
620 CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
621 if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
622 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
625 // No transactions are allowed below minRelayTxFee except from disconnected blocks
626 if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
627 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
630 if (nAbsurdFee && nFees > nAbsurdFee)
631 return state.Invalid(false,
632 REJECT_HIGHFEE, "absurdly-high-fee",
633 strprintf("%d > %d", nFees, nAbsurdFee));
635 // Calculate in-mempool ancestors, up to a limit.
636 CTxMemPool::setEntries setAncestors;
637 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
638 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
639 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
640 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
641 std::string errString;
642 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
643 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
646 // A transaction that spends outputs that would be replaced by it is invalid. Now
647 // that we have the set of all ancestors we can detect this
648 // pathological case by making sure setConflicts and setAncestors don't
649 // intersect.
650 for (CTxMemPool::txiter ancestorIt : setAncestors)
652 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
653 if (setConflicts.count(hashAncestor))
655 return state.DoS(10, false,
656 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
657 strprintf("%s spends conflicting transaction %s",
658 hash.ToString(),
659 hashAncestor.ToString()));
663 // Check if it's economically rational to mine this transaction rather
664 // than the ones it replaces.
665 CAmount nConflictingFees = 0;
666 size_t nConflictingSize = 0;
667 uint64_t nConflictingCount = 0;
668 CTxMemPool::setEntries allConflicting;
670 // If we don't hold the lock allConflicting might be incomplete; the
671 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
672 // mempool consistency for us.
673 LOCK(pool.cs);
674 const bool fReplacementTransaction = setConflicts.size();
675 if (fReplacementTransaction)
677 CFeeRate newFeeRate(nModifiedFees, nSize);
678 std::set<uint256> setConflictsParents;
679 const int maxDescendantsToVisit = 100;
680 CTxMemPool::setEntries setIterConflicting;
681 for (const uint256 &hashConflicting : setConflicts)
683 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
684 if (mi == pool.mapTx.end())
685 continue;
687 // Save these to avoid repeated lookups
688 setIterConflicting.insert(mi);
690 // Don't allow the replacement to reduce the feerate of the
691 // mempool.
693 // We usually don't want to accept replacements with lower
694 // feerates than what they replaced as that would lower the
695 // feerate of the next block. Requiring that the feerate always
696 // be increased is also an easy-to-reason about way to prevent
697 // DoS attacks via replacements.
699 // The mining code doesn't (currently) take children into
700 // account (CPFP) so we only consider the feerates of
701 // transactions being directly replaced, not their indirect
702 // descendants. While that does mean high feerate children are
703 // ignored when deciding whether or not to replace, we do
704 // require the replacement to pay more overall fees too,
705 // mitigating most cases.
706 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
707 if (newFeeRate <= oldFeeRate)
709 return state.DoS(0, false,
710 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
711 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
712 hash.ToString(),
713 newFeeRate.ToString(),
714 oldFeeRate.ToString()));
717 for (const CTxIn &txin : mi->GetTx().vin)
719 setConflictsParents.insert(txin.prevout.hash);
722 nConflictingCount += mi->GetCountWithDescendants();
724 // This potentially overestimates the number of actual descendants
725 // but we just want to be conservative to avoid doing too much
726 // work.
727 if (nConflictingCount <= maxDescendantsToVisit) {
728 // If not too many to replace, then calculate the set of
729 // transactions that would have to be evicted
730 for (CTxMemPool::txiter it : setIterConflicting) {
731 pool.CalculateDescendants(it, allConflicting);
733 for (CTxMemPool::txiter it : allConflicting) {
734 nConflictingFees += it->GetModifiedFee();
735 nConflictingSize += it->GetTxSize();
737 } else {
738 return state.DoS(0, false,
739 REJECT_NONSTANDARD, "too many potential replacements", false,
740 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
741 hash.ToString(),
742 nConflictingCount,
743 maxDescendantsToVisit));
746 for (unsigned int j = 0; j < tx.vin.size(); j++)
748 // We don't want to accept replacements that require low
749 // feerate junk to be mined first. Ideally we'd keep track of
750 // the ancestor feerates and make the decision based on that,
751 // but for now requiring all new inputs to be confirmed works.
752 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
754 // Rather than check the UTXO set - potentially expensive -
755 // it's cheaper to just check if the new input refers to a
756 // tx that's in the mempool.
757 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
758 return state.DoS(0, false,
759 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
760 strprintf("replacement %s adds unconfirmed input, idx %d",
761 hash.ToString(), j));
765 // The replacement must pay greater fees than the transactions it
766 // replaces - if we did the bandwidth used by those conflicting
767 // transactions would not be paid for.
768 if (nModifiedFees < nConflictingFees)
770 return state.DoS(0, false,
771 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
772 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
773 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
776 // Finally in addition to paying more fees than the conflicts the
777 // new transaction must pay for its own bandwidth.
778 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
779 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
781 return state.DoS(0, false,
782 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
783 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
784 hash.ToString(),
785 FormatMoney(nDeltaFees),
786 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
790 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
791 if (!chainparams.RequireStandard()) {
792 scriptVerifyFlags = gArgs.GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
795 // Check against previous transactions
796 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
797 PrecomputedTransactionData txdata(tx);
798 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, txdata)) {
799 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
800 // need to turn both off, and compare against just turning off CLEANSTACK
801 // to see if the failure is specifically due to witness validation.
802 CValidationState stateDummy; // Want reported failures to be from first CheckInputs
803 if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
804 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
805 // Only the witness is missing, so the transaction itself may be fine.
806 state.SetCorruptionPossible();
808 return false; // state filled in by CheckInputs
811 // Check again against the current block tip's script verification
812 // flags to cache our script execution flags. This is, of course,
813 // useless if the next block has different script flags from the
814 // previous one, but because the cache tracks script flags for us it
815 // will auto-invalidate and we'll just have a few blocks of extra
816 // misses on soft-fork activation.
818 // This is also useful in case of bugs in the standard flags that cause
819 // transactions to pass as valid when they're actually invalid. For
820 // instance the STRICTENC flag was incorrectly allowing certain
821 // CHECKSIG NOT scripts to pass, even though they were invalid.
823 // There is a similar check in CreateNewBlock() to prevent creating
824 // invalid blocks (using TestBlockValidity), however allowing such
825 // transactions into the mempool can be exploited as a DoS attack.
826 unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus());
827 if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata))
829 // If we're using promiscuousmempoolflags, we may hit this normally
830 // Check if current block has some flags that scriptVerifyFlags
831 // does not before printing an ominous warning
832 if (!(~scriptVerifyFlags & currentBlockScriptVerifyFlags)) {
833 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against latest-block but not STANDARD flags %s, %s",
834 __func__, hash.ToString(), FormatStateMessage(state));
835 } else {
836 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, false, txdata)) {
837 return error("%s: ConnectInputs failed against MANDATORY but not STANDARD flags due to promiscuous mempool %s, %s",
838 __func__, hash.ToString(), FormatStateMessage(state));
839 } else {
840 LogPrintf("Warning: -promiscuousmempool flags set to not include currently enforced soft forks, this may break mining or otherwise cause instability!\n");
845 // Remove conflicting transactions from the mempool
846 for (const CTxMemPool::txiter it : allConflicting)
848 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
849 it->GetTx().GetHash().ToString(),
850 hash.ToString(),
851 FormatMoney(nModifiedFees - nConflictingFees),
852 (int)nSize - (int)nConflictingSize);
853 if (plTxnReplaced)
854 plTxnReplaced->push_back(it->GetSharedTx());
856 pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
858 // This transaction should only count for fee estimation if it isn't a
859 // BIP 125 replacement transaction (may not be widely supported), the
860 // node is not behind, and the transaction is not dependent on any other
861 // transactions in the mempool.
862 bool validForFeeEstimation = !fReplacementTransaction && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
864 // Store transaction in memory
865 pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
867 // trim mempool and check if tx was trimmed
868 if (!fOverrideMempoolLimit) {
869 LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
870 if (!pool.exists(hash))
871 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
875 GetMainSignals().TransactionAddedToMempool(ptx);
877 return true;
880 /** (try to) add transaction to memory pool with a specified acceptance time **/
881 static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
882 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
883 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
885 std::vector<COutPoint> coins_to_uncache;
886 bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, coins_to_uncache);
887 if (!res) {
888 for (const COutPoint& hashTx : coins_to_uncache)
889 pcoinsTip->Uncache(hashTx);
891 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
892 CValidationState stateDummy;
893 FlushStateToDisk(chainparams, stateDummy, FLUSH_STATE_PERIODIC);
894 return res;
897 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
898 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
899 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
901 const CChainParams& chainparams = Params();
902 return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, fLimitFree, pfMissingInputs, GetTime(), plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee);
905 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
906 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
908 CBlockIndex *pindexSlow = nullptr;
910 LOCK(cs_main);
912 CTransactionRef ptx = mempool.get(hash);
913 if (ptx)
915 txOut = ptx;
916 return true;
919 if (fTxIndex) {
920 CDiskTxPos postx;
921 if (pblocktree->ReadTxIndex(hash, postx)) {
922 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
923 if (file.IsNull())
924 return error("%s: OpenBlockFile failed", __func__);
925 CBlockHeader header;
926 try {
927 file >> header;
928 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
929 file >> txOut;
930 } catch (const std::exception& e) {
931 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
933 hashBlock = header.GetHash();
934 if (txOut->GetHash() != hash)
935 return error("%s: txid mismatch", __func__);
936 return true;
940 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
941 const Coin& coin = AccessByTxid(*pcoinsTip, hash);
942 if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
945 if (pindexSlow) {
946 CBlock block;
947 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
948 for (const auto& tx : block.vtx) {
949 if (tx->GetHash() == hash) {
950 txOut = tx;
951 hashBlock = pindexSlow->GetBlockHash();
952 return true;
958 return false;
966 //////////////////////////////////////////////////////////////////////////////
968 // CBlock and CBlockIndex
971 static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
973 // Open history file to append
974 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
975 if (fileout.IsNull())
976 return error("WriteBlockToDisk: OpenBlockFile failed");
978 // Write index header
979 unsigned int nSize = GetSerializeSize(fileout, block);
980 fileout << FLATDATA(messageStart) << nSize;
982 // Write block
983 long fileOutPos = ftell(fileout.Get());
984 if (fileOutPos < 0)
985 return error("WriteBlockToDisk: ftell failed");
986 pos.nPos = (unsigned int)fileOutPos;
987 fileout << block;
989 return true;
992 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
994 block.SetNull();
996 // Open history file to read
997 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
998 if (filein.IsNull())
999 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1001 // Read block
1002 try {
1003 filein >> block;
1005 catch (const std::exception& e) {
1006 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1009 // Check the header
1010 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1011 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1013 return true;
1016 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1018 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1019 return false;
1020 if (block.GetHash() != pindex->GetBlockHash())
1021 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1022 pindex->ToString(), pindex->GetBlockPos().ToString());
1023 return true;
1026 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1028 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1029 // Force block reward to zero when right shift is undefined.
1030 if (halvings >= 64)
1031 return 0;
1033 CAmount nSubsidy = 50 * COIN;
1034 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1035 nSubsidy >>= halvings;
1036 return nSubsidy;
1039 bool IsInitialBlockDownload()
1041 // Once this function has returned false, it must remain false.
1042 static std::atomic<bool> latchToFalse{false};
1043 // Optimization: pre-test latch before taking the lock.
1044 if (latchToFalse.load(std::memory_order_relaxed))
1045 return false;
1047 LOCK(cs_main);
1048 if (latchToFalse.load(std::memory_order_relaxed))
1049 return false;
1050 if (fImporting || fReindex)
1051 return true;
1052 if (chainActive.Tip() == nullptr)
1053 return true;
1054 if (chainActive.Tip()->nChainWork < nMinimumChainWork)
1055 return true;
1056 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1057 return true;
1058 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1059 latchToFalse.store(true, std::memory_order_relaxed);
1060 return false;
1063 CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
1065 static void AlertNotify(const std::string& strMessage)
1067 uiInterface.NotifyAlertChanged();
1068 std::string strCmd = gArgs.GetArg("-alertnotify", "");
1069 if (strCmd.empty()) return;
1071 // Alert text should be plain ascii coming from a trusted source, but to
1072 // be safe we first strip anything not in safeChars, then add single quotes around
1073 // the whole string before passing it to the shell:
1074 std::string singleQuote("'");
1075 std::string safeStatus = SanitizeString(strMessage);
1076 safeStatus = singleQuote+safeStatus+singleQuote;
1077 boost::replace_all(strCmd, "%s", safeStatus);
1079 boost::thread t(runCommand, strCmd); // thread runs free
1082 static void CheckForkWarningConditions()
1084 AssertLockHeld(cs_main);
1085 // Before we get past initial download, we cannot reliably alert about forks
1086 // (we assume we don't get stuck on a fork before finishing our initial sync)
1087 if (IsInitialBlockDownload())
1088 return;
1090 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1091 // of our head, drop it
1092 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1093 pindexBestForkTip = nullptr;
1095 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1097 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
1099 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1100 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1101 AlertNotify(warning);
1103 if (pindexBestForkTip && pindexBestForkBase)
1105 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__,
1106 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1107 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1108 SetfLargeWorkForkFound(true);
1110 else
1112 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1113 SetfLargeWorkInvalidChainFound(true);
1116 else
1118 SetfLargeWorkForkFound(false);
1119 SetfLargeWorkInvalidChainFound(false);
1123 static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1125 AssertLockHeld(cs_main);
1126 // If we are on a fork that is sufficiently large, set a warning flag
1127 CBlockIndex* pfork = pindexNewForkTip;
1128 CBlockIndex* plonger = chainActive.Tip();
1129 while (pfork && pfork != plonger)
1131 while (plonger && plonger->nHeight > pfork->nHeight)
1132 plonger = plonger->pprev;
1133 if (pfork == plonger)
1134 break;
1135 pfork = pfork->pprev;
1138 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1139 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1140 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1141 // hash rate operating on the fork.
1142 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1143 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1144 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1145 if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
1146 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1147 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1149 pindexBestForkTip = pindexNewForkTip;
1150 pindexBestForkBase = pfork;
1153 CheckForkWarningConditions();
1156 void static InvalidChainFound(CBlockIndex* pindexNew)
1158 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1159 pindexBestInvalid = pindexNew;
1161 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1162 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1163 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1164 pindexNew->GetBlockTime()));
1165 CBlockIndex *tip = chainActive.Tip();
1166 assert (tip);
1167 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1168 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1169 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1170 CheckForkWarningConditions();
1173 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1174 if (!state.CorruptionPossible()) {
1175 pindex->nStatus |= BLOCK_FAILED_VALID;
1176 setDirtyBlockIndex.insert(pindex);
1177 setBlockIndexCandidates.erase(pindex);
1178 InvalidChainFound(pindex);
1182 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1184 // mark inputs spent
1185 if (!tx.IsCoinBase()) {
1186 txundo.vprevout.reserve(tx.vin.size());
1187 for (const CTxIn &txin : tx.vin) {
1188 txundo.vprevout.emplace_back();
1189 bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1190 assert(is_spent);
1193 // add outputs
1194 AddCoins(inputs, tx, nHeight);
1197 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1199 CTxUndo txundo;
1200 UpdateCoins(tx, inputs, txundo, nHeight);
1203 bool CScriptCheck::operator()() {
1204 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1205 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1206 return VerifyScript(scriptSig, scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), &error);
1209 int GetSpendHeight(const CCoinsViewCache& inputs)
1211 LOCK(cs_main);
1212 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1213 return pindexPrev->nHeight + 1;
1217 static CuckooCache::cache<uint256, SignatureCacheHasher> scriptExecutionCache;
1218 static uint256 scriptExecutionCacheNonce(GetRandHash());
1220 void InitScriptExecutionCache() {
1221 // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1222 // setup_bytes creates the minimum possible cache (2 elements).
1223 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);
1224 size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
1225 LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1226 (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1230 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
1231 * This does not modify the UTXO set.
1233 * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
1234 * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
1235 * not pushed onto pvChecks/run.
1237 * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
1238 * which are matched. This is useful for checking blocks where we will likely never need the cache
1239 * entry again.
1241 * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
1243 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)
1245 if (!tx.IsCoinBase())
1247 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1248 return false;
1250 if (pvChecks)
1251 pvChecks->reserve(tx.vin.size());
1253 // The first loop above does all the inexpensive checks.
1254 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1255 // Helps prevent CPU exhaustion attacks.
1257 // Skip script verification when connecting blocks under the
1258 // assumevalid block. Assuming the assumevalid block is valid this
1259 // is safe because block merkle hashes are still computed and checked,
1260 // Of course, if an assumed valid block is invalid due to false scriptSigs
1261 // this optimization would allow an invalid chain to be accepted.
1262 if (fScriptChecks) {
1263 // First check if script executions have been cached with the same
1264 // flags. Note that this assumes that the inputs provided are
1265 // correct (ie that the transaction hash which is in tx's prevouts
1266 // properly commits to the scriptPubKey in the inputs view of that
1267 // transaction).
1268 uint256 hashCacheEntry;
1269 // We only use the first 19 bytes of nonce to avoid a second SHA
1270 // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
1271 static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
1272 CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1273 AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1274 if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1275 return true;
1278 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1279 const COutPoint &prevout = tx.vin[i].prevout;
1280 const Coin& coin = inputs.AccessCoin(prevout);
1281 assert(!coin.IsSpent());
1283 // We very carefully only pass in things to CScriptCheck which
1284 // are clearly committed to by tx' witness hash. This provides
1285 // a sanity check that our caching is not introducing consensus
1286 // failures through additional data in, eg, the coins being
1287 // spent being checked as a part of CScriptCheck.
1288 const CScript& scriptPubKey = coin.out.scriptPubKey;
1289 const CAmount amount = coin.out.nValue;
1291 // Verify signature
1292 CScriptCheck check(scriptPubKey, amount, tx, i, flags, cacheSigStore, &txdata);
1293 if (pvChecks) {
1294 pvChecks->push_back(CScriptCheck());
1295 check.swap(pvChecks->back());
1296 } else if (!check()) {
1297 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1298 // Check whether the failure was caused by a
1299 // non-mandatory script verification check, such as
1300 // non-standard DER encodings or non-null dummy
1301 // arguments; if so, don't trigger DoS protection to
1302 // avoid splitting the network between upgraded and
1303 // non-upgraded nodes.
1304 CScriptCheck check2(scriptPubKey, amount, tx, i,
1305 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1306 if (check2())
1307 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1309 // Failures of other flags indicate a transaction that is
1310 // invalid in new blocks, e.g. an invalid P2SH. We DoS ban
1311 // such nodes as they are not following the protocol. That
1312 // said during an upgrade careful thought should be taken
1313 // as to the correct behavior - we may want to continue
1314 // peering with non-upgraded nodes even after soft-fork
1315 // super-majority signaling has occurred.
1316 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1320 if (cacheFullScriptStore && !pvChecks) {
1321 // We executed all of the provided scripts, and were told to
1322 // cache the result. Do so now.
1323 scriptExecutionCache.insert(hashCacheEntry);
1328 return true;
1331 namespace {
1333 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1335 // Open history file to append
1336 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1337 if (fileout.IsNull())
1338 return error("%s: OpenUndoFile failed", __func__);
1340 // Write index header
1341 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1342 fileout << FLATDATA(messageStart) << nSize;
1344 // Write undo data
1345 long fileOutPos = ftell(fileout.Get());
1346 if (fileOutPos < 0)
1347 return error("%s: ftell failed", __func__);
1348 pos.nPos = (unsigned int)fileOutPos;
1349 fileout << blockundo;
1351 // calculate & write checksum
1352 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1353 hasher << hashBlock;
1354 hasher << blockundo;
1355 fileout << hasher.GetHash();
1357 return true;
1360 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1362 // Open history file to read
1363 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1364 if (filein.IsNull())
1365 return error("%s: OpenUndoFile failed", __func__);
1367 // Read block
1368 uint256 hashChecksum;
1369 CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1370 try {
1371 verifier << hashBlock;
1372 verifier >> blockundo;
1373 filein >> hashChecksum;
1375 catch (const std::exception& e) {
1376 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1379 // Verify checksum
1380 if (hashChecksum != verifier.GetHash())
1381 return error("%s: Checksum mismatch", __func__);
1383 return true;
1386 /** Abort with a message */
1387 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1389 SetMiscWarning(strMessage);
1390 LogPrintf("*** %s\n", strMessage);
1391 uiInterface.ThreadSafeMessageBox(
1392 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1393 "", CClientUIInterface::MSG_ERROR);
1394 StartShutdown();
1395 return false;
1398 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1400 AbortNode(strMessage, userMessage);
1401 return state.Error(strMessage);
1404 } // namespace
1406 enum DisconnectResult
1408 DISCONNECT_OK, // All good.
1409 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
1410 DISCONNECT_FAILED // Something else went wrong.
1414 * Restore the UTXO in a Coin at a given COutPoint
1415 * @param undo The Coin to be restored.
1416 * @param view The coins view to which to apply the changes.
1417 * @param out The out point that corresponds to the tx input.
1418 * @return A DisconnectResult as an int
1420 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1422 bool fClean = true;
1424 if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1426 if (undo.nHeight == 0) {
1427 // Missing undo metadata (height and coinbase). Older versions included this
1428 // information only in undo records for the last spend of a transactions'
1429 // outputs. This implies that it must be present for some other output of the same tx.
1430 const Coin& alternate = AccessByTxid(view, out.hash);
1431 if (!alternate.IsSpent()) {
1432 undo.nHeight = alternate.nHeight;
1433 undo.fCoinBase = alternate.fCoinBase;
1434 } else {
1435 return DISCONNECT_FAILED; // adding output for transaction without known metadata
1438 // The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
1439 // sure that the coin did not already exist in the cache. As we have queried for that above
1440 // using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
1441 // it is an overwrite.
1442 view.AddCoin(out, std::move(undo), !fClean);
1444 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1447 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1448 * When FAILED is returned, view is left in an indeterminate state. */
1449 static DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1451 bool fClean = true;
1453 CBlockUndo blockUndo;
1454 CDiskBlockPos pos = pindex->GetUndoPos();
1455 if (pos.IsNull()) {
1456 error("DisconnectBlock(): no undo data available");
1457 return DISCONNECT_FAILED;
1459 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) {
1460 error("DisconnectBlock(): failure reading undo data");
1461 return DISCONNECT_FAILED;
1464 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1465 error("DisconnectBlock(): block and undo data inconsistent");
1466 return DISCONNECT_FAILED;
1469 // undo transactions in reverse order
1470 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1471 const CTransaction &tx = *(block.vtx[i]);
1472 uint256 hash = tx.GetHash();
1473 bool is_coinbase = tx.IsCoinBase();
1475 // Check that all outputs are available and match the outputs in the block itself
1476 // exactly.
1477 for (size_t o = 0; o < tx.vout.size(); o++) {
1478 if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1479 COutPoint out(hash, o);
1480 Coin coin;
1481 bool is_spent = view.SpendCoin(out, &coin);
1482 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1483 fClean = false; // transaction output mismatch
1488 // restore inputs
1489 if (i > 0) { // not coinbases
1490 CTxUndo &txundo = blockUndo.vtxundo[i-1];
1491 if (txundo.vprevout.size() != tx.vin.size()) {
1492 error("DisconnectBlock(): transaction and undo data inconsistent");
1493 return DISCONNECT_FAILED;
1495 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1496 const COutPoint &out = tx.vin[j].prevout;
1497 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1498 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1499 fClean = fClean && res != DISCONNECT_UNCLEAN;
1501 // At this point, all of txundo.vprevout should have been moved out.
1505 // move best block pointer to prevout block
1506 view.SetBestBlock(pindex->pprev->GetBlockHash());
1508 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1511 void static FlushBlockFile(bool fFinalize = false)
1513 LOCK(cs_LastBlockFile);
1515 CDiskBlockPos posOld(nLastBlockFile, 0);
1517 FILE *fileOld = OpenBlockFile(posOld);
1518 if (fileOld) {
1519 if (fFinalize)
1520 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1521 FileCommit(fileOld);
1522 fclose(fileOld);
1525 fileOld = OpenUndoFile(posOld);
1526 if (fileOld) {
1527 if (fFinalize)
1528 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1529 FileCommit(fileOld);
1530 fclose(fileOld);
1534 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1536 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1538 void ThreadScriptCheck() {
1539 RenameThread("bitcoin-scriptch");
1540 scriptcheckqueue.Thread();
1543 // Protected by cs_main
1544 VersionBitsCache versionbitscache;
1546 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1548 LOCK(cs_main);
1549 int32_t nVersion = VERSIONBITS_TOP_BITS;
1551 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1552 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1553 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1554 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1558 return nVersion;
1562 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1564 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1566 private:
1567 int bit;
1569 public:
1570 explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1572 int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1573 int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1574 int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1575 int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1577 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1579 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1580 ((pindex->nVersion >> bit) & 1) != 0 &&
1581 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1585 // Protected by cs_main
1586 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1588 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) {
1589 AssertLockHeld(cs_main);
1591 // BIP16 didn't become active until Apr 1 2012
1592 int64_t nBIP16SwitchTime = 1333238400;
1593 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1595 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1597 // Start enforcing the DERSIG (BIP66) rule
1598 if (pindex->nHeight >= consensusparams.BIP66Height) {
1599 flags |= SCRIPT_VERIFY_DERSIG;
1602 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1603 if (pindex->nHeight >= consensusparams.BIP65Height) {
1604 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1607 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1608 if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1609 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1612 // Start enforcing WITNESS rules using versionbits logic.
1613 if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
1614 flags |= SCRIPT_VERIFY_WITNESS;
1615 flags |= SCRIPT_VERIFY_NULLDUMMY;
1618 return flags;
1623 static int64_t nTimeCheck = 0;
1624 static int64_t nTimeForks = 0;
1625 static int64_t nTimeVerify = 0;
1626 static int64_t nTimeConnect = 0;
1627 static int64_t nTimeIndex = 0;
1628 static int64_t nTimeCallbacks = 0;
1629 static int64_t nTimeTotal = 0;
1630 static int64_t nBlocksTotal = 0;
1632 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1633 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1634 * can fail if those validity checks fail (among other reasons). */
1635 static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1636 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false)
1638 AssertLockHeld(cs_main);
1639 assert(pindex);
1640 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1641 assert((pindex->phashBlock == nullptr) ||
1642 (*pindex->phashBlock == block.GetHash()));
1643 int64_t nTimeStart = GetTimeMicros();
1645 // Check it again in case a previous version let a bad block in
1646 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1647 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1649 // verify that the view's current state corresponds to the previous block
1650 uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
1651 assert(hashPrevBlock == view.GetBestBlock());
1653 // Special case for the genesis block, skipping connection of its transactions
1654 // (its coinbase is unspendable)
1655 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1656 if (!fJustCheck)
1657 view.SetBestBlock(pindex->GetBlockHash());
1658 return true;
1661 nBlocksTotal++;
1663 bool fScriptChecks = true;
1664 if (!hashAssumeValid.IsNull()) {
1665 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1666 // A suitable default value is included with the software and updated from time to time. Because validity
1667 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1668 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1669 // effectively caching the result of part of the verification.
1670 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1671 if (it != mapBlockIndex.end()) {
1672 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1673 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1674 pindexBestHeader->nChainWork >= nMinimumChainWork) {
1675 // This block is a member of the assumed verified chain and an ancestor of the best header.
1676 // The equivalent time check discourages hash power from extorting the network via DOS attack
1677 // into accepting an invalid block through telling users they must manually set assumevalid.
1678 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1679 // it hard to hide the implication of the demand. This also avoids having release candidates
1680 // that are hardly doing any signature verification at all in testing without having to
1681 // artificially set the default assumed verified block further back.
1682 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1683 // least as good as the expected chain.
1684 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1689 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1690 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
1692 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1693 // unless those are already completely spent.
1694 // If such overwrites are allowed, coinbases and transactions depending upon those
1695 // can be duplicated to remove the ability to spend the first instance -- even after
1696 // being sent to another address.
1697 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1698 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1699 // already refuses previously-known transaction ids entirely.
1700 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1701 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1702 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1703 // initial block download.
1704 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1705 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1706 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1708 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1709 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1710 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1711 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1712 // duplicate transactions descending from the known pairs either.
1713 // 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.
1714 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1715 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1716 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1718 if (fEnforceBIP30) {
1719 for (const auto& tx : block.vtx) {
1720 for (size_t o = 0; o < tx->vout.size(); o++) {
1721 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
1722 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1723 REJECT_INVALID, "bad-txns-BIP30");
1729 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1730 int nLockTimeFlags = 0;
1731 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1732 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1735 // Get the script flags for this block
1736 unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
1738 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1739 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
1741 CBlockUndo blockundo;
1743 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
1745 std::vector<int> prevheights;
1746 CAmount nFees = 0;
1747 int nInputs = 0;
1748 int64_t nSigOpsCost = 0;
1749 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1750 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1751 vPos.reserve(block.vtx.size());
1752 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1753 std::vector<PrecomputedTransactionData> txdata;
1754 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1755 for (unsigned int i = 0; i < block.vtx.size(); i++)
1757 const CTransaction &tx = *(block.vtx[i]);
1759 nInputs += tx.vin.size();
1761 if (!tx.IsCoinBase())
1763 if (!view.HaveInputs(tx))
1764 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1765 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1767 // Check that transaction is BIP68 final
1768 // BIP68 lock checks (as opposed to nLockTime checks) must
1769 // be in ConnectBlock because they require the UTXO set
1770 prevheights.resize(tx.vin.size());
1771 for (size_t j = 0; j < tx.vin.size(); j++) {
1772 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
1775 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1776 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1777 REJECT_INVALID, "bad-txns-nonfinal");
1781 // GetTransactionSigOpCost counts 3 types of sigops:
1782 // * legacy (always)
1783 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1784 // * witness (when witness enabled in flags and excludes coinbase)
1785 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1786 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1787 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1788 REJECT_INVALID, "bad-blk-sigops");
1790 txdata.emplace_back(tx);
1791 if (!tx.IsCoinBase())
1793 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1795 std::vector<CScriptCheck> vChecks;
1796 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1797 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr))
1798 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1799 tx.GetHash().ToString(), FormatStateMessage(state));
1800 control.Add(vChecks);
1803 CTxUndo undoDummy;
1804 if (i > 0) {
1805 blockundo.vtxundo.push_back(CTxUndo());
1807 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1809 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1810 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1812 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1813 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);
1815 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1816 if (block.vtx[0]->GetValueOut() > blockReward)
1817 return state.DoS(100,
1818 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1819 block.vtx[0]->GetValueOut(), blockReward),
1820 REJECT_INVALID, "bad-cb-amount");
1822 if (!control.Wait())
1823 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1824 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1825 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);
1827 if (fJustCheck)
1828 return true;
1830 // Write undo information to disk
1831 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1833 if (pindex->GetUndoPos().IsNull()) {
1834 CDiskBlockPos _pos;
1835 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1836 return error("ConnectBlock(): FindUndoPos failed");
1837 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1838 return AbortNode(state, "Failed to write undo data");
1840 // update nUndoPos in block index
1841 pindex->nUndoPos = _pos.nPos;
1842 pindex->nStatus |= BLOCK_HAVE_UNDO;
1845 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1846 setDirtyBlockIndex.insert(pindex);
1849 if (fTxIndex)
1850 if (!pblocktree->WriteTxIndex(vPos))
1851 return AbortNode(state, "Failed to write transaction index");
1853 // add this block to the view's block chain
1854 view.SetBestBlock(pindex->GetBlockHash());
1856 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1857 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
1859 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1860 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
1862 return true;
1866 * Update the on-disk chain state.
1867 * The caches and indexes are flushed depending on the mode we're called with
1868 * if they're too large, if it's been a while since the last write,
1869 * or always and in all cases if we're in prune mode and are deleting files.
1871 bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
1872 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
1873 LOCK(cs_main);
1874 static int64_t nLastWrite = 0;
1875 static int64_t nLastFlush = 0;
1876 static int64_t nLastSetChain = 0;
1877 std::set<int> setFilesToPrune;
1878 bool fFlushForPrune = false;
1879 bool fDoFullFlush = false;
1880 int64_t nNow = 0;
1881 try {
1883 LOCK(cs_LastBlockFile);
1884 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1885 if (nManualPruneHeight > 0) {
1886 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
1887 } else {
1888 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1889 fCheckForPruning = false;
1891 if (!setFilesToPrune.empty()) {
1892 fFlushForPrune = true;
1893 if (!fHavePruned) {
1894 pblocktree->WriteFlag("prunedblockfiles", true);
1895 fHavePruned = true;
1899 nNow = GetTimeMicros();
1900 // Avoid writing/flushing immediately after startup.
1901 if (nLastWrite == 0) {
1902 nLastWrite = nNow;
1904 if (nLastFlush == 0) {
1905 nLastFlush = nNow;
1907 if (nLastSetChain == 0) {
1908 nLastSetChain = nNow;
1910 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1911 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1912 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
1913 // 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).
1914 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
1915 // The cache is over the limit, we have to write now.
1916 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
1917 // 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.
1918 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1919 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1920 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1921 // Combine all conditions that result in a full cache flush.
1922 fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1923 // Write blocks and block index to disk.
1924 if (fDoFullFlush || fPeriodicWrite) {
1925 // Depend on nMinDiskSpace to ensure we can write block index
1926 if (!CheckDiskSpace(0))
1927 return state.Error("out of disk space");
1928 // First make sure all block and undo data is flushed to disk.
1929 FlushBlockFile();
1930 // Then update all block file information (which may refer to block and undo files).
1932 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1933 vFiles.reserve(setDirtyFileInfo.size());
1934 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1935 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
1936 setDirtyFileInfo.erase(it++);
1938 std::vector<const CBlockIndex*> vBlocks;
1939 vBlocks.reserve(setDirtyBlockIndex.size());
1940 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1941 vBlocks.push_back(*it);
1942 setDirtyBlockIndex.erase(it++);
1944 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1945 return AbortNode(state, "Failed to write to block index database");
1948 // Finally remove any pruned files
1949 if (fFlushForPrune)
1950 UnlinkPrunedFiles(setFilesToPrune);
1951 nLastWrite = nNow;
1953 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1954 if (fDoFullFlush) {
1955 // Typical Coin structures on disk are around 48 bytes in size.
1956 // Pushing a new one to the database can cause it to be written
1957 // twice (once in the log, and once in the tables). This is already
1958 // an overestimation, as most will delete an existing entry or
1959 // overwrite one. Still, use a conservative safety factor of 2.
1960 if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
1961 return state.Error("out of disk space");
1962 // Flush the chainstate (which may refer to block index entries).
1963 if (!pcoinsTip->Flush())
1964 return AbortNode(state, "Failed to write to coin database");
1965 nLastFlush = nNow;
1968 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
1969 // Update best block in wallet (so we can detect restored wallets).
1970 GetMainSignals().SetBestChain(chainActive.GetLocator());
1971 nLastSetChain = nNow;
1973 } catch (const std::runtime_error& e) {
1974 return AbortNode(state, std::string("System error while flushing: ") + e.what());
1976 return true;
1979 void FlushStateToDisk() {
1980 CValidationState state;
1981 const CChainParams& chainparams = Params();
1982 FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
1985 void PruneAndFlush() {
1986 CValidationState state;
1987 fCheckForPruning = true;
1988 const CChainParams& chainparams = Params();
1989 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
1992 static void DoWarning(const std::string& strWarning)
1994 static bool fWarned = false;
1995 SetMiscWarning(strWarning);
1996 if (!fWarned) {
1997 AlertNotify(strWarning);
1998 fWarned = true;
2002 /** Update chainActive and related internal data structures. */
2003 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
2004 chainActive.SetTip(pindexNew);
2006 // New best block
2007 mempool.AddTransactionsUpdated(1);
2009 cvBlockChange.notify_all();
2011 std::vector<std::string> warningMessages;
2012 if (!IsInitialBlockDownload())
2014 int nUpgraded = 0;
2015 const CBlockIndex* pindex = chainActive.Tip();
2016 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2017 WarningBitsConditionChecker checker(bit);
2018 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2019 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2020 const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2021 if (state == THRESHOLD_ACTIVE) {
2022 DoWarning(strWarning);
2023 } else {
2024 warningMessages.push_back(strWarning);
2028 // Check the version of the last 100 blocks to see if we need to upgrade:
2029 for (int i = 0; i < 100 && pindex != nullptr; i++)
2031 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2032 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2033 ++nUpgraded;
2034 pindex = pindex->pprev;
2036 if (nUpgraded > 0)
2037 warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
2038 if (nUpgraded > 100/2)
2040 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2041 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2042 DoWarning(strWarning);
2045 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
2046 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
2047 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2048 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2049 GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2050 if (!warningMessages.empty())
2051 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2052 LogPrintf("\n");
2056 /** Disconnect chainActive's tip.
2057 * After calling, the mempool will be in an inconsistent state, with
2058 * transactions from disconnected blocks being added to disconnectpool. You
2059 * should make the mempool consistent again by calling UpdateMempoolForReorg.
2060 * with cs_main held.
2062 * If disconnectpool is nullptr, then no disconnected transactions are added to
2063 * disconnectpool (note that the caller is responsible for mempool consistency
2064 * in any case).
2066 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
2068 CBlockIndex *pindexDelete = chainActive.Tip();
2069 assert(pindexDelete);
2070 // Read block from disk.
2071 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2072 CBlock& block = *pblock;
2073 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2074 return AbortNode(state, "Failed to read block");
2075 // Apply the block atomically to the chain state.
2076 int64_t nStart = GetTimeMicros();
2078 CCoinsViewCache view(pcoinsTip);
2079 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2080 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2081 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2082 bool flushed = view.Flush();
2083 assert(flushed);
2085 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
2086 // Write the chain state to disk, if necessary.
2087 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2088 return false;
2090 if (disconnectpool) {
2091 // Save transactions to re-add to mempool at end of reorg
2092 for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2093 disconnectpool->addTransaction(*it);
2095 while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2096 // Drop the earliest entry, and remove its children from the mempool.
2097 auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2098 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
2099 disconnectpool->removeEntry(it);
2103 // Update chainActive and related variables.
2104 UpdateTip(pindexDelete->pprev, chainparams);
2105 // Let wallets know transactions went from 1-confirmed to
2106 // 0-confirmed or conflicted:
2107 GetMainSignals().BlockDisconnected(pblock);
2108 return true;
2111 static int64_t nTimeReadFromDisk = 0;
2112 static int64_t nTimeConnectTotal = 0;
2113 static int64_t nTimeFlush = 0;
2114 static int64_t nTimeChainState = 0;
2115 static int64_t nTimePostConnect = 0;
2117 struct PerBlockConnectTrace {
2118 CBlockIndex* pindex = nullptr;
2119 std::shared_ptr<const CBlock> pblock;
2120 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
2121 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
2124 * Used to track blocks whose transactions were applied to the UTXO state as a
2125 * part of a single ActivateBestChainStep call.
2127 * This class also tracks transactions that are removed from the mempool as
2128 * conflicts (per block) and can be used to pass all those transactions
2129 * through SyncTransaction.
2131 * This class assumes (and asserts) that the conflicted transactions for a given
2132 * block are added via mempool callbacks prior to the BlockConnected() associated
2133 * with those transactions. If any transactions are marked conflicted, it is
2134 * assumed that an associated block will always be added.
2136 * This class is single-use, once you call GetBlocksConnected() you have to throw
2137 * it away and make a new one.
2139 class ConnectTrace {
2140 private:
2141 std::vector<PerBlockConnectTrace> blocksConnected;
2142 CTxMemPool &pool;
2144 public:
2145 explicit ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
2146 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2149 ~ConnectTrace() {
2150 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2153 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2154 assert(!blocksConnected.back().pindex);
2155 assert(pindex);
2156 assert(pblock);
2157 blocksConnected.back().pindex = pindex;
2158 blocksConnected.back().pblock = std::move(pblock);
2159 blocksConnected.emplace_back();
2162 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2163 // We always keep one extra block at the end of our list because
2164 // blocks are added after all the conflicted transactions have
2165 // been filled in. Thus, the last entry should always be an empty
2166 // one waiting for the transactions from the next block. We pop
2167 // the last entry here to make sure the list we return is sane.
2168 assert(!blocksConnected.back().pindex);
2169 assert(blocksConnected.back().conflictedTxs->empty());
2170 blocksConnected.pop_back();
2171 return blocksConnected;
2174 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
2175 assert(!blocksConnected.back().pindex);
2176 if (reason == MemPoolRemovalReason::CONFLICT) {
2177 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2183 * Connect a new block to chainActive. pblock is either nullptr or a pointer to a CBlock
2184 * corresponding to pindexNew, to bypass loading it again from disk.
2186 * The block is added to connectTrace if connection succeeds.
2188 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
2190 assert(pindexNew->pprev == chainActive.Tip());
2191 // Read block from disk.
2192 int64_t nTime1 = GetTimeMicros();
2193 std::shared_ptr<const CBlock> pthisBlock;
2194 if (!pblock) {
2195 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2196 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2197 return AbortNode(state, "Failed to read block");
2198 pthisBlock = pblockNew;
2199 } else {
2200 pthisBlock = pblock;
2202 const CBlock& blockConnecting = *pthisBlock;
2203 // Apply the block atomically to the chain state.
2204 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2205 int64_t nTime3;
2206 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
2208 CCoinsViewCache view(pcoinsTip);
2209 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2210 GetMainSignals().BlockChecked(blockConnecting, state);
2211 if (!rv) {
2212 if (state.IsInvalid())
2213 InvalidBlockFound(pindexNew, state);
2214 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2216 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2217 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
2218 bool flushed = view.Flush();
2219 assert(flushed);
2221 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2222 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
2223 // Write the chain state to disk, if necessary.
2224 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2225 return false;
2226 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2227 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
2228 // Remove conflicting transactions from the mempool.;
2229 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2230 disconnectpool.removeForBlock(blockConnecting.vtx);
2231 // Update chainActive & related variables.
2232 UpdateTip(pindexNew, chainparams);
2234 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2235 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
2236 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
2238 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2239 return true;
2243 * Return the tip of the chain with the most work in it, that isn't
2244 * known to be invalid (it's however far from certain to be valid).
2246 static CBlockIndex* FindMostWorkChain() {
2247 do {
2248 CBlockIndex *pindexNew = nullptr;
2250 // Find the best candidate header.
2252 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2253 if (it == setBlockIndexCandidates.rend())
2254 return nullptr;
2255 pindexNew = *it;
2258 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2259 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2260 CBlockIndex *pindexTest = pindexNew;
2261 bool fInvalidAncestor = false;
2262 while (pindexTest && !chainActive.Contains(pindexTest)) {
2263 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2265 // Pruned nodes may have entries in setBlockIndexCandidates for
2266 // which block files have been deleted. Remove those as candidates
2267 // for the most work chain if we come across them; we can't switch
2268 // to a chain unless we have all the non-active-chain parent blocks.
2269 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2270 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2271 if (fFailedChain || fMissingData) {
2272 // Candidate chain is not usable (either invalid or missing data)
2273 if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2274 pindexBestInvalid = pindexNew;
2275 CBlockIndex *pindexFailed = pindexNew;
2276 // Remove the entire chain from the set.
2277 while (pindexTest != pindexFailed) {
2278 if (fFailedChain) {
2279 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2280 } else if (fMissingData) {
2281 // If we're missing data, then add back to mapBlocksUnlinked,
2282 // so that if the block arrives in the future we can try adding
2283 // to setBlockIndexCandidates again.
2284 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2286 setBlockIndexCandidates.erase(pindexFailed);
2287 pindexFailed = pindexFailed->pprev;
2289 setBlockIndexCandidates.erase(pindexTest);
2290 fInvalidAncestor = true;
2291 break;
2293 pindexTest = pindexTest->pprev;
2295 if (!fInvalidAncestor)
2296 return pindexNew;
2297 } while(true);
2300 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2301 static void PruneBlockIndexCandidates() {
2302 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2303 // reorganization to a better block fails.
2304 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2305 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2306 setBlockIndexCandidates.erase(it++);
2308 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2309 assert(!setBlockIndexCandidates.empty());
2313 * Try to make some progress towards making pindexMostWork the active block.
2314 * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
2316 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2318 AssertLockHeld(cs_main);
2319 const CBlockIndex *pindexOldTip = chainActive.Tip();
2320 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2322 // Disconnect active blocks which are no longer in the best chain.
2323 bool fBlocksDisconnected = false;
2324 DisconnectedBlockTransactions disconnectpool;
2325 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2326 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2327 // This is likely a fatal error, but keep the mempool consistent,
2328 // just in case. Only remove from the mempool in this case.
2329 UpdateMempoolForReorg(disconnectpool, false);
2330 return false;
2332 fBlocksDisconnected = true;
2335 // Build list of new blocks to connect.
2336 std::vector<CBlockIndex*> vpindexToConnect;
2337 bool fContinue = true;
2338 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2339 while (fContinue && nHeight != pindexMostWork->nHeight) {
2340 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2341 // a few blocks along the way.
2342 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2343 vpindexToConnect.clear();
2344 vpindexToConnect.reserve(nTargetHeight - nHeight);
2345 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2346 while (pindexIter && pindexIter->nHeight != nHeight) {
2347 vpindexToConnect.push_back(pindexIter);
2348 pindexIter = pindexIter->pprev;
2350 nHeight = nTargetHeight;
2352 // Connect new blocks.
2353 for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
2354 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2355 if (state.IsInvalid()) {
2356 // The block violates a consensus rule.
2357 if (!state.CorruptionPossible())
2358 InvalidChainFound(vpindexToConnect.back());
2359 state = CValidationState();
2360 fInvalidFound = true;
2361 fContinue = false;
2362 break;
2363 } else {
2364 // A system error occurred (disk space, database error, ...).
2365 // Make the mempool consistent with the current tip, just in case
2366 // any observers try to use it before shutdown.
2367 UpdateMempoolForReorg(disconnectpool, false);
2368 return false;
2370 } else {
2371 PruneBlockIndexCandidates();
2372 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2373 // We're in a better position than we were. Return temporarily to release the lock.
2374 fContinue = false;
2375 break;
2381 if (fBlocksDisconnected) {
2382 // If any blocks were disconnected, disconnectpool may be non empty. Add
2383 // any disconnected transactions back to the mempool.
2384 UpdateMempoolForReorg(disconnectpool, true);
2386 mempool.check(pcoinsTip);
2388 // Callbacks/notifications for a new best chain.
2389 if (fInvalidFound)
2390 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2391 else
2392 CheckForkWarningConditions();
2394 return true;
2397 static void NotifyHeaderTip() {
2398 bool fNotify = false;
2399 bool fInitialBlockDownload = false;
2400 static CBlockIndex* pindexHeaderOld = nullptr;
2401 CBlockIndex* pindexHeader = nullptr;
2403 LOCK(cs_main);
2404 pindexHeader = pindexBestHeader;
2406 if (pindexHeader != pindexHeaderOld) {
2407 fNotify = true;
2408 fInitialBlockDownload = IsInitialBlockDownload();
2409 pindexHeaderOld = pindexHeader;
2412 // Send block tip changed notifications without cs_main
2413 if (fNotify) {
2414 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2419 * Make the best chain active, in multiple steps. The result is either failure
2420 * or an activated best chain. pblock is either nullptr or a pointer to a block
2421 * that is already loaded (to avoid loading it again from disk).
2423 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2424 // Note that while we're often called here from ProcessNewBlock, this is
2425 // far from a guarantee. Things in the P2P/RPC will often end up calling
2426 // us in the middle of ProcessNewBlock - do not assume pblock is set
2427 // sanely for performance or correctness!
2429 CBlockIndex *pindexMostWork = nullptr;
2430 CBlockIndex *pindexNewTip = nullptr;
2431 int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2432 do {
2433 boost::this_thread::interruption_point();
2434 if (ShutdownRequested())
2435 break;
2437 const CBlockIndex *pindexFork;
2438 bool fInitialDownload;
2440 LOCK(cs_main);
2441 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2443 CBlockIndex *pindexOldTip = chainActive.Tip();
2444 if (pindexMostWork == nullptr) {
2445 pindexMostWork = FindMostWorkChain();
2448 // Whether we have anything to do at all.
2449 if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip())
2450 return true;
2452 bool fInvalidFound = false;
2453 std::shared_ptr<const CBlock> nullBlockPtr;
2454 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2455 return false;
2457 if (fInvalidFound) {
2458 // Wipe cache, we may need another branch now.
2459 pindexMostWork = nullptr;
2461 pindexNewTip = chainActive.Tip();
2462 pindexFork = chainActive.FindFork(pindexOldTip);
2463 fInitialDownload = IsInitialBlockDownload();
2465 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2466 assert(trace.pblock && trace.pindex);
2467 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, *trace.conflictedTxs);
2470 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2472 // Notifications/callbacks that can run without cs_main
2474 // Notify external listeners about the new tip.
2475 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2477 // Always notify the UI if a new block tip was connected
2478 if (pindexFork != pindexNewTip) {
2479 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2482 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2483 } while (pindexNewTip != pindexMostWork);
2484 CheckBlockIndex(chainparams.GetConsensus());
2486 // Write changes periodically to disk, after relay.
2487 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
2488 return false;
2491 return true;
2495 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2498 LOCK(cs_main);
2499 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2500 // Nothing to do, this block is not at the tip.
2501 return true;
2503 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2504 // The chain has been extended since the last call, reset the counter.
2505 nBlockReverseSequenceId = -1;
2507 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2508 setBlockIndexCandidates.erase(pindex);
2509 pindex->nSequenceId = nBlockReverseSequenceId;
2510 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2511 // We can't keep reducing the counter if somebody really wants to
2512 // call preciousblock 2**31-1 times on the same set of tips...
2513 nBlockReverseSequenceId--;
2515 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2516 setBlockIndexCandidates.insert(pindex);
2517 PruneBlockIndexCandidates();
2521 return ActivateBestChain(state, params);
2524 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2526 AssertLockHeld(cs_main);
2528 // Mark the block itself as invalid.
2529 pindex->nStatus |= BLOCK_FAILED_VALID;
2530 setDirtyBlockIndex.insert(pindex);
2531 setBlockIndexCandidates.erase(pindex);
2533 DisconnectedBlockTransactions disconnectpool;
2534 while (chainActive.Contains(pindex)) {
2535 CBlockIndex *pindexWalk = chainActive.Tip();
2536 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2537 setDirtyBlockIndex.insert(pindexWalk);
2538 setBlockIndexCandidates.erase(pindexWalk);
2539 // ActivateBestChain considers blocks already in chainActive
2540 // unconditionally valid already, so force disconnect away from it.
2541 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2542 // It's probably hopeless to try to make the mempool consistent
2543 // here if DisconnectTip failed, but we can try.
2544 UpdateMempoolForReorg(disconnectpool, false);
2545 return false;
2549 // DisconnectTip will add transactions to disconnectpool; try to add these
2550 // back to the mempool.
2551 UpdateMempoolForReorg(disconnectpool, true);
2553 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2554 // add it again.
2555 BlockMap::iterator it = mapBlockIndex.begin();
2556 while (it != mapBlockIndex.end()) {
2557 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2558 setBlockIndexCandidates.insert(it->second);
2560 it++;
2563 InvalidChainFound(pindex);
2564 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2565 return true;
2568 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2569 AssertLockHeld(cs_main);
2571 int nHeight = pindex->nHeight;
2573 // Remove the invalidity flag from this block and all its descendants.
2574 BlockMap::iterator it = mapBlockIndex.begin();
2575 while (it != mapBlockIndex.end()) {
2576 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2577 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2578 setDirtyBlockIndex.insert(it->second);
2579 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2580 setBlockIndexCandidates.insert(it->second);
2582 if (it->second == pindexBestInvalid) {
2583 // Reset invalid block marker if it was pointing to one of those.
2584 pindexBestInvalid = nullptr;
2587 it++;
2590 // Remove the invalidity flag from all ancestors too.
2591 while (pindex != nullptr) {
2592 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2593 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2594 setDirtyBlockIndex.insert(pindex);
2596 pindex = pindex->pprev;
2598 return true;
2601 static CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2603 // Check for duplicate
2604 uint256 hash = block.GetHash();
2605 BlockMap::iterator it = mapBlockIndex.find(hash);
2606 if (it != mapBlockIndex.end())
2607 return it->second;
2609 // Construct new block index object
2610 CBlockIndex* pindexNew = new CBlockIndex(block);
2611 assert(pindexNew);
2612 // We assign the sequence id to blocks only when the full data is available,
2613 // to avoid miners withholding blocks but broadcasting headers, to get a
2614 // competitive advantage.
2615 pindexNew->nSequenceId = 0;
2616 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2617 pindexNew->phashBlock = &((*mi).first);
2618 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2619 if (miPrev != mapBlockIndex.end())
2621 pindexNew->pprev = (*miPrev).second;
2622 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2623 pindexNew->BuildSkip();
2625 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2626 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2627 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2628 if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2629 pindexBestHeader = pindexNew;
2631 setDirtyBlockIndex.insert(pindexNew);
2633 return pindexNew;
2636 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2637 static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2639 pindexNew->nTx = block.vtx.size();
2640 pindexNew->nChainTx = 0;
2641 pindexNew->nFile = pos.nFile;
2642 pindexNew->nDataPos = pos.nPos;
2643 pindexNew->nUndoPos = 0;
2644 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2645 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2646 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2648 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2649 setDirtyBlockIndex.insert(pindexNew);
2651 if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
2652 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2653 std::deque<CBlockIndex*> queue;
2654 queue.push_back(pindexNew);
2656 // Recursively process any descendant blocks that now may be eligible to be connected.
2657 while (!queue.empty()) {
2658 CBlockIndex *pindex = queue.front();
2659 queue.pop_front();
2660 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2662 LOCK(cs_nBlockSequenceId);
2663 pindex->nSequenceId = nBlockSequenceId++;
2665 if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2666 setBlockIndexCandidates.insert(pindex);
2668 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2669 while (range.first != range.second) {
2670 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2671 queue.push_back(it->second);
2672 range.first++;
2673 mapBlocksUnlinked.erase(it);
2676 } else {
2677 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2678 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2682 return true;
2685 static bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2687 LOCK(cs_LastBlockFile);
2689 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2690 if (vinfoBlockFile.size() <= nFile) {
2691 vinfoBlockFile.resize(nFile + 1);
2694 if (!fKnown) {
2695 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2696 nFile++;
2697 if (vinfoBlockFile.size() <= nFile) {
2698 vinfoBlockFile.resize(nFile + 1);
2701 pos.nFile = nFile;
2702 pos.nPos = vinfoBlockFile[nFile].nSize;
2705 if ((int)nFile != nLastBlockFile) {
2706 if (!fKnown) {
2707 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2709 FlushBlockFile(!fKnown);
2710 nLastBlockFile = nFile;
2713 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2714 if (fKnown)
2715 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2716 else
2717 vinfoBlockFile[nFile].nSize += nAddSize;
2719 if (!fKnown) {
2720 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2721 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2722 if (nNewChunks > nOldChunks) {
2723 if (fPruneMode)
2724 fCheckForPruning = true;
2725 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2726 FILE *file = OpenBlockFile(pos);
2727 if (file) {
2728 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2729 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2730 fclose(file);
2733 else
2734 return state.Error("out of disk space");
2738 setDirtyFileInfo.insert(nFile);
2739 return true;
2742 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2744 pos.nFile = nFile;
2746 LOCK(cs_LastBlockFile);
2748 unsigned int nNewSize;
2749 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2750 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2751 setDirtyFileInfo.insert(nFile);
2753 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2754 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2755 if (nNewChunks > nOldChunks) {
2756 if (fPruneMode)
2757 fCheckForPruning = true;
2758 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2759 FILE *file = OpenUndoFile(pos);
2760 if (file) {
2761 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2762 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2763 fclose(file);
2766 else
2767 return state.Error("out of disk space");
2770 return true;
2773 static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
2775 // Check proof of work matches claimed amount
2776 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2777 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2779 return true;
2782 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2784 // These are checks that are independent of context.
2786 if (block.fChecked)
2787 return true;
2789 // Check that the header is valid (particularly PoW). This is mostly
2790 // redundant with the call in AcceptBlockHeader.
2791 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2792 return false;
2794 // Check the merkle root.
2795 if (fCheckMerkleRoot) {
2796 bool mutated;
2797 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2798 if (block.hashMerkleRoot != hashMerkleRoot2)
2799 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2801 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2802 // of transactions in a block without affecting the merkle root of a block,
2803 // while still invalidating it.
2804 if (mutated)
2805 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2808 // All potential-corruption validation must be done before we do any
2809 // transaction validation, as otherwise we may mark the header as invalid
2810 // because we receive the wrong transactions for it.
2811 // Note that witness malleability is checked in ContextualCheckBlock, so no
2812 // checks that use witness data may be performed here.
2814 // Size limits
2815 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)
2816 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2818 // First transaction must be coinbase, the rest must not be
2819 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2820 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2821 for (unsigned int i = 1; i < block.vtx.size(); i++)
2822 if (block.vtx[i]->IsCoinBase())
2823 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2825 // Check transactions
2826 for (const auto& tx : block.vtx)
2827 if (!CheckTransaction(*tx, state, false))
2828 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2829 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2831 unsigned int nSigOps = 0;
2832 for (const auto& tx : block.vtx)
2834 nSigOps += GetLegacySigOpCount(*tx);
2836 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2837 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2839 if (fCheckPOW && fCheckMerkleRoot)
2840 block.fChecked = true;
2842 return true;
2845 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2847 LOCK(cs_main);
2848 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2851 // Compute at which vout of the block's coinbase transaction the witness
2852 // commitment occurs, or -1 if not found.
2853 static int GetWitnessCommitmentIndex(const CBlock& block)
2855 int commitpos = -1;
2856 if (!block.vtx.empty()) {
2857 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2858 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) {
2859 commitpos = o;
2863 return commitpos;
2866 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2868 int commitpos = GetWitnessCommitmentIndex(block);
2869 static const std::vector<unsigned char> nonce(32, 0x00);
2870 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2871 CMutableTransaction tx(*block.vtx[0]);
2872 tx.vin[0].scriptWitness.stack.resize(1);
2873 tx.vin[0].scriptWitness.stack[0] = nonce;
2874 block.vtx[0] = MakeTransactionRef(std::move(tx));
2878 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2880 std::vector<unsigned char> commitment;
2881 int commitpos = GetWitnessCommitmentIndex(block);
2882 std::vector<unsigned char> ret(32, 0x00);
2883 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2884 if (commitpos == -1) {
2885 uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
2886 CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
2887 CTxOut out;
2888 out.nValue = 0;
2889 out.scriptPubKey.resize(38);
2890 out.scriptPubKey[0] = OP_RETURN;
2891 out.scriptPubKey[1] = 0x24;
2892 out.scriptPubKey[2] = 0xaa;
2893 out.scriptPubKey[3] = 0x21;
2894 out.scriptPubKey[4] = 0xa9;
2895 out.scriptPubKey[5] = 0xed;
2896 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2897 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2898 CMutableTransaction tx(*block.vtx[0]);
2899 tx.vout.push_back(out);
2900 block.vtx[0] = MakeTransactionRef(std::move(tx));
2903 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2904 return commitment;
2907 /** Context-dependent validity checks.
2908 * By "context", we mean only the previous block headers, but not the UTXO
2909 * set; UTXO-related validity checks are done in ConnectBlock(). */
2910 static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2912 assert(pindexPrev != nullptr);
2913 const int nHeight = pindexPrev->nHeight + 1;
2915 // Check proof of work
2916 const Consensus::Params& consensusParams = params.GetConsensus();
2917 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2918 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2920 // Check against checkpoints
2921 if (fCheckpointsEnabled) {
2922 // Don't accept any forks from the main chain prior to last checkpoint.
2923 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
2924 // MapBlockIndex.
2925 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(params.Checkpoints());
2926 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2927 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
2930 // Check timestamp against prev
2931 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2932 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2934 // Check timestamp
2935 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
2936 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
2938 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2939 // check for version 2, 3 and 4 upgrades
2940 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
2941 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
2942 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
2943 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
2944 strprintf("rejected nVersion=0x%08x block", block.nVersion));
2946 return true;
2949 static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
2951 const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
2953 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
2954 int nLockTimeFlags = 0;
2955 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
2956 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
2959 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
2960 ? pindexPrev->GetMedianTimePast()
2961 : block.GetBlockTime();
2963 // Check that all transactions are finalized
2964 for (const auto& tx : block.vtx) {
2965 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
2966 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
2970 // Enforce rule that the coinbase starts with serialized block height
2971 if (nHeight >= consensusParams.BIP34Height)
2973 CScript expect = CScript() << nHeight;
2974 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
2975 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
2976 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
2980 // Validation for witness commitments.
2981 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
2982 // coinbase (where 0x0000....0000 is used instead).
2983 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
2984 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
2985 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
2986 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
2987 // multiple, the last one is used.
2988 bool fHaveWitness = false;
2989 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
2990 int commitpos = GetWitnessCommitmentIndex(block);
2991 if (commitpos != -1) {
2992 bool malleated = false;
2993 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
2994 // The malleation check is ignored; as the transaction tree itself
2995 // already does not permit it, it is impossible to trigger in the
2996 // witness tree.
2997 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
2998 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
3000 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
3001 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3002 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
3004 fHaveWitness = true;
3008 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3009 if (!fHaveWitness) {
3010 for (const auto& tx : block.vtx) {
3011 if (tx->HasWitness()) {
3012 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
3017 // After the coinbase witness nonce and commitment are verified,
3018 // we can check if the block weight passes (before we've checked the
3019 // coinbase witness, it would be possible for the weight to be too
3020 // large by filling up the coinbase witness, which doesn't change
3021 // the block hash, so we couldn't mark the block as permanently
3022 // failed).
3023 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3024 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
3027 return true;
3030 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3032 AssertLockHeld(cs_main);
3033 // Check for duplicate
3034 uint256 hash = block.GetHash();
3035 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3036 CBlockIndex *pindex = nullptr;
3037 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3039 if (miSelf != mapBlockIndex.end()) {
3040 // Block header is already known.
3041 pindex = miSelf->second;
3042 if (ppindex)
3043 *ppindex = pindex;
3044 if (pindex->nStatus & BLOCK_FAILED_MASK)
3045 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3046 return true;
3049 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3050 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3052 // Get prev block index
3053 CBlockIndex* pindexPrev = nullptr;
3054 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3055 if (mi == mapBlockIndex.end())
3056 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
3057 pindexPrev = (*mi).second;
3058 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3059 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3060 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3061 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3063 if (pindex == nullptr)
3064 pindex = AddToBlockIndex(block);
3066 if (ppindex)
3067 *ppindex = pindex;
3069 CheckBlockIndex(chainparams.GetConsensus());
3071 return true;
3074 // Exposed wrapper for AcceptBlockHeader
3075 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
3078 LOCK(cs_main);
3079 for (const CBlockHeader& header : headers) {
3080 CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3081 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
3082 return false;
3084 if (ppindex) {
3085 *ppindex = pindex;
3089 NotifyHeaderTip();
3090 return true;
3093 /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
3094 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3096 const CBlock& block = *pblock;
3098 if (fNewBlock) *fNewBlock = false;
3099 AssertLockHeld(cs_main);
3101 CBlockIndex *pindexDummy = nullptr;
3102 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3104 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3105 return false;
3107 // Try to process all requested blocks that we don't have, but only
3108 // process an unrequested block if it's new and has enough work to
3109 // advance our tip, and isn't too many blocks ahead.
3110 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3111 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3112 // Blocks that are too out-of-order needlessly limit the effectiveness of
3113 // pruning, because pruning will not delete block files that contain any
3114 // blocks which are too close in height to the tip. Apply this test
3115 // regardless of whether pruning is enabled; it should generally be safe to
3116 // not process unrequested blocks.
3117 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3119 // TODO: Decouple this function from the block download logic by removing fRequested
3120 // This requires some new chain data structure to efficiently look up if a
3121 // block is in a chain leading to a candidate for best tip, despite not
3122 // being such a candidate itself.
3124 // TODO: deal better with return value and error conditions for duplicate
3125 // and unrequested blocks.
3126 if (fAlreadyHave) return true;
3127 if (!fRequested) { // If we didn't ask for it:
3128 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3129 if (!fHasMoreWork) return true; // Don't process less-work chains
3130 if (fTooFarAhead) return true; // Block height is too high
3132 if (fNewBlock) *fNewBlock = true;
3134 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3135 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3136 if (state.IsInvalid() && !state.CorruptionPossible()) {
3137 pindex->nStatus |= BLOCK_FAILED_VALID;
3138 setDirtyBlockIndex.insert(pindex);
3140 return error("%s: %s", __func__, FormatStateMessage(state));
3143 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3144 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3145 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3146 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3148 int nHeight = pindex->nHeight;
3150 // Write block to history file
3151 try {
3152 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3153 CDiskBlockPos blockPos;
3154 if (dbp != nullptr)
3155 blockPos = *dbp;
3156 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr))
3157 return error("AcceptBlock(): FindBlockPos failed");
3158 if (dbp == nullptr)
3159 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3160 AbortNode(state, "Failed to write block");
3161 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3162 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3163 } catch (const std::runtime_error& e) {
3164 return AbortNode(state, std::string("System error: ") + e.what());
3167 if (fCheckForPruning)
3168 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3170 return true;
3173 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3176 CBlockIndex *pindex = nullptr;
3177 if (fNewBlock) *fNewBlock = false;
3178 CValidationState state;
3179 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3180 // belt-and-suspenders.
3181 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3183 LOCK(cs_main);
3185 if (ret) {
3186 // Store to disk
3187 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
3189 CheckBlockIndex(chainparams.GetConsensus());
3190 if (!ret) {
3191 GetMainSignals().BlockChecked(*pblock, state);
3192 return error("%s: AcceptBlock FAILED", __func__);
3196 NotifyHeaderTip();
3198 CValidationState state; // Only used to report errors, not invalidity - ignore it
3199 if (!ActivateBestChain(state, chainparams, pblock))
3200 return error("%s: ActivateBestChain failed", __func__);
3202 return true;
3205 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3207 AssertLockHeld(cs_main);
3208 assert(pindexPrev && pindexPrev == chainActive.Tip());
3209 CCoinsViewCache viewNew(pcoinsTip);
3210 CBlockIndex indexDummy(block);
3211 indexDummy.pprev = pindexPrev;
3212 indexDummy.nHeight = pindexPrev->nHeight + 1;
3214 // NOTE: CheckBlockHeader is called by CheckBlock
3215 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3216 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3217 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3218 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3219 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3220 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3221 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3222 return false;
3223 assert(state.IsValid());
3225 return true;
3229 * BLOCK PRUNING CODE
3232 /* Calculate the amount of disk space the block & undo files currently use */
3233 static uint64_t CalculateCurrentUsage()
3235 uint64_t retval = 0;
3236 for (const CBlockFileInfo &file : vinfoBlockFile) {
3237 retval += file.nSize + file.nUndoSize;
3239 return retval;
3242 /* Prune a block file (modify associated database entries)*/
3243 void PruneOneBlockFile(const int fileNumber)
3245 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3246 CBlockIndex* pindex = it->second;
3247 if (pindex->nFile == fileNumber) {
3248 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3249 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3250 pindex->nFile = 0;
3251 pindex->nDataPos = 0;
3252 pindex->nUndoPos = 0;
3253 setDirtyBlockIndex.insert(pindex);
3255 // Prune from mapBlocksUnlinked -- any block we prune would have
3256 // to be downloaded again in order to consider its chain, at which
3257 // point it would be considered as a candidate for
3258 // mapBlocksUnlinked or setBlockIndexCandidates.
3259 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3260 while (range.first != range.second) {
3261 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3262 range.first++;
3263 if (_it->second == pindex) {
3264 mapBlocksUnlinked.erase(_it);
3270 vinfoBlockFile[fileNumber].SetNull();
3271 setDirtyFileInfo.insert(fileNumber);
3275 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3277 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3278 CDiskBlockPos pos(*it, 0);
3279 fs::remove(GetBlockPosFilename(pos, "blk"));
3280 fs::remove(GetBlockPosFilename(pos, "rev"));
3281 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3285 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3286 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3288 assert(fPruneMode && nManualPruneHeight > 0);
3290 LOCK2(cs_main, cs_LastBlockFile);
3291 if (chainActive.Tip() == nullptr)
3292 return;
3294 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3295 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3296 int count=0;
3297 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3298 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3299 continue;
3300 PruneOneBlockFile(fileNumber);
3301 setFilesToPrune.insert(fileNumber);
3302 count++;
3304 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3307 /* This function is called from the RPC code for pruneblockchain */
3308 void PruneBlockFilesManual(int nManualPruneHeight)
3310 CValidationState state;
3311 const CChainParams& chainparams = Params();
3312 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
3316 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
3317 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
3318 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
3319 * (which in this case means the blockchain must be re-downloaded.)
3321 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
3322 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
3323 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
3324 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
3325 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
3326 * A db flag records the fact that at least some block files have been pruned.
3328 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
3330 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3332 LOCK2(cs_main, cs_LastBlockFile);
3333 if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
3334 return;
3336 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3337 return;
3340 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3341 uint64_t nCurrentUsage = CalculateCurrentUsage();
3342 // We don't check to prune until after we've allocated new space for files
3343 // So we should leave a buffer under our target to account for another allocation
3344 // before the next pruning.
3345 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3346 uint64_t nBytesToPrune;
3347 int count=0;
3349 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3350 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3351 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3353 if (vinfoBlockFile[fileNumber].nSize == 0)
3354 continue;
3356 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3357 break;
3359 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3360 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3361 continue;
3363 PruneOneBlockFile(fileNumber);
3364 // Queue up the files for removal
3365 setFilesToPrune.insert(fileNumber);
3366 nCurrentUsage -= nBytesToPrune;
3367 count++;
3371 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3372 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3373 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3374 nLastBlockWeCanPrune, count);
3377 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3379 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3381 // Check for nMinDiskSpace bytes (currently 50MB)
3382 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3383 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3385 return true;
3388 static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3390 if (pos.IsNull())
3391 return nullptr;
3392 fs::path path = GetBlockPosFilename(pos, prefix);
3393 fs::create_directories(path.parent_path());
3394 FILE* file = fsbridge::fopen(path, "rb+");
3395 if (!file && !fReadOnly)
3396 file = fsbridge::fopen(path, "wb+");
3397 if (!file) {
3398 LogPrintf("Unable to open file %s\n", path.string());
3399 return nullptr;
3401 if (pos.nPos) {
3402 if (fseek(file, pos.nPos, SEEK_SET)) {
3403 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3404 fclose(file);
3405 return nullptr;
3408 return file;
3411 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3412 return OpenDiskFile(pos, "blk", fReadOnly);
3415 /** Open an undo file (rev?????.dat) */
3416 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3417 return OpenDiskFile(pos, "rev", fReadOnly);
3420 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3422 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3425 CBlockIndex * InsertBlockIndex(uint256 hash)
3427 if (hash.IsNull())
3428 return nullptr;
3430 // Return existing
3431 BlockMap::iterator mi = mapBlockIndex.find(hash);
3432 if (mi != mapBlockIndex.end())
3433 return (*mi).second;
3435 // Create new
3436 CBlockIndex* pindexNew = new CBlockIndex();
3437 if (!pindexNew)
3438 throw std::runtime_error(std::string(__func__) + ": new CBlockIndex failed");
3439 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3440 pindexNew->phashBlock = &((*mi).first);
3442 return pindexNew;
3445 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3447 if (!pblocktree->LoadBlockIndexGuts(chainparams.GetConsensus(), InsertBlockIndex))
3448 return false;
3450 boost::this_thread::interruption_point();
3452 // Calculate nChainWork
3453 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3454 vSortedByHeight.reserve(mapBlockIndex.size());
3455 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3457 CBlockIndex* pindex = item.second;
3458 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3460 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3461 for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
3463 CBlockIndex* pindex = item.second;
3464 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3465 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3466 // We can link the chain of blocks for which we've received transactions at some point.
3467 // Pruned nodes may have deleted the block.
3468 if (pindex->nTx > 0) {
3469 if (pindex->pprev) {
3470 if (pindex->pprev->nChainTx) {
3471 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3472 } else {
3473 pindex->nChainTx = 0;
3474 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3476 } else {
3477 pindex->nChainTx = pindex->nTx;
3480 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
3481 setBlockIndexCandidates.insert(pindex);
3482 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3483 pindexBestInvalid = pindex;
3484 if (pindex->pprev)
3485 pindex->BuildSkip();
3486 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3487 pindexBestHeader = pindex;
3490 // Load block file info
3491 pblocktree->ReadLastBlockFile(nLastBlockFile);
3492 vinfoBlockFile.resize(nLastBlockFile + 1);
3493 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3494 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3495 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3497 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3498 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3499 CBlockFileInfo info;
3500 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3501 vinfoBlockFile.push_back(info);
3502 } else {
3503 break;
3507 // Check presence of blk files
3508 LogPrintf("Checking all blk files are present...\n");
3509 std::set<int> setBlkDataFiles;
3510 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3512 CBlockIndex* pindex = item.second;
3513 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3514 setBlkDataFiles.insert(pindex->nFile);
3517 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3519 CDiskBlockPos pos(*it, 0);
3520 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3521 return false;
3525 // Check whether we have ever pruned block & undo files
3526 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3527 if (fHavePruned)
3528 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3530 // Check whether we need to continue reindexing
3531 bool fReindexing = false;
3532 pblocktree->ReadReindexing(fReindexing);
3533 fReindex |= fReindexing;
3535 // Check whether we have a transaction index
3536 pblocktree->ReadFlag("txindex", fTxIndex);
3537 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3539 return true;
3542 bool LoadChainTip(const CChainParams& chainparams)
3544 if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
3546 if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
3547 // In case we just added the genesis block, connect it now, so
3548 // that we always have a chainActive.Tip() when we return.
3549 LogPrintf("%s: Connecting genesis block...\n", __func__);
3550 CValidationState state;
3551 if (!ActivateBestChain(state, chainparams)) {
3552 return false;
3556 // Load pointer to end of best chain
3557 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3558 if (it == mapBlockIndex.end())
3559 return false;
3560 chainActive.SetTip(it->second);
3562 PruneBlockIndexCandidates();
3564 LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
3565 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3566 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3567 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3568 return true;
3571 CVerifyDB::CVerifyDB()
3573 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3576 CVerifyDB::~CVerifyDB()
3578 uiInterface.ShowProgress("", 100);
3581 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3583 LOCK(cs_main);
3584 if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
3585 return true;
3587 // Verify blocks in the best chain
3588 if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height())
3589 nCheckDepth = chainActive.Height();
3590 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3591 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3592 CCoinsViewCache coins(coinsview);
3593 CBlockIndex* pindexState = chainActive.Tip();
3594 CBlockIndex* pindexFailure = nullptr;
3595 int nGoodTransactions = 0;
3596 CValidationState state;
3597 int reportDone = 0;
3598 LogPrintf("[0%%]...");
3599 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3601 boost::this_thread::interruption_point();
3602 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3603 if (reportDone < percentageDone/10) {
3604 // report every 10% step
3605 LogPrintf("[%d%%]...", percentageDone);
3606 reportDone = percentageDone/10;
3608 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone);
3609 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3610 break;
3611 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3612 // If pruning, only go back as far as we have data.
3613 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3614 break;
3616 CBlock block;
3617 // check level 0: read from disk
3618 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3619 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3620 // check level 1: verify block validity
3621 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3622 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3623 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3624 // check level 2: verify undo validity
3625 if (nCheckLevel >= 2 && pindex) {
3626 CBlockUndo undo;
3627 CDiskBlockPos pos = pindex->GetUndoPos();
3628 if (!pos.IsNull()) {
3629 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3630 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3633 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3634 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3635 assert(coins.GetBestBlock() == pindex->GetBlockHash());
3636 DisconnectResult res = DisconnectBlock(block, pindex, coins);
3637 if (res == DISCONNECT_FAILED) {
3638 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3640 pindexState = pindex->pprev;
3641 if (res == DISCONNECT_UNCLEAN) {
3642 nGoodTransactions = 0;
3643 pindexFailure = pindex;
3644 } else {
3645 nGoodTransactions += block.vtx.size();
3648 if (ShutdownRequested())
3649 return true;
3651 if (pindexFailure)
3652 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3654 // check level 4: try reconnecting blocks
3655 if (nCheckLevel >= 4) {
3656 CBlockIndex *pindex = pindexState;
3657 while (pindex != chainActive.Tip()) {
3658 boost::this_thread::interruption_point();
3659 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3660 pindex = chainActive.Next(pindex);
3661 CBlock block;
3662 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3663 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3664 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3665 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3669 LogPrintf("[DONE].\n");
3670 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3672 return true;
3675 /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
3676 static bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
3678 // TODO: merge with ConnectBlock
3679 CBlock block;
3680 if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
3681 return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3684 for (const CTransactionRef& tx : block.vtx) {
3685 if (!tx->IsCoinBase()) {
3686 for (const CTxIn &txin : tx->vin) {
3687 inputs.SpendCoin(txin.prevout);
3690 // Pass check = true as every addition may be an overwrite.
3691 AddCoins(inputs, *tx, pindex->nHeight, true);
3693 return true;
3696 bool ReplayBlocks(const CChainParams& params, CCoinsView* view)
3698 LOCK(cs_main);
3700 CCoinsViewCache cache(view);
3702 std::vector<uint256> hashHeads = view->GetHeadBlocks();
3703 if (hashHeads.empty()) return true; // We're already in a consistent state.
3704 if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
3706 uiInterface.ShowProgress(_("Replaying blocks..."), 0);
3707 LogPrintf("Replaying blocks\n");
3709 const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
3710 const CBlockIndex* pindexNew; // New tip during the interrupted flush.
3711 const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
3713 if (mapBlockIndex.count(hashHeads[0]) == 0) {
3714 return error("ReplayBlocks(): reorganization to unknown block requested");
3716 pindexNew = mapBlockIndex[hashHeads[0]];
3718 if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
3719 if (mapBlockIndex.count(hashHeads[1]) == 0) {
3720 return error("ReplayBlocks(): reorganization from unknown block requested");
3722 pindexOld = mapBlockIndex[hashHeads[1]];
3723 pindexFork = LastCommonAncestor(pindexOld, pindexNew);
3724 assert(pindexFork != nullptr);
3727 // Rollback along the old branch.
3728 while (pindexOld != pindexFork) {
3729 if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
3730 CBlock block;
3731 if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
3732 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3734 LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
3735 DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
3736 if (res == DISCONNECT_FAILED) {
3737 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3739 // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
3740 // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
3741 // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
3742 // the result is still a version of the UTXO set with the effects of that block undone.
3744 pindexOld = pindexOld->pprev;
3747 // Roll forward from the forking point to the new tip.
3748 int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
3749 for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
3750 const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
3751 LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
3752 if (!RollforwardBlock(pindex, cache, params)) return false;
3755 cache.SetBestBlock(pindexNew->GetBlockHash());
3756 cache.Flush();
3757 uiInterface.ShowProgress("", 100);
3758 return true;
3761 bool RewindBlockIndex(const CChainParams& params)
3763 LOCK(cs_main);
3765 // Note that during -reindex-chainstate we are called with an empty chainActive!
3767 int nHeight = 1;
3768 while (nHeight <= chainActive.Height()) {
3769 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3770 break;
3772 nHeight++;
3775 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3776 CValidationState state;
3777 CBlockIndex* pindex = chainActive.Tip();
3778 while (chainActive.Height() >= nHeight) {
3779 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3780 // If pruning, don't try rewinding past the HAVE_DATA point;
3781 // since older blocks can't be served anyway, there's
3782 // no need to walk further, and trying to DisconnectTip()
3783 // will fail (and require a needless reindex/redownload
3784 // of the blockchain).
3785 break;
3787 if (!DisconnectTip(state, params, nullptr)) {
3788 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3790 // Occasionally flush state to disk.
3791 if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
3792 return false;
3795 // Reduce validity flag and have-data flags.
3796 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3797 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3798 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3799 CBlockIndex* pindexIter = it->second;
3801 // Note: If we encounter an insufficiently validated block that
3802 // is on chainActive, it must be because we are a pruning node, and
3803 // this block or some successor doesn't HAVE_DATA, so we were unable to
3804 // rewind all the way. Blocks remaining on chainActive at this point
3805 // must not have their validity reduced.
3806 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3807 // Reduce validity
3808 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3809 // Remove have-data flags.
3810 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3811 // Remove storage location.
3812 pindexIter->nFile = 0;
3813 pindexIter->nDataPos = 0;
3814 pindexIter->nUndoPos = 0;
3815 // Remove various other things
3816 pindexIter->nTx = 0;
3817 pindexIter->nChainTx = 0;
3818 pindexIter->nSequenceId = 0;
3819 // Make sure it gets written.
3820 setDirtyBlockIndex.insert(pindexIter);
3821 // Update indexes
3822 setBlockIndexCandidates.erase(pindexIter);
3823 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3824 while (ret.first != ret.second) {
3825 if (ret.first->second == pindexIter) {
3826 mapBlocksUnlinked.erase(ret.first++);
3827 } else {
3828 ++ret.first;
3831 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3832 setBlockIndexCandidates.insert(pindexIter);
3836 if (chainActive.Tip() != nullptr) {
3837 // We can't prune block index candidates based on our tip if we have
3838 // no tip due to chainActive being empty!
3839 PruneBlockIndexCandidates();
3841 CheckBlockIndex(params.GetConsensus());
3843 // FlushStateToDisk can possibly read chainActive. Be conservative
3844 // and skip it here, we're about to -reindex-chainstate anyway, so
3845 // it'll get called a bunch real soon.
3846 if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
3847 return false;
3851 return true;
3854 // May NOT be used after any connections are up as much
3855 // of the peer-processing logic assumes a consistent
3856 // block index state
3857 void UnloadBlockIndex()
3859 LOCK(cs_main);
3860 setBlockIndexCandidates.clear();
3861 chainActive.SetTip(nullptr);
3862 pindexBestInvalid = nullptr;
3863 pindexBestHeader = nullptr;
3864 mempool.clear();
3865 mapBlocksUnlinked.clear();
3866 vinfoBlockFile.clear();
3867 nLastBlockFile = 0;
3868 nBlockSequenceId = 1;
3869 setDirtyBlockIndex.clear();
3870 setDirtyFileInfo.clear();
3871 versionbitscache.Clear();
3872 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3873 warningcache[b].clear();
3876 for (BlockMap::value_type& entry : mapBlockIndex) {
3877 delete entry.second;
3879 mapBlockIndex.clear();
3880 fHavePruned = false;
3883 bool LoadBlockIndex(const CChainParams& chainparams)
3885 // Load block index from databases
3886 bool needs_init = fReindex;
3887 if (!fReindex) {
3888 bool ret = LoadBlockIndexDB(chainparams);
3889 if (!ret) return false;
3890 needs_init = mapBlockIndex.empty();
3893 if (needs_init) {
3894 // Everything here is for *new* reindex/DBs. Thus, though
3895 // LoadBlockIndexDB may have set fReindex if we shut down
3896 // mid-reindex previously, we don't check fReindex and
3897 // instead only check it prior to LoadBlockIndexDB to set
3898 // needs_init.
3900 LogPrintf("Initializing databases...\n");
3901 // Use the provided setting for -txindex in the new database
3902 fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
3903 pblocktree->WriteFlag("txindex", fTxIndex);
3905 return true;
3908 bool LoadGenesisBlock(const CChainParams& chainparams)
3910 LOCK(cs_main);
3912 // Check whether we're already initialized by checking for genesis in
3913 // mapBlockIndex. Note that we can't use chainActive here, since it is
3914 // set based on the coins db, not the block index db, which is the only
3915 // thing loaded at this point.
3916 if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
3917 return true;
3919 try {
3920 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3921 // Start new block file
3922 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3923 CDiskBlockPos blockPos;
3924 CValidationState state;
3925 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3926 return error("%s: FindBlockPos failed", __func__);
3927 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3928 return error("%s: writing genesis block to disk failed", __func__);
3929 CBlockIndex *pindex = AddToBlockIndex(block);
3930 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3931 return error("%s: genesis block not accepted", __func__);
3932 } catch (const std::runtime_error& e) {
3933 return error("%s: failed to write genesis block: %s", __func__, e.what());
3936 return true;
3939 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
3941 // Map of disk positions for blocks with unknown parent (only used for reindex)
3942 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3943 int64_t nStart = GetTimeMillis();
3945 int nLoaded = 0;
3946 try {
3947 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3948 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
3949 uint64_t nRewind = blkdat.GetPos();
3950 while (!blkdat.eof()) {
3951 boost::this_thread::interruption_point();
3953 blkdat.SetPos(nRewind);
3954 nRewind++; // start one byte further next time, in case of failure
3955 blkdat.SetLimit(); // remove former limit
3956 unsigned int nSize = 0;
3957 try {
3958 // locate a header
3959 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
3960 blkdat.FindByte(chainparams.MessageStart()[0]);
3961 nRewind = blkdat.GetPos()+1;
3962 blkdat >> FLATDATA(buf);
3963 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
3964 continue;
3965 // read size
3966 blkdat >> nSize;
3967 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3968 continue;
3969 } catch (const std::exception&) {
3970 // no valid block header found; don't complain
3971 break;
3973 try {
3974 // read block
3975 uint64_t nBlockPos = blkdat.GetPos();
3976 if (dbp)
3977 dbp->nPos = nBlockPos;
3978 blkdat.SetLimit(nBlockPos + nSize);
3979 blkdat.SetPos(nBlockPos);
3980 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3981 CBlock& block = *pblock;
3982 blkdat >> block;
3983 nRewind = blkdat.GetPos();
3985 // detect out of order blocks, and store them for later
3986 uint256 hash = block.GetHash();
3987 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3988 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3989 block.hashPrevBlock.ToString());
3990 if (dbp)
3991 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3992 continue;
3995 // process in case the block isn't known yet
3996 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3997 LOCK(cs_main);
3998 CValidationState state;
3999 if (AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
4000 nLoaded++;
4001 if (state.IsError())
4002 break;
4003 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4004 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4007 // Activate the genesis block so normal node progress can continue
4008 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
4009 CValidationState state;
4010 if (!ActivateBestChain(state, chainparams)) {
4011 break;
4015 NotifyHeaderTip();
4017 // Recursively process earlier encountered successors of this block
4018 std::deque<uint256> queue;
4019 queue.push_back(hash);
4020 while (!queue.empty()) {
4021 uint256 head = queue.front();
4022 queue.pop_front();
4023 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4024 while (range.first != range.second) {
4025 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4026 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4027 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
4029 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4030 head.ToString());
4031 LOCK(cs_main);
4032 CValidationState dummy;
4033 if (AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
4035 nLoaded++;
4036 queue.push_back(pblockrecursive->GetHash());
4039 range.first++;
4040 mapBlocksUnknownParent.erase(it);
4041 NotifyHeaderTip();
4044 } catch (const std::exception& e) {
4045 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4048 } catch (const std::runtime_error& e) {
4049 AbortNode(std::string("System error: ") + e.what());
4051 if (nLoaded > 0)
4052 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4053 return nLoaded > 0;
4056 void static CheckBlockIndex(const Consensus::Params& consensusParams)
4058 if (!fCheckBlockIndex) {
4059 return;
4062 LOCK(cs_main);
4064 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4065 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4066 // iterating the block tree require that chainActive has been initialized.)
4067 if (chainActive.Height() < 0) {
4068 assert(mapBlockIndex.size() <= 1);
4069 return;
4072 // Build forward-pointing map of the entire block tree.
4073 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4074 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4075 forward.insert(std::make_pair(it->second->pprev, it->second));
4078 assert(forward.size() == mapBlockIndex.size());
4080 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4081 CBlockIndex *pindex = rangeGenesis.first->second;
4082 rangeGenesis.first++;
4083 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4085 // Iterate over the entire block tree, using depth-first search.
4086 // Along the way, remember whether there are blocks on the path from genesis
4087 // block being explored which are the first to have certain properties.
4088 size_t nNodes = 0;
4089 int nHeight = 0;
4090 CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4091 CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4092 CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4093 CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4094 CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4095 CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4096 CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4097 while (pindex != nullptr) {
4098 nNodes++;
4099 if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4100 if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4101 if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4102 if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4103 if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4104 if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4105 if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4107 // Begin: actual consistency checks.
4108 if (pindex->pprev == nullptr) {
4109 // Genesis block checks.
4110 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4111 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4113 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)
4114 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4115 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4116 if (!fHavePruned) {
4117 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4118 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4119 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4120 } else {
4121 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4122 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4124 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4125 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4126 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4127 assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4128 assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
4129 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4130 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.
4131 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4132 assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
4133 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4134 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4135 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4136 if (pindexFirstInvalid == nullptr) {
4137 // Checks for not-invalid blocks.
4138 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4140 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
4141 if (pindexFirstInvalid == nullptr) {
4142 // If this block sorts at least as good as the current tip and
4143 // is valid and we have all data for its parents, it must be in
4144 // setBlockIndexCandidates. chainActive.Tip() must also be there
4145 // even if some data has been pruned.
4146 if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
4147 assert(setBlockIndexCandidates.count(pindex));
4149 // If some parent is missing, then it could be that this block was in
4150 // setBlockIndexCandidates but had to be removed because of the missing data.
4151 // In this case it must be in mapBlocksUnlinked -- see test below.
4153 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4154 assert(setBlockIndexCandidates.count(pindex) == 0);
4156 // Check whether this block is in mapBlocksUnlinked.
4157 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4158 bool foundInUnlinked = false;
4159 while (rangeUnlinked.first != rangeUnlinked.second) {
4160 assert(rangeUnlinked.first->first == pindex->pprev);
4161 if (rangeUnlinked.first->second == pindex) {
4162 foundInUnlinked = true;
4163 break;
4165 rangeUnlinked.first++;
4167 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4168 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4169 assert(foundInUnlinked);
4171 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4172 if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4173 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4174 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4175 assert(fHavePruned); // We must have pruned.
4176 // This block may have entered mapBlocksUnlinked if:
4177 // - it has a descendant that at some point had more work than the
4178 // tip, and
4179 // - we tried switching to that descendant but were missing
4180 // data for some intermediate block between chainActive and the
4181 // tip.
4182 // So if this block is itself better than chainActive.Tip() and it wasn't in
4183 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4184 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4185 if (pindexFirstInvalid == nullptr) {
4186 assert(foundInUnlinked);
4190 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4191 // End: actual consistency checks.
4193 // Try descending into the first subnode.
4194 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4195 if (range.first != range.second) {
4196 // A subnode was found.
4197 pindex = range.first->second;
4198 nHeight++;
4199 continue;
4201 // This is a leaf node.
4202 // Move upwards until we reach a node of which we have not yet visited the last child.
4203 while (pindex) {
4204 // We are going to either move to a parent or a sibling of pindex.
4205 // If pindex was the first with a certain property, unset the corresponding variable.
4206 if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4207 if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4208 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4209 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4210 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4211 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4212 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4213 // Find our parent.
4214 CBlockIndex* pindexPar = pindex->pprev;
4215 // Find which child we just visited.
4216 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4217 while (rangePar.first->second != pindex) {
4218 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4219 rangePar.first++;
4221 // Proceed to the next one.
4222 rangePar.first++;
4223 if (rangePar.first != rangePar.second) {
4224 // Move to the sibling.
4225 pindex = rangePar.first->second;
4226 break;
4227 } else {
4228 // Move up further.
4229 pindex = pindexPar;
4230 nHeight--;
4231 continue;
4236 // Check that we actually traversed the entire map.
4237 assert(nNodes == forward.size());
4240 std::string CBlockFileInfo::ToString() const
4242 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));
4245 CBlockFileInfo* GetBlockFileInfo(size_t n)
4247 return &vinfoBlockFile.at(n);
4250 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
4252 LOCK(cs_main);
4253 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4256 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
4258 LOCK(cs_main);
4259 return VersionBitsStatistics(chainActive.Tip(), params, pos);
4262 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
4264 LOCK(cs_main);
4265 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
4268 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4270 bool LoadMempool(void)
4272 const CChainParams& chainparams = Params();
4273 int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4274 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4275 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4276 if (file.IsNull()) {
4277 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4278 return false;
4281 int64_t count = 0;
4282 int64_t skipped = 0;
4283 int64_t failed = 0;
4284 int64_t nNow = GetTime();
4286 try {
4287 uint64_t version;
4288 file >> version;
4289 if (version != MEMPOOL_DUMP_VERSION) {
4290 return false;
4292 uint64_t num;
4293 file >> num;
4294 while (num--) {
4295 CTransactionRef tx;
4296 int64_t nTime;
4297 int64_t nFeeDelta;
4298 file >> tx;
4299 file >> nTime;
4300 file >> nFeeDelta;
4302 CAmount amountdelta = nFeeDelta;
4303 if (amountdelta) {
4304 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4306 CValidationState state;
4307 if (nTime + nExpiryTimeout > nNow) {
4308 LOCK(cs_main);
4309 AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, true, nullptr, nTime, nullptr, false, 0);
4310 if (state.IsValid()) {
4311 ++count;
4312 } else {
4313 ++failed;
4315 } else {
4316 ++skipped;
4318 if (ShutdownRequested())
4319 return false;
4321 std::map<uint256, CAmount> mapDeltas;
4322 file >> mapDeltas;
4324 for (const auto& i : mapDeltas) {
4325 mempool.PrioritiseTransaction(i.first, i.second);
4327 } catch (const std::exception& e) {
4328 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4329 return false;
4332 LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
4333 return true;
4336 bool DumpMempool(void)
4338 int64_t start = GetTimeMicros();
4340 std::map<uint256, CAmount> mapDeltas;
4341 std::vector<TxMempoolInfo> vinfo;
4344 LOCK(mempool.cs);
4345 for (const auto &i : mempool.mapDeltas) {
4346 mapDeltas[i.first] = i.second;
4348 vinfo = mempool.infoAll();
4351 int64_t mid = GetTimeMicros();
4353 try {
4354 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4355 if (!filestr) {
4356 return false;
4359 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4361 uint64_t version = MEMPOOL_DUMP_VERSION;
4362 file << version;
4364 file << (uint64_t)vinfo.size();
4365 for (const auto& i : vinfo) {
4366 file << *(i.tx);
4367 file << (int64_t)i.nTime;
4368 file << (int64_t)i.nFeeDelta;
4369 mapDeltas.erase(i.tx->GetHash());
4372 file << mapDeltas;
4373 FileCommit(file.Get());
4374 file.fclose();
4375 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4376 int64_t last = GetTimeMicros();
4377 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
4378 } catch (const std::exception& e) {
4379 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4380 return false;
4382 return true;
4385 //! Guess how far we are in the verification process at the given block index
4386 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4387 if (pindex == nullptr)
4388 return 0.0;
4390 int64_t nNow = time(nullptr);
4392 double fTxTotal;
4394 if (pindex->nChainTx <= data.nTxCount) {
4395 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4396 } else {
4397 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4400 return pindex->nChainTx / fTxTotal;
4403 class CMainCleanup
4405 public:
4406 CMainCleanup() {}
4407 ~CMainCleanup() {
4408 // block headers
4409 BlockMap::iterator it1 = mapBlockIndex.begin();
4410 for (; it1 != mapBlockIndex.end(); it1++)
4411 delete (*it1).second;
4412 mapBlockIndex.clear();
4414 } instance_of_cmaincleanup;