Fix typo: "conditon" → "condition"
[bitcoinplatinum.git] / src / validation.cpp
blobd7d880d24f556393286efad732f185b83d21be9a
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 "pow.h"
24 #include "primitives/block.h"
25 #include "primitives/transaction.h"
26 #include "random.h"
27 #include "reverse_iterator.h"
28 #include "script/script.h"
29 #include "script/sigcache.h"
30 #include "script/standard.h"
31 #include "timedata.h"
32 #include "tinyformat.h"
33 #include "txdb.h"
34 #include "txmempool.h"
35 #include "ui_interface.h"
36 #include "undo.h"
37 #include "util.h"
38 #include "utilmoneystr.h"
39 #include "utilstrencodings.h"
40 #include "validationinterface.h"
41 #include "versionbits.h"
42 #include "warnings.h"
44 #include <atomic>
45 #include <sstream>
47 #include <boost/algorithm/string/replace.hpp>
48 #include <boost/algorithm/string/join.hpp>
49 #include <boost/thread.hpp>
51 #if defined(NDEBUG)
52 # error "Bitcoin cannot be compiled without assertions."
53 #endif
55 /**
56 * Global state
59 CCriticalSection cs_main;
61 BlockMap mapBlockIndex;
62 CChain chainActive;
63 CBlockIndex *pindexBestHeader = NULL;
64 CWaitableCriticalSection csBestBlock;
65 CConditionVariable cvBlockChange;
66 int nScriptCheckThreads = 0;
67 std::atomic_bool fImporting(false);
68 bool fReindex = false;
69 bool fTxIndex = false;
70 bool fHavePruned = false;
71 bool fPruneMode = false;
72 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
73 bool fRequireStandard = true;
74 bool fCheckBlockIndex = false;
75 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
76 size_t nCoinCacheUsage = 5000 * 300;
77 uint64_t nPruneTarget = 0;
78 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
79 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
81 uint256 hashAssumeValid;
83 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
84 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
86 CBlockPolicyEstimator feeEstimator;
87 CTxMemPool mempool(&feeEstimator);
89 static void CheckBlockIndex(const Consensus::Params& consensusParams);
91 /** Constant stuff for coinbase transactions we create: */
92 CScript COINBASE_FLAGS;
94 const std::string strMessageMagic = "Bitcoin Signed Message:\n";
96 // Internal stuff
97 namespace {
99 struct CBlockIndexWorkComparator
101 bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
102 // First sort by most total work, ...
103 if (pa->nChainWork > pb->nChainWork) return false;
104 if (pa->nChainWork < pb->nChainWork) return true;
106 // ... then by earliest time received, ...
107 if (pa->nSequenceId < pb->nSequenceId) return false;
108 if (pa->nSequenceId > pb->nSequenceId) return true;
110 // Use pointer address as tie breaker (should only happen with blocks
111 // loaded from disk, as those all have id 0).
112 if (pa < pb) return false;
113 if (pa > pb) return true;
115 // Identical blocks.
116 return false;
120 CBlockIndex *pindexBestInvalid;
123 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
124 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
125 * missing the data for the block.
127 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
128 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
129 * Pruned nodes may have entries where B is missing data.
131 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
133 CCriticalSection cs_LastBlockFile;
134 std::vector<CBlockFileInfo> vinfoBlockFile;
135 int nLastBlockFile = 0;
136 /** Global flag to indicate we should check to see if there are
137 * block/undo files that should be deleted. Set on startup
138 * or if we allocate more file space when we're in prune mode
140 bool fCheckForPruning = false;
143 * Every received block is assigned a unique and increasing identifier, so we
144 * know which one to give priority in case of a fork.
146 CCriticalSection cs_nBlockSequenceId;
147 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
148 int32_t nBlockSequenceId = 1;
149 /** Decreasing counter (used by subsequent preciousblock calls). */
150 int32_t nBlockReverseSequenceId = -1;
151 /** chainwork for the last block that preciousblock has been applied to. */
152 arith_uint256 nLastPreciousChainwork = 0;
154 /** Dirty block index entries. */
155 std::set<CBlockIndex*> setDirtyBlockIndex;
157 /** Dirty block file entries. */
158 std::set<int> setDirtyFileInfo;
159 } // anon namespace
161 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
163 // Find the first block the caller has in the main chain
164 for (const uint256& hash : locator.vHave) {
165 BlockMap::iterator mi = mapBlockIndex.find(hash);
166 if (mi != mapBlockIndex.end())
168 CBlockIndex* pindex = (*mi).second;
169 if (chain.Contains(pindex))
170 return pindex;
171 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
172 return chain.Tip();
176 return chain.Genesis();
179 CCoinsViewDB *pcoinsdbview = NULL;
180 CCoinsViewCache *pcoinsTip = NULL;
181 CBlockTreeDB *pblocktree = NULL;
183 enum FlushStateMode {
184 FLUSH_STATE_NONE,
185 FLUSH_STATE_IF_NEEDED,
186 FLUSH_STATE_PERIODIC,
187 FLUSH_STATE_ALWAYS
190 // See definition for documentation
191 static bool FlushStateToDisk(const CChainParams& chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
192 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
193 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
194 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);
195 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
197 bool CheckFinalTx(const CTransaction &tx, int flags)
199 AssertLockHeld(cs_main);
201 // By convention a negative value for flags indicates that the
202 // current network-enforced consensus rules should be used. In
203 // a future soft-fork scenario that would mean checking which
204 // rules would be enforced for the next block and setting the
205 // appropriate flags. At the present time no soft-forks are
206 // scheduled, so no flags are set.
207 flags = std::max(flags, 0);
209 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
210 // nLockTime because when IsFinalTx() is called within
211 // CBlock::AcceptBlock(), the height of the block *being*
212 // evaluated is what is used. Thus if we want to know if a
213 // transaction can be part of the *next* block, we need to call
214 // IsFinalTx() with one more than chainActive.Height().
215 const int nBlockHeight = chainActive.Height() + 1;
217 // BIP113 will require that time-locked transactions have nLockTime set to
218 // less than the median time of the previous block they're contained in.
219 // When the next block is created its previous block will be the current
220 // chain tip, so we use that to calculate the median time passed to
221 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
222 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
223 ? chainActive.Tip()->GetMedianTimePast()
224 : GetAdjustedTime();
226 return IsFinalTx(tx, nBlockHeight, nBlockTime);
229 bool TestLockPointValidity(const LockPoints* lp)
231 AssertLockHeld(cs_main);
232 assert(lp);
233 // If there are relative lock times then the maxInputBlock will be set
234 // If there are no relative lock times, the LockPoints don't depend on the chain
235 if (lp->maxInputBlock) {
236 // Check whether chainActive is an extension of the block at which the LockPoints
237 // calculation was valid. If not LockPoints are no longer valid
238 if (!chainActive.Contains(lp->maxInputBlock)) {
239 return false;
243 // LockPoints still valid
244 return true;
247 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
249 AssertLockHeld(cs_main);
250 AssertLockHeld(mempool.cs);
252 CBlockIndex* tip = chainActive.Tip();
253 CBlockIndex index;
254 index.pprev = tip;
255 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
256 // height based locks because when SequenceLocks() is called within
257 // ConnectBlock(), the height of the block *being*
258 // evaluated is what is used.
259 // Thus if we want to know if a transaction can be part of the
260 // *next* block, we need to use one more than chainActive.Height()
261 index.nHeight = tip->nHeight + 1;
263 std::pair<int, int64_t> lockPair;
264 if (useExistingLockPoints) {
265 assert(lp);
266 lockPair.first = lp->height;
267 lockPair.second = lp->time;
269 else {
270 // pcoinsTip contains the UTXO set for chainActive.Tip()
271 CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
272 std::vector<int> prevheights;
273 prevheights.resize(tx.vin.size());
274 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
275 const CTxIn& txin = tx.vin[txinIndex];
276 Coin coin;
277 if (!viewMemPool.GetCoin(txin.prevout, coin)) {
278 return error("%s: Missing input", __func__);
280 if (coin.nHeight == MEMPOOL_HEIGHT) {
281 // Assume all mempool transaction confirm in the next block
282 prevheights[txinIndex] = tip->nHeight + 1;
283 } else {
284 prevheights[txinIndex] = coin.nHeight;
287 lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
288 if (lp) {
289 lp->height = lockPair.first;
290 lp->time = lockPair.second;
291 // Also store the hash of the block with the highest height of
292 // all the blocks which have sequence locked prevouts.
293 // This hash needs to still be on the chain
294 // for these LockPoint calculations to be valid
295 // Note: It is impossible to correctly calculate a maxInputBlock
296 // if any of the sequence locked inputs depend on unconfirmed txs,
297 // except in the special case where the relative lock time/height
298 // is 0, which is equivalent to no sequence lock. Since we assume
299 // input height of tip+1 for mempool txs and test the resulting
300 // lockPair from CalculateSequenceLocks against tip+1. We know
301 // EvaluateSequenceLocks will fail if there was a non-zero sequence
302 // lock on a mempool input, so we can use the return value of
303 // CheckSequenceLocks to indicate the LockPoints validity
304 int maxInputHeight = 0;
305 for (int height : prevheights) {
306 // Can ignore mempool inputs since we'll fail if they had non-zero locks
307 if (height != tip->nHeight+1) {
308 maxInputHeight = std::max(maxInputHeight, height);
311 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
314 return EvaluateSequenceLocks(index, lockPair);
317 // Returns the script flags which should be checked for a given block
318 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
320 static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
321 int expired = pool.Expire(GetTime() - age);
322 if (expired != 0) {
323 LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
326 std::vector<COutPoint> vNoSpendsRemaining;
327 pool.TrimToSize(limit, &vNoSpendsRemaining);
328 for (const COutPoint& removed : vNoSpendsRemaining)
329 pcoinsTip->Uncache(removed);
332 /** Convert CValidationState to a human-readable message for logging */
333 std::string FormatStateMessage(const CValidationState &state)
335 return strprintf("%s%s (code %i)",
336 state.GetRejectReason(),
337 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
338 state.GetRejectCode());
341 static bool IsCurrentForFeeEstimation()
343 AssertLockHeld(cs_main);
344 if (IsInitialBlockDownload())
345 return false;
346 if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
347 return false;
348 if (chainActive.Height() < pindexBestHeader->nHeight - 1)
349 return false;
350 return true;
353 /* Make mempool consistent after a reorg, by re-adding or recursively erasing
354 * disconnected block transactions from the mempool, and also removing any
355 * other transactions from the mempool that are no longer valid given the new
356 * tip/height.
358 * Note: we assume that disconnectpool only contains transactions that are NOT
359 * confirmed in the current chain nor already in the mempool (otherwise,
360 * in-mempool descendants of such transactions would be removed).
362 * Passing fAddToMempool=false will skip trying to add the transactions back,
363 * and instead just erase from the mempool as needed.
366 void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
368 AssertLockHeld(cs_main);
369 std::vector<uint256> vHashUpdate;
370 // disconnectpool's insertion_order index sorts the entries from
371 // oldest to newest, but the oldest entry will be the last tx from the
372 // latest mined block that was disconnected.
373 // Iterate disconnectpool in reverse, so that we add transactions
374 // back to the mempool starting with the earliest transaction that had
375 // been previously seen in a block.
376 auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
377 while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
378 // ignore validation errors in resurrected transactions
379 CValidationState stateDummy;
380 if (!fAddToMempool || (*it)->IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, *it, false, NULL, NULL, true)) {
381 // If the transaction doesn't make it in to the mempool, remove any
382 // transactions that depend on it (which would now be orphans).
383 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
384 } else if (mempool.exists((*it)->GetHash())) {
385 vHashUpdate.push_back((*it)->GetHash());
387 ++it;
389 disconnectpool.queuedTx.clear();
390 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
391 // no in-mempool children, which is generally not true when adding
392 // previously-confirmed transactions back to the mempool.
393 // UpdateTransactionsFromBlock finds descendants of any transactions in
394 // the disconnectpool that were added back and cleans up the mempool state.
395 mempool.UpdateTransactionsFromBlock(vHashUpdate);
397 // We also need to remove any now-immature transactions
398 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
399 // Re-limit mempool size, in case we added any transactions
400 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
403 // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
404 // were somehow broken and returning the wrong scriptPubKeys
405 static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool& pool,
406 unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) {
407 AssertLockHeld(cs_main);
409 // pool.cs should be locked already, but go ahead and re-take the lock here
410 // to enforce that mempool doesn't change between when we check the view
411 // and when we actually call through to CheckInputs
412 LOCK(pool.cs);
414 assert(!tx.IsCoinBase());
415 for (const CTxIn& txin : tx.vin) {
416 const Coin& coin = view.AccessCoin(txin.prevout);
418 // At this point we haven't actually checked if the coins are all
419 // available (or shouldn't assume we have, since CheckInputs does).
420 // So we just return failure if the inputs are not available here,
421 // and then only have to check equivalence for available inputs.
422 if (coin.IsSpent()) return false;
424 const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
425 if (txFrom) {
426 assert(txFrom->GetHash() == txin.prevout.hash);
427 assert(txFrom->vout.size() > txin.prevout.n);
428 assert(txFrom->vout[txin.prevout.n] == coin.out);
429 } else {
430 const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout);
431 assert(!coinFromDisk.IsSpent());
432 assert(coinFromDisk.out == coin.out);
436 return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata);
439 static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool fLimitFree,
440 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
441 bool fOverrideMempoolLimit, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache)
443 const CTransaction& tx = *ptx;
444 const uint256 hash = tx.GetHash();
445 AssertLockHeld(cs_main);
446 if (pfMissingInputs)
447 *pfMissingInputs = false;
449 if (!CheckTransaction(tx, state))
450 return false; // state filled in by CheckTransaction
452 // Coinbase is only valid in a block, not as a loose transaction
453 if (tx.IsCoinBase())
454 return state.DoS(100, false, REJECT_INVALID, "coinbase");
456 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
457 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), chainparams.GetConsensus());
458 if (!GetBoolArg("-prematurewitness", false) && tx.HasWitness() && !witnessEnabled) {
459 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
462 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
463 std::string reason;
464 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
465 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
467 // Only accept nLockTime-using transactions that can be mined in the next
468 // block; we don't want our mempool filled up with transactions that can't
469 // be mined yet.
470 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
471 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
473 // is it already in the memory pool?
474 if (pool.exists(hash)) {
475 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool");
478 // Check for conflicts with in-memory transactions
479 std::set<uint256> setConflicts;
481 LOCK(pool.cs); // protect pool.mapNextTx
482 for (const CTxIn &txin : tx.vin)
484 auto itConflicting = pool.mapNextTx.find(txin.prevout);
485 if (itConflicting != pool.mapNextTx.end())
487 const CTransaction *ptxConflicting = itConflicting->second;
488 if (!setConflicts.count(ptxConflicting->GetHash()))
490 // Allow opt-out of transaction replacement by setting
491 // nSequence >= maxint-1 on all inputs.
493 // maxint-1 is picked to still allow use of nLockTime by
494 // non-replaceable transactions. All inputs rather than just one
495 // is for the sake of multi-party protocols, where we don't
496 // want a single party to be able to disable replacement.
498 // The opt-out ignores descendants as anyone relying on
499 // first-seen mempool behavior should be checking all
500 // unconfirmed ancestors anyway; doing otherwise is hopelessly
501 // insecure.
502 bool fReplacementOptOut = true;
503 if (fEnableReplacement)
505 for (const CTxIn &_txin : ptxConflicting->vin)
507 if (_txin.nSequence < std::numeric_limits<unsigned int>::max()-1)
509 fReplacementOptOut = false;
510 break;
514 if (fReplacementOptOut) {
515 return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict");
518 setConflicts.insert(ptxConflicting->GetHash());
525 CCoinsView dummy;
526 CCoinsViewCache view(&dummy);
528 CAmount nValueIn = 0;
529 LockPoints lp;
531 LOCK(pool.cs);
532 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
533 view.SetBackend(viewMemPool);
535 // do all inputs exist?
536 for (const CTxIn txin : tx.vin) {
537 if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
538 coins_to_uncache.push_back(txin.prevout);
540 if (!view.HaveCoin(txin.prevout)) {
541 // Are inputs missing because we already have the tx?
542 for (size_t out = 0; out < tx.vout.size(); out++) {
543 // Optimistically just do efficient check of cache for outputs
544 if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
545 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
548 // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
549 if (pfMissingInputs) {
550 *pfMissingInputs = true;
552 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
556 // Bring the best block into scope
557 view.GetBestBlock();
559 nValueIn = view.GetValueIn(tx);
561 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
562 view.SetBackend(dummy);
564 // Only accept BIP68 sequence locked transactions that can be mined in the next
565 // block; we don't want our mempool filled up with transactions that can't
566 // be mined yet.
567 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
568 // CoinsViewCache instead of create its own
569 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
570 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
573 // Check for non-standard pay-to-script-hash in inputs
574 if (fRequireStandard && !AreInputsStandard(tx, view))
575 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
577 // Check for non-standard witness in P2WSH
578 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
579 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
581 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
583 CAmount nValueOut = tx.GetValueOut();
584 CAmount nFees = nValueIn-nValueOut;
585 // nModifiedFees includes any fee deltas from PrioritiseTransaction
586 CAmount nModifiedFees = nFees;
587 pool.ApplyDelta(hash, nModifiedFees);
589 // Keep track of transactions that spend a coinbase, which we re-scan
590 // during reorgs to ensure COINBASE_MATURITY is still met.
591 bool fSpendsCoinbase = false;
592 for (const CTxIn &txin : tx.vin) {
593 const Coin &coin = view.AccessCoin(txin.prevout);
594 if (coin.IsCoinBase()) {
595 fSpendsCoinbase = true;
596 break;
600 CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
601 fSpendsCoinbase, nSigOpsCost, lp);
602 unsigned int nSize = entry.GetTxSize();
604 // Check that the transaction doesn't have an excessive number of
605 // sigops, making it impossible to mine. Since the coinbase transaction
606 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
607 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
608 // merely non-standard transaction.
609 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
610 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
611 strprintf("%d", nSigOpsCost));
613 CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
614 if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
615 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
618 // No transactions are allowed below minRelayTxFee except from disconnected blocks
619 if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
620 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
623 if (nAbsurdFee && nFees > nAbsurdFee)
624 return state.Invalid(false,
625 REJECT_HIGHFEE, "absurdly-high-fee",
626 strprintf("%d > %d", nFees, nAbsurdFee));
628 // Calculate in-mempool ancestors, up to a limit.
629 CTxMemPool::setEntries setAncestors;
630 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
631 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
632 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
633 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
634 std::string errString;
635 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
636 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
639 // A transaction that spends outputs that would be replaced by it is invalid. Now
640 // that we have the set of all ancestors we can detect this
641 // pathological case by making sure setConflicts and setAncestors don't
642 // intersect.
643 for (CTxMemPool::txiter ancestorIt : setAncestors)
645 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
646 if (setConflicts.count(hashAncestor))
648 return state.DoS(10, false,
649 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
650 strprintf("%s spends conflicting transaction %s",
651 hash.ToString(),
652 hashAncestor.ToString()));
656 // Check if it's economically rational to mine this transaction rather
657 // than the ones it replaces.
658 CAmount nConflictingFees = 0;
659 size_t nConflictingSize = 0;
660 uint64_t nConflictingCount = 0;
661 CTxMemPool::setEntries allConflicting;
663 // If we don't hold the lock allConflicting might be incomplete; the
664 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
665 // mempool consistency for us.
666 LOCK(pool.cs);
667 const bool fReplacementTransaction = setConflicts.size();
668 if (fReplacementTransaction)
670 CFeeRate newFeeRate(nModifiedFees, nSize);
671 std::set<uint256> setConflictsParents;
672 const int maxDescendantsToVisit = 100;
673 CTxMemPool::setEntries setIterConflicting;
674 for (const uint256 &hashConflicting : setConflicts)
676 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
677 if (mi == pool.mapTx.end())
678 continue;
680 // Save these to avoid repeated lookups
681 setIterConflicting.insert(mi);
683 // Don't allow the replacement to reduce the feerate of the
684 // mempool.
686 // We usually don't want to accept replacements with lower
687 // feerates than what they replaced as that would lower the
688 // feerate of the next block. Requiring that the feerate always
689 // be increased is also an easy-to-reason about way to prevent
690 // DoS attacks via replacements.
692 // The mining code doesn't (currently) take children into
693 // account (CPFP) so we only consider the feerates of
694 // transactions being directly replaced, not their indirect
695 // descendants. While that does mean high feerate children are
696 // ignored when deciding whether or not to replace, we do
697 // require the replacement to pay more overall fees too,
698 // mitigating most cases.
699 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
700 if (newFeeRate <= oldFeeRate)
702 return state.DoS(0, false,
703 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
704 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
705 hash.ToString(),
706 newFeeRate.ToString(),
707 oldFeeRate.ToString()));
710 for (const CTxIn &txin : mi->GetTx().vin)
712 setConflictsParents.insert(txin.prevout.hash);
715 nConflictingCount += mi->GetCountWithDescendants();
717 // This potentially overestimates the number of actual descendants
718 // but we just want to be conservative to avoid doing too much
719 // work.
720 if (nConflictingCount <= maxDescendantsToVisit) {
721 // If not too many to replace, then calculate the set of
722 // transactions that would have to be evicted
723 for (CTxMemPool::txiter it : setIterConflicting) {
724 pool.CalculateDescendants(it, allConflicting);
726 for (CTxMemPool::txiter it : allConflicting) {
727 nConflictingFees += it->GetModifiedFee();
728 nConflictingSize += it->GetTxSize();
730 } else {
731 return state.DoS(0, false,
732 REJECT_NONSTANDARD, "too many potential replacements", false,
733 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
734 hash.ToString(),
735 nConflictingCount,
736 maxDescendantsToVisit));
739 for (unsigned int j = 0; j < tx.vin.size(); j++)
741 // We don't want to accept replacements that require low
742 // feerate junk to be mined first. Ideally we'd keep track of
743 // the ancestor feerates and make the decision based on that,
744 // but for now requiring all new inputs to be confirmed works.
745 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
747 // Rather than check the UTXO set - potentially expensive -
748 // it's cheaper to just check if the new input refers to a
749 // tx that's in the mempool.
750 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
751 return state.DoS(0, false,
752 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
753 strprintf("replacement %s adds unconfirmed input, idx %d",
754 hash.ToString(), j));
758 // The replacement must pay greater fees than the transactions it
759 // replaces - if we did the bandwidth used by those conflicting
760 // transactions would not be paid for.
761 if (nModifiedFees < nConflictingFees)
763 return state.DoS(0, false,
764 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
765 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
766 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
769 // Finally in addition to paying more fees than the conflicts the
770 // new transaction must pay for its own bandwidth.
771 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
772 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
774 return state.DoS(0, false,
775 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
776 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
777 hash.ToString(),
778 FormatMoney(nDeltaFees),
779 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
783 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
784 if (!chainparams.RequireStandard()) {
785 scriptVerifyFlags = GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
788 // Check against previous transactions
789 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
790 PrecomputedTransactionData txdata(tx);
791 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, txdata)) {
792 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
793 // need to turn both off, and compare against just turning off CLEANSTACK
794 // to see if the failure is specifically due to witness validation.
795 CValidationState stateDummy; // Want reported failures to be from first CheckInputs
796 if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
797 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
798 // Only the witness is missing, so the transaction itself may be fine.
799 state.SetCorruptionPossible();
801 return false; // state filled in by CheckInputs
804 // Check again against the current block tip's script verification
805 // flags to cache our script execution flags. This is, of course,
806 // useless if the next block has different script flags from the
807 // previous one, but because the cache tracks script flags for us it
808 // will auto-invalidate and we'll just have a few blocks of extra
809 // misses on soft-fork activation.
811 // This is also useful in case of bugs in the standard flags that cause
812 // transactions to pass as valid when they're actually invalid. For
813 // instance the STRICTENC flag was incorrectly allowing certain
814 // CHECKSIG NOT scripts to pass, even though they were invalid.
816 // There is a similar check in CreateNewBlock() to prevent creating
817 // invalid blocks (using TestBlockValidity), however allowing such
818 // transactions into the mempool can be exploited as a DoS attack.
819 unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus());
820 if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata))
822 // If we're using promiscuousmempoolflags, we may hit this normally
823 // Check if current block has some flags that scriptVerifyFlags
824 // does not before printing an ominous warning
825 if (!(~scriptVerifyFlags & currentBlockScriptVerifyFlags)) {
826 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against latest-block but not STANDARD flags %s, %s",
827 __func__, hash.ToString(), FormatStateMessage(state));
828 } else {
829 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, false, txdata)) {
830 return error("%s: ConnectInputs failed against MANDATORY but not STANDARD flags due to promiscuous mempool %s, %s",
831 __func__, hash.ToString(), FormatStateMessage(state));
832 } else {
833 LogPrintf("Warning: -promiscuousmempool flags set to not include currently enforced soft forks, this may break mining or otherwise cause instability!\n");
838 // Remove conflicting transactions from the mempool
839 for (const CTxMemPool::txiter it : allConflicting)
841 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
842 it->GetTx().GetHash().ToString(),
843 hash.ToString(),
844 FormatMoney(nModifiedFees - nConflictingFees),
845 (int)nSize - (int)nConflictingSize);
846 if (plTxnReplaced)
847 plTxnReplaced->push_back(it->GetSharedTx());
849 pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
851 // This transaction should only count for fee estimation if it isn't a
852 // BIP 125 replacement transaction (may not be widely supported), the
853 // node is not behind, and the transaction is not dependent on any other
854 // transactions in the mempool.
855 bool validForFeeEstimation = !fReplacementTransaction && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
857 // Store transaction in memory
858 pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
860 // trim mempool and check if tx was trimmed
861 if (!fOverrideMempoolLimit) {
862 LimitMempoolSize(pool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
863 if (!pool.exists(hash))
864 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
868 GetMainSignals().TransactionAddedToMempool(ptx);
870 return true;
873 /** (try to) add transaction to memory pool with a specified acceptance time **/
874 static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
875 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
876 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
878 std::vector<COutPoint> coins_to_uncache;
879 bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, coins_to_uncache);
880 if (!res) {
881 for (const COutPoint& hashTx : coins_to_uncache)
882 pcoinsTip->Uncache(hashTx);
884 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
885 CValidationState stateDummy;
886 FlushStateToDisk(chainparams, stateDummy, FLUSH_STATE_PERIODIC);
887 return res;
890 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
891 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
892 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
894 const CChainParams& chainparams = Params();
895 return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, fLimitFree, pfMissingInputs, GetTime(), plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee);
898 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
899 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
901 CBlockIndex *pindexSlow = NULL;
903 LOCK(cs_main);
905 CTransactionRef ptx = mempool.get(hash);
906 if (ptx)
908 txOut = ptx;
909 return true;
912 if (fTxIndex) {
913 CDiskTxPos postx;
914 if (pblocktree->ReadTxIndex(hash, postx)) {
915 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
916 if (file.IsNull())
917 return error("%s: OpenBlockFile failed", __func__);
918 CBlockHeader header;
919 try {
920 file >> header;
921 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
922 file >> txOut;
923 } catch (const std::exception& e) {
924 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
926 hashBlock = header.GetHash();
927 if (txOut->GetHash() != hash)
928 return error("%s: txid mismatch", __func__);
929 return true;
933 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
934 const Coin& coin = AccessByTxid(*pcoinsTip, hash);
935 if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
938 if (pindexSlow) {
939 CBlock block;
940 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
941 for (const auto& tx : block.vtx) {
942 if (tx->GetHash() == hash) {
943 txOut = tx;
944 hashBlock = pindexSlow->GetBlockHash();
945 return true;
951 return false;
959 //////////////////////////////////////////////////////////////////////////////
961 // CBlock and CBlockIndex
964 static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
966 // Open history file to append
967 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
968 if (fileout.IsNull())
969 return error("WriteBlockToDisk: OpenBlockFile failed");
971 // Write index header
972 unsigned int nSize = GetSerializeSize(fileout, block);
973 fileout << FLATDATA(messageStart) << nSize;
975 // Write block
976 long fileOutPos = ftell(fileout.Get());
977 if (fileOutPos < 0)
978 return error("WriteBlockToDisk: ftell failed");
979 pos.nPos = (unsigned int)fileOutPos;
980 fileout << block;
982 return true;
985 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
987 block.SetNull();
989 // Open history file to read
990 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
991 if (filein.IsNull())
992 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
994 // Read block
995 try {
996 filein >> block;
998 catch (const std::exception& e) {
999 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1002 // Check the header
1003 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1004 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1006 return true;
1009 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1011 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1012 return false;
1013 if (block.GetHash() != pindex->GetBlockHash())
1014 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1015 pindex->ToString(), pindex->GetBlockPos().ToString());
1016 return true;
1019 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1021 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1022 // Force block reward to zero when right shift is undefined.
1023 if (halvings >= 64)
1024 return 0;
1026 CAmount nSubsidy = 50 * COIN;
1027 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1028 nSubsidy >>= halvings;
1029 return nSubsidy;
1032 bool IsInitialBlockDownload()
1034 const CChainParams& chainParams = Params();
1036 // Once this function has returned false, it must remain false.
1037 static std::atomic<bool> latchToFalse{false};
1038 // Optimization: pre-test latch before taking the lock.
1039 if (latchToFalse.load(std::memory_order_relaxed))
1040 return false;
1042 LOCK(cs_main);
1043 if (latchToFalse.load(std::memory_order_relaxed))
1044 return false;
1045 if (fImporting || fReindex)
1046 return true;
1047 if (chainActive.Tip() == NULL)
1048 return true;
1049 if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork))
1050 return true;
1051 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1052 return true;
1053 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1054 latchToFalse.store(true, std::memory_order_relaxed);
1055 return false;
1058 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1060 static void AlertNotify(const std::string& strMessage)
1062 uiInterface.NotifyAlertChanged();
1063 std::string strCmd = GetArg("-alertnotify", "");
1064 if (strCmd.empty()) return;
1066 // Alert text should be plain ascii coming from a trusted source, but to
1067 // be safe we first strip anything not in safeChars, then add single quotes around
1068 // the whole string before passing it to the shell:
1069 std::string singleQuote("'");
1070 std::string safeStatus = SanitizeString(strMessage);
1071 safeStatus = singleQuote+safeStatus+singleQuote;
1072 boost::replace_all(strCmd, "%s", safeStatus);
1074 boost::thread t(runCommand, strCmd); // thread runs free
1077 static void CheckForkWarningConditions()
1079 AssertLockHeld(cs_main);
1080 // Before we get past initial download, we cannot reliably alert about forks
1081 // (we assume we don't get stuck on a fork before finishing our initial sync)
1082 if (IsInitialBlockDownload())
1083 return;
1085 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1086 // of our head, drop it
1087 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1088 pindexBestForkTip = NULL;
1090 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1092 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
1094 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1095 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1096 AlertNotify(warning);
1098 if (pindexBestForkTip && pindexBestForkBase)
1100 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__,
1101 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1102 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1103 SetfLargeWorkForkFound(true);
1105 else
1107 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1108 SetfLargeWorkInvalidChainFound(true);
1111 else
1113 SetfLargeWorkForkFound(false);
1114 SetfLargeWorkInvalidChainFound(false);
1118 static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1120 AssertLockHeld(cs_main);
1121 // If we are on a fork that is sufficiently large, set a warning flag
1122 CBlockIndex* pfork = pindexNewForkTip;
1123 CBlockIndex* plonger = chainActive.Tip();
1124 while (pfork && pfork != plonger)
1126 while (plonger && plonger->nHeight > pfork->nHeight)
1127 plonger = plonger->pprev;
1128 if (pfork == plonger)
1129 break;
1130 pfork = pfork->pprev;
1133 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1134 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1135 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1136 // hash rate operating on the fork.
1137 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1138 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1139 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1140 if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
1141 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1142 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1144 pindexBestForkTip = pindexNewForkTip;
1145 pindexBestForkBase = pfork;
1148 CheckForkWarningConditions();
1151 void static InvalidChainFound(CBlockIndex* pindexNew)
1153 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1154 pindexBestInvalid = pindexNew;
1156 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1157 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1158 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1159 pindexNew->GetBlockTime()));
1160 CBlockIndex *tip = chainActive.Tip();
1161 assert (tip);
1162 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1163 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1164 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1165 CheckForkWarningConditions();
1168 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1169 if (!state.CorruptionPossible()) {
1170 pindex->nStatus |= BLOCK_FAILED_VALID;
1171 setDirtyBlockIndex.insert(pindex);
1172 setBlockIndexCandidates.erase(pindex);
1173 InvalidChainFound(pindex);
1177 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1179 // mark inputs spent
1180 if (!tx.IsCoinBase()) {
1181 txundo.vprevout.reserve(tx.vin.size());
1182 for (const CTxIn &txin : tx.vin) {
1183 txundo.vprevout.emplace_back();
1184 bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1185 assert(is_spent);
1188 // add outputs
1189 AddCoins(inputs, tx, nHeight);
1192 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1194 CTxUndo txundo;
1195 UpdateCoins(tx, inputs, txundo, nHeight);
1198 bool CScriptCheck::operator()() {
1199 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1200 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1201 return VerifyScript(scriptSig, scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), &error);
1204 int GetSpendHeight(const CCoinsViewCache& inputs)
1206 LOCK(cs_main);
1207 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1208 return pindexPrev->nHeight + 1;
1212 static CuckooCache::cache<uint256, SignatureCacheHasher> scriptExecutionCache;
1213 static uint256 scriptExecutionCacheNonce(GetRandHash());
1215 void InitScriptExecutionCache() {
1216 // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1217 // setup_bytes creates the minimum possible cache (2 elements).
1218 size_t nMaxCacheSize = std::min(std::max((int64_t)0, GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
1219 size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
1220 LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1221 (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1225 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
1226 * This does not modify the UTXO set.
1228 * If pvChecks is not NULL, script checks are pushed onto it instead of being performed inline. Any
1229 * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
1230 * not pushed onto pvChecks/run.
1232 * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
1233 * which are matched. This is useful for checking blocks where we will likely never need the cache
1234 * entry again.
1236 * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
1238 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)
1240 if (!tx.IsCoinBase())
1242 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1243 return false;
1245 if (pvChecks)
1246 pvChecks->reserve(tx.vin.size());
1248 // The first loop above does all the inexpensive checks.
1249 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1250 // Helps prevent CPU exhaustion attacks.
1252 // Skip script verification when connecting blocks under the
1253 // assumevalid block. Assuming the assumevalid block is valid this
1254 // is safe because block merkle hashes are still computed and checked,
1255 // Of course, if an assumed valid block is invalid due to false scriptSigs
1256 // this optimization would allow an invalid chain to be accepted.
1257 if (fScriptChecks) {
1258 // First check if script executions have been cached with the same
1259 // flags. Note that this assumes that the inputs provided are
1260 // correct (ie that the transaction hash which is in tx's prevouts
1261 // properly commits to the scriptPubKey in the inputs view of that
1262 // transaction).
1263 uint256 hashCacheEntry;
1264 // We only use the first 19 bytes of nonce to avoid a second SHA
1265 // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
1266 static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
1267 CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1268 AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1269 if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1270 return true;
1273 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1274 const COutPoint &prevout = tx.vin[i].prevout;
1275 const Coin& coin = inputs.AccessCoin(prevout);
1276 assert(!coin.IsSpent());
1278 // We very carefully only pass in things to CScriptCheck which
1279 // are clearly committed to by tx' witness hash. This provides
1280 // a sanity check that our caching is not introducing consensus
1281 // failures through additional data in, eg, the coins being
1282 // spent being checked as a part of CScriptCheck.
1283 const CScript& scriptPubKey = coin.out.scriptPubKey;
1284 const CAmount amount = coin.out.nValue;
1286 // Verify signature
1287 CScriptCheck check(scriptPubKey, amount, tx, i, flags, cacheSigStore, &txdata);
1288 if (pvChecks) {
1289 pvChecks->push_back(CScriptCheck());
1290 check.swap(pvChecks->back());
1291 } else if (!check()) {
1292 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1293 // Check whether the failure was caused by a
1294 // non-mandatory script verification check, such as
1295 // non-standard DER encodings or non-null dummy
1296 // arguments; if so, don't trigger DoS protection to
1297 // avoid splitting the network between upgraded and
1298 // non-upgraded nodes.
1299 CScriptCheck check2(scriptPubKey, amount, tx, i,
1300 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1301 if (check2())
1302 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1304 // Failures of other flags indicate a transaction that is
1305 // invalid in new blocks, e.g. an invalid P2SH. We DoS ban
1306 // such nodes as they are not following the protocol. That
1307 // said during an upgrade careful thought should be taken
1308 // as to the correct behavior - we may want to continue
1309 // peering with non-upgraded nodes even after soft-fork
1310 // super-majority signaling has occurred.
1311 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1315 if (cacheFullScriptStore && !pvChecks) {
1316 // We executed all of the provided scripts, and were told to
1317 // cache the result. Do so now.
1318 scriptExecutionCache.insert(hashCacheEntry);
1323 return true;
1326 namespace {
1328 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1330 // Open history file to append
1331 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1332 if (fileout.IsNull())
1333 return error("%s: OpenUndoFile failed", __func__);
1335 // Write index header
1336 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1337 fileout << FLATDATA(messageStart) << nSize;
1339 // Write undo data
1340 long fileOutPos = ftell(fileout.Get());
1341 if (fileOutPos < 0)
1342 return error("%s: ftell failed", __func__);
1343 pos.nPos = (unsigned int)fileOutPos;
1344 fileout << blockundo;
1346 // calculate & write checksum
1347 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1348 hasher << hashBlock;
1349 hasher << blockundo;
1350 fileout << hasher.GetHash();
1352 return true;
1355 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1357 // Open history file to read
1358 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1359 if (filein.IsNull())
1360 return error("%s: OpenUndoFile failed", __func__);
1362 // Read block
1363 uint256 hashChecksum;
1364 CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1365 try {
1366 verifier << hashBlock;
1367 verifier >> blockundo;
1368 filein >> hashChecksum;
1370 catch (const std::exception& e) {
1371 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1374 // Verify checksum
1375 if (hashChecksum != verifier.GetHash())
1376 return error("%s: Checksum mismatch", __func__);
1378 return true;
1381 /** Abort with a message */
1382 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1384 SetMiscWarning(strMessage);
1385 LogPrintf("*** %s\n", strMessage);
1386 uiInterface.ThreadSafeMessageBox(
1387 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1388 "", CClientUIInterface::MSG_ERROR);
1389 StartShutdown();
1390 return false;
1393 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1395 AbortNode(strMessage, userMessage);
1396 return state.Error(strMessage);
1399 } // namespace
1401 enum DisconnectResult
1403 DISCONNECT_OK, // All good.
1404 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
1405 DISCONNECT_FAILED // Something else went wrong.
1409 * Restore the UTXO in a Coin at a given COutPoint
1410 * @param undo The Coin to be restored.
1411 * @param view The coins view to which to apply the changes.
1412 * @param out The out point that corresponds to the tx input.
1413 * @return A DisconnectResult as an int
1415 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1417 bool fClean = true;
1419 if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1421 if (undo.nHeight == 0) {
1422 // Missing undo metadata (height and coinbase). Older versions included this
1423 // information only in undo records for the last spend of a transactions'
1424 // outputs. This implies that it must be present for some other output of the same tx.
1425 const Coin& alternate = AccessByTxid(view, out.hash);
1426 if (!alternate.IsSpent()) {
1427 undo.nHeight = alternate.nHeight;
1428 undo.fCoinBase = alternate.fCoinBase;
1429 } else {
1430 return DISCONNECT_FAILED; // adding output for transaction without known metadata
1433 // The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
1434 // sure that the coin did not already exist in the cache. As we have queried for that above
1435 // using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
1436 // it is an overwrite.
1437 view.AddCoin(out, std::move(undo), !fClean);
1439 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1442 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1443 * When FAILED is returned, view is left in an indeterminate state. */
1444 static DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1446 bool fClean = true;
1448 CBlockUndo blockUndo;
1449 CDiskBlockPos pos = pindex->GetUndoPos();
1450 if (pos.IsNull()) {
1451 error("DisconnectBlock(): no undo data available");
1452 return DISCONNECT_FAILED;
1454 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) {
1455 error("DisconnectBlock(): failure reading undo data");
1456 return DISCONNECT_FAILED;
1459 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1460 error("DisconnectBlock(): block and undo data inconsistent");
1461 return DISCONNECT_FAILED;
1464 // undo transactions in reverse order
1465 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1466 const CTransaction &tx = *(block.vtx[i]);
1467 uint256 hash = tx.GetHash();
1468 bool is_coinbase = tx.IsCoinBase();
1470 // Check that all outputs are available and match the outputs in the block itself
1471 // exactly.
1472 for (size_t o = 0; o < tx.vout.size(); o++) {
1473 if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1474 COutPoint out(hash, o);
1475 Coin coin;
1476 bool is_spent = view.SpendCoin(out, &coin);
1477 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1478 fClean = false; // transaction output mismatch
1483 // restore inputs
1484 if (i > 0) { // not coinbases
1485 CTxUndo &txundo = blockUndo.vtxundo[i-1];
1486 if (txundo.vprevout.size() != tx.vin.size()) {
1487 error("DisconnectBlock(): transaction and undo data inconsistent");
1488 return DISCONNECT_FAILED;
1490 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1491 const COutPoint &out = tx.vin[j].prevout;
1492 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1493 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1494 fClean = fClean && res != DISCONNECT_UNCLEAN;
1496 // At this point, all of txundo.vprevout should have been moved out.
1500 // move best block pointer to prevout block
1501 view.SetBestBlock(pindex->pprev->GetBlockHash());
1503 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1506 void static FlushBlockFile(bool fFinalize = false)
1508 LOCK(cs_LastBlockFile);
1510 CDiskBlockPos posOld(nLastBlockFile, 0);
1512 FILE *fileOld = OpenBlockFile(posOld);
1513 if (fileOld) {
1514 if (fFinalize)
1515 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1516 FileCommit(fileOld);
1517 fclose(fileOld);
1520 fileOld = OpenUndoFile(posOld);
1521 if (fileOld) {
1522 if (fFinalize)
1523 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1524 FileCommit(fileOld);
1525 fclose(fileOld);
1529 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1531 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1533 void ThreadScriptCheck() {
1534 RenameThread("bitcoin-scriptch");
1535 scriptcheckqueue.Thread();
1538 // Protected by cs_main
1539 VersionBitsCache versionbitscache;
1541 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1543 LOCK(cs_main);
1544 int32_t nVersion = VERSIONBITS_TOP_BITS;
1546 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1547 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1548 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1549 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1553 return nVersion;
1557 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1559 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1561 private:
1562 int bit;
1564 public:
1565 WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1567 int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1568 int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1569 int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1570 int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1572 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1574 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1575 ((pindex->nVersion >> bit) & 1) != 0 &&
1576 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1580 // Protected by cs_main
1581 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1583 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) {
1584 AssertLockHeld(cs_main);
1586 // BIP16 didn't become active until Apr 1 2012
1587 int64_t nBIP16SwitchTime = 1333238400;
1588 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1590 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1592 // Start enforcing the DERSIG (BIP66) rule
1593 if (pindex->nHeight >= consensusparams.BIP66Height) {
1594 flags |= SCRIPT_VERIFY_DERSIG;
1597 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1598 if (pindex->nHeight >= consensusparams.BIP65Height) {
1599 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1602 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1603 if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1604 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1607 // Start enforcing WITNESS rules using versionbits logic.
1608 if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
1609 flags |= SCRIPT_VERIFY_WITNESS;
1610 flags |= SCRIPT_VERIFY_NULLDUMMY;
1613 return flags;
1618 static int64_t nTimeCheck = 0;
1619 static int64_t nTimeForks = 0;
1620 static int64_t nTimeVerify = 0;
1621 static int64_t nTimeConnect = 0;
1622 static int64_t nTimeIndex = 0;
1623 static int64_t nTimeCallbacks = 0;
1624 static int64_t nTimeTotal = 0;
1626 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1627 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1628 * can fail if those validity checks fail (among other reasons). */
1629 static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1630 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false)
1632 AssertLockHeld(cs_main);
1633 assert(pindex);
1634 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1635 assert((pindex->phashBlock == NULL) ||
1636 (*pindex->phashBlock == block.GetHash()));
1637 int64_t nTimeStart = GetTimeMicros();
1639 // Check it again in case a previous version let a bad block in
1640 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1641 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1643 // verify that the view's current state corresponds to the previous block
1644 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1645 assert(hashPrevBlock == view.GetBestBlock());
1647 // Special case for the genesis block, skipping connection of its transactions
1648 // (its coinbase is unspendable)
1649 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1650 if (!fJustCheck)
1651 view.SetBestBlock(pindex->GetBlockHash());
1652 return true;
1655 bool fScriptChecks = true;
1656 if (!hashAssumeValid.IsNull()) {
1657 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1658 // A suitable default value is included with the software and updated from time to time. Because validity
1659 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1660 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1661 // effectively caching the result of part of the verification.
1662 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1663 if (it != mapBlockIndex.end()) {
1664 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1665 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1666 pindexBestHeader->nChainWork >= UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
1667 // This block is a member of the assumed verified chain and an ancestor of the best header.
1668 // The equivalent time check discourages hash power from extorting the network via DOS attack
1669 // into accepting an invalid block through telling users they must manually set assumevalid.
1670 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1671 // it hard to hide the implication of the demand. This also avoids having release candidates
1672 // that are hardly doing any signature verification at all in testing without having to
1673 // artificially set the default assumed verified block further back.
1674 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1675 // least as good as the expected chain.
1676 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1681 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1682 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
1684 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1685 // unless those are already completely spent.
1686 // If such overwrites are allowed, coinbases and transactions depending upon those
1687 // can be duplicated to remove the ability to spend the first instance -- even after
1688 // being sent to another address.
1689 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1690 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1691 // already refuses previously-known transaction ids entirely.
1692 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1693 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1694 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1695 // initial block download.
1696 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1697 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1698 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1700 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1701 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1702 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1703 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1704 // duplicate transactions descending from the known pairs either.
1705 // 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.
1706 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1707 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1708 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1710 if (fEnforceBIP30) {
1711 for (const auto& tx : block.vtx) {
1712 for (size_t o = 0; o < tx->vout.size(); o++) {
1713 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
1714 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1715 REJECT_INVALID, "bad-txns-BIP30");
1721 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1722 int nLockTimeFlags = 0;
1723 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1724 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1727 // Get the script flags for this block
1728 unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
1730 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1731 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
1733 CBlockUndo blockundo;
1735 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1737 std::vector<int> prevheights;
1738 CAmount nFees = 0;
1739 int nInputs = 0;
1740 int64_t nSigOpsCost = 0;
1741 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1742 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1743 vPos.reserve(block.vtx.size());
1744 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1745 std::vector<PrecomputedTransactionData> txdata;
1746 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1747 for (unsigned int i = 0; i < block.vtx.size(); i++)
1749 const CTransaction &tx = *(block.vtx[i]);
1751 nInputs += tx.vin.size();
1753 if (!tx.IsCoinBase())
1755 if (!view.HaveInputs(tx))
1756 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1757 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1759 // Check that transaction is BIP68 final
1760 // BIP68 lock checks (as opposed to nLockTime checks) must
1761 // be in ConnectBlock because they require the UTXO set
1762 prevheights.resize(tx.vin.size());
1763 for (size_t j = 0; j < tx.vin.size(); j++) {
1764 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
1767 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1768 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1769 REJECT_INVALID, "bad-txns-nonfinal");
1773 // GetTransactionSigOpCost counts 3 types of sigops:
1774 // * legacy (always)
1775 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1776 // * witness (when witness enabled in flags and excludes coinbase)
1777 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1778 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1779 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1780 REJECT_INVALID, "bad-blk-sigops");
1782 txdata.emplace_back(tx);
1783 if (!tx.IsCoinBase())
1785 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1787 std::vector<CScriptCheck> vChecks;
1788 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1789 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : NULL))
1790 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1791 tx.GetHash().ToString(), FormatStateMessage(state));
1792 control.Add(vChecks);
1795 CTxUndo undoDummy;
1796 if (i > 0) {
1797 blockundo.vtxundo.push_back(CTxUndo());
1799 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1801 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1802 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1804 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1805 LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001);
1807 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1808 if (block.vtx[0]->GetValueOut() > blockReward)
1809 return state.DoS(100,
1810 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1811 block.vtx[0]->GetValueOut(), blockReward),
1812 REJECT_INVALID, "bad-cb-amount");
1814 if (!control.Wait())
1815 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1816 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1817 LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime4 - nTime2), nInputs <= 1 ? 0 : 0.001 * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * 0.000001);
1819 if (fJustCheck)
1820 return true;
1822 // Write undo information to disk
1823 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1825 if (pindex->GetUndoPos().IsNull()) {
1826 CDiskBlockPos _pos;
1827 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1828 return error("ConnectBlock(): FindUndoPos failed");
1829 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1830 return AbortNode(state, "Failed to write undo data");
1832 // update nUndoPos in block index
1833 pindex->nUndoPos = _pos.nPos;
1834 pindex->nStatus |= BLOCK_HAVE_UNDO;
1837 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1838 setDirtyBlockIndex.insert(pindex);
1841 if (fTxIndex)
1842 if (!pblocktree->WriteTxIndex(vPos))
1843 return AbortNode(state, "Failed to write transaction index");
1845 // add this block to the view's block chain
1846 view.SetBestBlock(pindex->GetBlockHash());
1848 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1849 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
1851 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1852 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
1854 return true;
1858 * Update the on-disk chain state.
1859 * The caches and indexes are flushed depending on the mode we're called with
1860 * if they're too large, if it's been a while since the last write,
1861 * or always and in all cases if we're in prune mode and are deleting files.
1863 bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
1864 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
1865 LOCK2(cs_main, cs_LastBlockFile);
1866 static int64_t nLastWrite = 0;
1867 static int64_t nLastFlush = 0;
1868 static int64_t nLastSetChain = 0;
1869 std::set<int> setFilesToPrune;
1870 bool fFlushForPrune = false;
1871 try {
1872 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1873 if (nManualPruneHeight > 0) {
1874 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
1875 } else {
1876 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1877 fCheckForPruning = false;
1879 if (!setFilesToPrune.empty()) {
1880 fFlushForPrune = true;
1881 if (!fHavePruned) {
1882 pblocktree->WriteFlag("prunedblockfiles", true);
1883 fHavePruned = true;
1887 int64_t nNow = GetTimeMicros();
1888 // Avoid writing/flushing immediately after startup.
1889 if (nLastWrite == 0) {
1890 nLastWrite = nNow;
1892 if (nLastFlush == 0) {
1893 nLastFlush = nNow;
1895 if (nLastSetChain == 0) {
1896 nLastSetChain = nNow;
1898 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1899 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1900 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
1901 // 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).
1902 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
1903 // The cache is over the limit, we have to write now.
1904 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
1905 // 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.
1906 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1907 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1908 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1909 // Combine all conditions that result in a full cache flush.
1910 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1911 // Write blocks and block index to disk.
1912 if (fDoFullFlush || fPeriodicWrite) {
1913 // Depend on nMinDiskSpace to ensure we can write block index
1914 if (!CheckDiskSpace(0))
1915 return state.Error("out of disk space");
1916 // First make sure all block and undo data is flushed to disk.
1917 FlushBlockFile();
1918 // Then update all block file information (which may refer to block and undo files).
1920 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1921 vFiles.reserve(setDirtyFileInfo.size());
1922 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1923 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
1924 setDirtyFileInfo.erase(it++);
1926 std::vector<const CBlockIndex*> vBlocks;
1927 vBlocks.reserve(setDirtyBlockIndex.size());
1928 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1929 vBlocks.push_back(*it);
1930 setDirtyBlockIndex.erase(it++);
1932 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1933 return AbortNode(state, "Failed to write to block index database");
1936 // Finally remove any pruned files
1937 if (fFlushForPrune)
1938 UnlinkPrunedFiles(setFilesToPrune);
1939 nLastWrite = nNow;
1941 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1942 if (fDoFullFlush) {
1943 // Typical Coin structures on disk are around 48 bytes in size.
1944 // Pushing a new one to the database can cause it to be written
1945 // twice (once in the log, and once in the tables). This is already
1946 // an overestimation, as most will delete an existing entry or
1947 // overwrite one. Still, use a conservative safety factor of 2.
1948 if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
1949 return state.Error("out of disk space");
1950 // Flush the chainstate (which may refer to block index entries).
1951 if (!pcoinsTip->Flush())
1952 return AbortNode(state, "Failed to write to coin database");
1953 nLastFlush = nNow;
1955 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
1956 // Update best block in wallet (so we can detect restored wallets).
1957 GetMainSignals().SetBestChain(chainActive.GetLocator());
1958 nLastSetChain = nNow;
1960 } catch (const std::runtime_error& e) {
1961 return AbortNode(state, std::string("System error while flushing: ") + e.what());
1963 return true;
1966 void FlushStateToDisk() {
1967 CValidationState state;
1968 const CChainParams& chainparams = Params();
1969 FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
1972 void PruneAndFlush() {
1973 CValidationState state;
1974 fCheckForPruning = true;
1975 const CChainParams& chainparams = Params();
1976 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
1979 static void DoWarning(const std::string& strWarning)
1981 static bool fWarned = false;
1982 SetMiscWarning(strWarning);
1983 if (!fWarned) {
1984 AlertNotify(strWarning);
1985 fWarned = true;
1989 /** Update chainActive and related internal data structures. */
1990 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
1991 chainActive.SetTip(pindexNew);
1993 // New best block
1994 mempool.AddTransactionsUpdated(1);
1996 cvBlockChange.notify_all();
1998 std::vector<std::string> warningMessages;
1999 if (!IsInitialBlockDownload())
2001 int nUpgraded = 0;
2002 const CBlockIndex* pindex = chainActive.Tip();
2003 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2004 WarningBitsConditionChecker checker(bit);
2005 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2006 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2007 const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2008 if (state == THRESHOLD_ACTIVE) {
2009 DoWarning(strWarning);
2010 } else {
2011 warningMessages.push_back(strWarning);
2015 // Check the version of the last 100 blocks to see if we need to upgrade:
2016 for (int i = 0; i < 100 && pindex != NULL; i++)
2018 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2019 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2020 ++nUpgraded;
2021 pindex = pindex->pprev;
2023 if (nUpgraded > 0)
2024 warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
2025 if (nUpgraded > 100/2)
2027 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2028 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2029 DoWarning(strWarning);
2032 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
2033 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
2034 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2035 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2036 GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2037 if (!warningMessages.empty())
2038 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2039 LogPrintf("\n");
2043 /** Disconnect chainActive's tip.
2044 * After calling, the mempool will be in an inconsistent state, with
2045 * transactions from disconnected blocks being added to disconnectpool. You
2046 * should make the mempool consistent again by calling UpdateMempoolForReorg.
2047 * with cs_main held.
2049 * If disconnectpool is NULL, then no disconnected transactions are added to
2050 * disconnectpool (note that the caller is responsible for mempool consistency
2051 * in any case).
2053 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
2055 CBlockIndex *pindexDelete = chainActive.Tip();
2056 assert(pindexDelete);
2057 // Read block from disk.
2058 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2059 CBlock& block = *pblock;
2060 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2061 return AbortNode(state, "Failed to read block");
2062 // Apply the block atomically to the chain state.
2063 int64_t nStart = GetTimeMicros();
2065 CCoinsViewCache view(pcoinsTip);
2066 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2067 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2068 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2069 bool flushed = view.Flush();
2070 assert(flushed);
2072 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2073 // Write the chain state to disk, if necessary.
2074 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2075 return false;
2077 if (disconnectpool) {
2078 // Save transactions to re-add to mempool at end of reorg
2079 for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2080 disconnectpool->addTransaction(*it);
2082 while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2083 // Drop the earliest entry, and remove its children from the mempool.
2084 auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2085 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
2086 disconnectpool->removeEntry(it);
2090 // Update chainActive and related variables.
2091 UpdateTip(pindexDelete->pprev, chainparams);
2092 // Let wallets know transactions went from 1-confirmed to
2093 // 0-confirmed or conflicted:
2094 GetMainSignals().BlockDisconnected(pblock);
2095 return true;
2098 static int64_t nTimeReadFromDisk = 0;
2099 static int64_t nTimeConnectTotal = 0;
2100 static int64_t nTimeFlush = 0;
2101 static int64_t nTimeChainState = 0;
2102 static int64_t nTimePostConnect = 0;
2104 struct PerBlockConnectTrace {
2105 CBlockIndex* pindex = NULL;
2106 std::shared_ptr<const CBlock> pblock;
2107 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
2108 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
2111 * Used to track blocks whose transactions were applied to the UTXO state as a
2112 * part of a single ActivateBestChainStep call.
2114 * This class also tracks transactions that are removed from the mempool as
2115 * conflicts (per block) and can be used to pass all those transactions
2116 * through SyncTransaction.
2118 * This class assumes (and asserts) that the conflicted transactions for a given
2119 * block are added via mempool callbacks prior to the BlockConnected() associated
2120 * with those transactions. If any transactions are marked conflicted, it is
2121 * assumed that an associated block will always be added.
2123 * This class is single-use, once you call GetBlocksConnected() you have to throw
2124 * it away and make a new one.
2126 class ConnectTrace {
2127 private:
2128 std::vector<PerBlockConnectTrace> blocksConnected;
2129 CTxMemPool &pool;
2131 public:
2132 ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
2133 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2136 ~ConnectTrace() {
2137 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2140 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2141 assert(!blocksConnected.back().pindex);
2142 assert(pindex);
2143 assert(pblock);
2144 blocksConnected.back().pindex = pindex;
2145 blocksConnected.back().pblock = std::move(pblock);
2146 blocksConnected.emplace_back();
2149 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2150 // We always keep one extra block at the end of our list because
2151 // blocks are added after all the conflicted transactions have
2152 // been filled in. Thus, the last entry should always be an empty
2153 // one waiting for the transactions from the next block. We pop
2154 // the last entry here to make sure the list we return is sane.
2155 assert(!blocksConnected.back().pindex);
2156 assert(blocksConnected.back().conflictedTxs->empty());
2157 blocksConnected.pop_back();
2158 return blocksConnected;
2161 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
2162 assert(!blocksConnected.back().pindex);
2163 if (reason == MemPoolRemovalReason::CONFLICT) {
2164 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2170 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2171 * corresponding to pindexNew, to bypass loading it again from disk.
2173 * The block is added to connectTrace if connection succeeds.
2175 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
2177 assert(pindexNew->pprev == chainActive.Tip());
2178 // Read block from disk.
2179 int64_t nTime1 = GetTimeMicros();
2180 std::shared_ptr<const CBlock> pthisBlock;
2181 if (!pblock) {
2182 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2183 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2184 return AbortNode(state, "Failed to read block");
2185 pthisBlock = pblockNew;
2186 } else {
2187 pthisBlock = pblock;
2189 const CBlock& blockConnecting = *pthisBlock;
2190 // Apply the block atomically to the chain state.
2191 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2192 int64_t nTime3;
2193 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2195 CCoinsViewCache view(pcoinsTip);
2196 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2197 GetMainSignals().BlockChecked(blockConnecting, state);
2198 if (!rv) {
2199 if (state.IsInvalid())
2200 InvalidBlockFound(pindexNew, state);
2201 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2203 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2204 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2205 bool flushed = view.Flush();
2206 assert(flushed);
2208 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2209 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2210 // Write the chain state to disk, if necessary.
2211 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2212 return false;
2213 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2214 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2215 // Remove conflicting transactions from the mempool.;
2216 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2217 disconnectpool.removeForBlock(blockConnecting.vtx);
2218 // Update chainActive & related variables.
2219 UpdateTip(pindexNew, chainparams);
2221 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2222 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2223 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2225 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2226 return true;
2230 * Return the tip of the chain with the most work in it, that isn't
2231 * known to be invalid (it's however far from certain to be valid).
2233 static CBlockIndex* FindMostWorkChain() {
2234 do {
2235 CBlockIndex *pindexNew = NULL;
2237 // Find the best candidate header.
2239 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2240 if (it == setBlockIndexCandidates.rend())
2241 return NULL;
2242 pindexNew = *it;
2245 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2246 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2247 CBlockIndex *pindexTest = pindexNew;
2248 bool fInvalidAncestor = false;
2249 while (pindexTest && !chainActive.Contains(pindexTest)) {
2250 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2252 // Pruned nodes may have entries in setBlockIndexCandidates for
2253 // which block files have been deleted. Remove those as candidates
2254 // for the most work chain if we come across them; we can't switch
2255 // to a chain unless we have all the non-active-chain parent blocks.
2256 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2257 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2258 if (fFailedChain || fMissingData) {
2259 // Candidate chain is not usable (either invalid or missing data)
2260 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2261 pindexBestInvalid = pindexNew;
2262 CBlockIndex *pindexFailed = pindexNew;
2263 // Remove the entire chain from the set.
2264 while (pindexTest != pindexFailed) {
2265 if (fFailedChain) {
2266 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2267 } else if (fMissingData) {
2268 // If we're missing data, then add back to mapBlocksUnlinked,
2269 // so that if the block arrives in the future we can try adding
2270 // to setBlockIndexCandidates again.
2271 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2273 setBlockIndexCandidates.erase(pindexFailed);
2274 pindexFailed = pindexFailed->pprev;
2276 setBlockIndexCandidates.erase(pindexTest);
2277 fInvalidAncestor = true;
2278 break;
2280 pindexTest = pindexTest->pprev;
2282 if (!fInvalidAncestor)
2283 return pindexNew;
2284 } while(true);
2287 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2288 static void PruneBlockIndexCandidates() {
2289 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2290 // reorganization to a better block fails.
2291 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2292 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2293 setBlockIndexCandidates.erase(it++);
2295 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2296 assert(!setBlockIndexCandidates.empty());
2300 * Try to make some progress towards making pindexMostWork the active block.
2301 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2303 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2305 AssertLockHeld(cs_main);
2306 const CBlockIndex *pindexOldTip = chainActive.Tip();
2307 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2309 // Disconnect active blocks which are no longer in the best chain.
2310 bool fBlocksDisconnected = false;
2311 DisconnectedBlockTransactions disconnectpool;
2312 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2313 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2314 // This is likely a fatal error, but keep the mempool consistent,
2315 // just in case. Only remove from the mempool in this case.
2316 UpdateMempoolForReorg(disconnectpool, false);
2317 return false;
2319 fBlocksDisconnected = true;
2322 // Build list of new blocks to connect.
2323 std::vector<CBlockIndex*> vpindexToConnect;
2324 bool fContinue = true;
2325 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2326 while (fContinue && nHeight != pindexMostWork->nHeight) {
2327 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2328 // a few blocks along the way.
2329 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2330 vpindexToConnect.clear();
2331 vpindexToConnect.reserve(nTargetHeight - nHeight);
2332 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2333 while (pindexIter && pindexIter->nHeight != nHeight) {
2334 vpindexToConnect.push_back(pindexIter);
2335 pindexIter = pindexIter->pprev;
2337 nHeight = nTargetHeight;
2339 // Connect new blocks.
2340 for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
2341 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2342 if (state.IsInvalid()) {
2343 // The block violates a consensus rule.
2344 if (!state.CorruptionPossible())
2345 InvalidChainFound(vpindexToConnect.back());
2346 state = CValidationState();
2347 fInvalidFound = true;
2348 fContinue = false;
2349 break;
2350 } else {
2351 // A system error occurred (disk space, database error, ...).
2352 // Make the mempool consistent with the current tip, just in case
2353 // any observers try to use it before shutdown.
2354 UpdateMempoolForReorg(disconnectpool, false);
2355 return false;
2357 } else {
2358 PruneBlockIndexCandidates();
2359 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2360 // We're in a better position than we were. Return temporarily to release the lock.
2361 fContinue = false;
2362 break;
2368 if (fBlocksDisconnected) {
2369 // If any blocks were disconnected, disconnectpool may be non empty. Add
2370 // any disconnected transactions back to the mempool.
2371 UpdateMempoolForReorg(disconnectpool, true);
2373 mempool.check(pcoinsTip);
2375 // Callbacks/notifications for a new best chain.
2376 if (fInvalidFound)
2377 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2378 else
2379 CheckForkWarningConditions();
2381 return true;
2384 static void NotifyHeaderTip() {
2385 bool fNotify = false;
2386 bool fInitialBlockDownload = false;
2387 static CBlockIndex* pindexHeaderOld = NULL;
2388 CBlockIndex* pindexHeader = NULL;
2390 LOCK(cs_main);
2391 pindexHeader = pindexBestHeader;
2393 if (pindexHeader != pindexHeaderOld) {
2394 fNotify = true;
2395 fInitialBlockDownload = IsInitialBlockDownload();
2396 pindexHeaderOld = pindexHeader;
2399 // Send block tip changed notifications without cs_main
2400 if (fNotify) {
2401 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2406 * Make the best chain active, in multiple steps. The result is either failure
2407 * or an activated best chain. pblock is either NULL or a pointer to a block
2408 * that is already loaded (to avoid loading it again from disk).
2410 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2411 // Note that while we're often called here from ProcessNewBlock, this is
2412 // far from a guarantee. Things in the P2P/RPC will often end up calling
2413 // us in the middle of ProcessNewBlock - do not assume pblock is set
2414 // sanely for performance or correctness!
2416 CBlockIndex *pindexMostWork = NULL;
2417 CBlockIndex *pindexNewTip = NULL;
2418 int nStopAtHeight = GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2419 do {
2420 boost::this_thread::interruption_point();
2421 if (ShutdownRequested())
2422 break;
2424 const CBlockIndex *pindexFork;
2425 bool fInitialDownload;
2427 LOCK(cs_main);
2428 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2430 CBlockIndex *pindexOldTip = chainActive.Tip();
2431 if (pindexMostWork == NULL) {
2432 pindexMostWork = FindMostWorkChain();
2435 // Whether we have anything to do at all.
2436 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2437 return true;
2439 bool fInvalidFound = false;
2440 std::shared_ptr<const CBlock> nullBlockPtr;
2441 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2442 return false;
2444 if (fInvalidFound) {
2445 // Wipe cache, we may need another branch now.
2446 pindexMostWork = NULL;
2448 pindexNewTip = chainActive.Tip();
2449 pindexFork = chainActive.FindFork(pindexOldTip);
2450 fInitialDownload = IsInitialBlockDownload();
2452 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2453 assert(trace.pblock && trace.pindex);
2454 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, *trace.conflictedTxs);
2457 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2459 // Notifications/callbacks that can run without cs_main
2461 // Notify external listeners about the new tip.
2462 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2464 // Always notify the UI if a new block tip was connected
2465 if (pindexFork != pindexNewTip) {
2466 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2469 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2470 } while (pindexNewTip != pindexMostWork);
2471 CheckBlockIndex(chainparams.GetConsensus());
2473 // Write changes periodically to disk, after relay.
2474 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
2475 return false;
2478 return true;
2482 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2485 LOCK(cs_main);
2486 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2487 // Nothing to do, this block is not at the tip.
2488 return true;
2490 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2491 // The chain has been extended since the last call, reset the counter.
2492 nBlockReverseSequenceId = -1;
2494 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2495 setBlockIndexCandidates.erase(pindex);
2496 pindex->nSequenceId = nBlockReverseSequenceId;
2497 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2498 // We can't keep reducing the counter if somebody really wants to
2499 // call preciousblock 2**31-1 times on the same set of tips...
2500 nBlockReverseSequenceId--;
2502 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2503 setBlockIndexCandidates.insert(pindex);
2504 PruneBlockIndexCandidates();
2508 return ActivateBestChain(state, params);
2511 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2513 AssertLockHeld(cs_main);
2515 // Mark the block itself as invalid.
2516 pindex->nStatus |= BLOCK_FAILED_VALID;
2517 setDirtyBlockIndex.insert(pindex);
2518 setBlockIndexCandidates.erase(pindex);
2520 DisconnectedBlockTransactions disconnectpool;
2521 while (chainActive.Contains(pindex)) {
2522 CBlockIndex *pindexWalk = chainActive.Tip();
2523 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2524 setDirtyBlockIndex.insert(pindexWalk);
2525 setBlockIndexCandidates.erase(pindexWalk);
2526 // ActivateBestChain considers blocks already in chainActive
2527 // unconditionally valid already, so force disconnect away from it.
2528 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2529 // It's probably hopeless to try to make the mempool consistent
2530 // here if DisconnectTip failed, but we can try.
2531 UpdateMempoolForReorg(disconnectpool, false);
2532 return false;
2536 // DisconnectTip will add transactions to disconnectpool; try to add these
2537 // back to the mempool.
2538 UpdateMempoolForReorg(disconnectpool, true);
2540 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2541 // add it again.
2542 BlockMap::iterator it = mapBlockIndex.begin();
2543 while (it != mapBlockIndex.end()) {
2544 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2545 setBlockIndexCandidates.insert(it->second);
2547 it++;
2550 InvalidChainFound(pindex);
2551 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2552 return true;
2555 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2556 AssertLockHeld(cs_main);
2558 int nHeight = pindex->nHeight;
2560 // Remove the invalidity flag from this block and all its descendants.
2561 BlockMap::iterator it = mapBlockIndex.begin();
2562 while (it != mapBlockIndex.end()) {
2563 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2564 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2565 setDirtyBlockIndex.insert(it->second);
2566 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2567 setBlockIndexCandidates.insert(it->second);
2569 if (it->second == pindexBestInvalid) {
2570 // Reset invalid block marker if it was pointing to one of those.
2571 pindexBestInvalid = NULL;
2574 it++;
2577 // Remove the invalidity flag from all ancestors too.
2578 while (pindex != NULL) {
2579 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2580 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2581 setDirtyBlockIndex.insert(pindex);
2583 pindex = pindex->pprev;
2585 return true;
2588 static CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2590 // Check for duplicate
2591 uint256 hash = block.GetHash();
2592 BlockMap::iterator it = mapBlockIndex.find(hash);
2593 if (it != mapBlockIndex.end())
2594 return it->second;
2596 // Construct new block index object
2597 CBlockIndex* pindexNew = new CBlockIndex(block);
2598 assert(pindexNew);
2599 // We assign the sequence id to blocks only when the full data is available,
2600 // to avoid miners withholding blocks but broadcasting headers, to get a
2601 // competitive advantage.
2602 pindexNew->nSequenceId = 0;
2603 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2604 pindexNew->phashBlock = &((*mi).first);
2605 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2606 if (miPrev != mapBlockIndex.end())
2608 pindexNew->pprev = (*miPrev).second;
2609 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2610 pindexNew->BuildSkip();
2612 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2613 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2614 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2615 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2616 pindexBestHeader = pindexNew;
2618 setDirtyBlockIndex.insert(pindexNew);
2620 return pindexNew;
2623 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2624 static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2626 pindexNew->nTx = block.vtx.size();
2627 pindexNew->nChainTx = 0;
2628 pindexNew->nFile = pos.nFile;
2629 pindexNew->nDataPos = pos.nPos;
2630 pindexNew->nUndoPos = 0;
2631 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2632 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2633 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2635 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2636 setDirtyBlockIndex.insert(pindexNew);
2638 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2639 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2640 std::deque<CBlockIndex*> queue;
2641 queue.push_back(pindexNew);
2643 // Recursively process any descendant blocks that now may be eligible to be connected.
2644 while (!queue.empty()) {
2645 CBlockIndex *pindex = queue.front();
2646 queue.pop_front();
2647 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2649 LOCK(cs_nBlockSequenceId);
2650 pindex->nSequenceId = nBlockSequenceId++;
2652 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2653 setBlockIndexCandidates.insert(pindex);
2655 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2656 while (range.first != range.second) {
2657 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2658 queue.push_back(it->second);
2659 range.first++;
2660 mapBlocksUnlinked.erase(it);
2663 } else {
2664 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2665 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2669 return true;
2672 static bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2674 LOCK(cs_LastBlockFile);
2676 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2677 if (vinfoBlockFile.size() <= nFile) {
2678 vinfoBlockFile.resize(nFile + 1);
2681 if (!fKnown) {
2682 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2683 nFile++;
2684 if (vinfoBlockFile.size() <= nFile) {
2685 vinfoBlockFile.resize(nFile + 1);
2688 pos.nFile = nFile;
2689 pos.nPos = vinfoBlockFile[nFile].nSize;
2692 if ((int)nFile != nLastBlockFile) {
2693 if (!fKnown) {
2694 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2696 FlushBlockFile(!fKnown);
2697 nLastBlockFile = nFile;
2700 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2701 if (fKnown)
2702 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2703 else
2704 vinfoBlockFile[nFile].nSize += nAddSize;
2706 if (!fKnown) {
2707 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2708 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2709 if (nNewChunks > nOldChunks) {
2710 if (fPruneMode)
2711 fCheckForPruning = true;
2712 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2713 FILE *file = OpenBlockFile(pos);
2714 if (file) {
2715 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2716 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2717 fclose(file);
2720 else
2721 return state.Error("out of disk space");
2725 setDirtyFileInfo.insert(nFile);
2726 return true;
2729 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2731 pos.nFile = nFile;
2733 LOCK(cs_LastBlockFile);
2735 unsigned int nNewSize;
2736 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2737 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2738 setDirtyFileInfo.insert(nFile);
2740 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2741 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2742 if (nNewChunks > nOldChunks) {
2743 if (fPruneMode)
2744 fCheckForPruning = true;
2745 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2746 FILE *file = OpenUndoFile(pos);
2747 if (file) {
2748 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2749 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2750 fclose(file);
2753 else
2754 return state.Error("out of disk space");
2757 return true;
2760 static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
2762 // Check proof of work matches claimed amount
2763 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2764 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2766 return true;
2769 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2771 // These are checks that are independent of context.
2773 if (block.fChecked)
2774 return true;
2776 // Check that the header is valid (particularly PoW). This is mostly
2777 // redundant with the call in AcceptBlockHeader.
2778 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2779 return false;
2781 // Check the merkle root.
2782 if (fCheckMerkleRoot) {
2783 bool mutated;
2784 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2785 if (block.hashMerkleRoot != hashMerkleRoot2)
2786 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2788 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2789 // of transactions in a block without affecting the merkle root of a block,
2790 // while still invalidating it.
2791 if (mutated)
2792 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2795 // All potential-corruption validation must be done before we do any
2796 // transaction validation, as otherwise we may mark the header as invalid
2797 // because we receive the wrong transactions for it.
2798 // Note that witness malleability is checked in ContextualCheckBlock, so no
2799 // checks that use witness data may be performed here.
2801 // Size limits
2802 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)
2803 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2805 // First transaction must be coinbase, the rest must not be
2806 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2807 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2808 for (unsigned int i = 1; i < block.vtx.size(); i++)
2809 if (block.vtx[i]->IsCoinBase())
2810 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2812 // Check transactions
2813 for (const auto& tx : block.vtx)
2814 if (!CheckTransaction(*tx, state, false))
2815 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2816 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2818 unsigned int nSigOps = 0;
2819 for (const auto& tx : block.vtx)
2821 nSigOps += GetLegacySigOpCount(*tx);
2823 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2824 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2826 if (fCheckPOW && fCheckMerkleRoot)
2827 block.fChecked = true;
2829 return true;
2832 static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
2834 if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)
2835 return true;
2837 int nHeight = pindexPrev->nHeight+1;
2838 // Don't accept any forks from the main chain prior to last checkpoint.
2839 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
2840 // MapBlockIndex.
2841 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2842 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2843 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
2845 return true;
2848 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2850 LOCK(cs_main);
2851 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2854 // Compute at which vout of the block's coinbase transaction the witness
2855 // commitment occurs, or -1 if not found.
2856 static int GetWitnessCommitmentIndex(const CBlock& block)
2858 int commitpos = -1;
2859 if (!block.vtx.empty()) {
2860 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2861 if (block.vtx[0]->vout[o].scriptPubKey.size() >= 38 && block.vtx[0]->vout[o].scriptPubKey[0] == OP_RETURN && block.vtx[0]->vout[o].scriptPubKey[1] == 0x24 && block.vtx[0]->vout[o].scriptPubKey[2] == 0xaa && block.vtx[0]->vout[o].scriptPubKey[3] == 0x21 && block.vtx[0]->vout[o].scriptPubKey[4] == 0xa9 && block.vtx[0]->vout[o].scriptPubKey[5] == 0xed) {
2862 commitpos = o;
2866 return commitpos;
2869 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2871 int commitpos = GetWitnessCommitmentIndex(block);
2872 static const std::vector<unsigned char> nonce(32, 0x00);
2873 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2874 CMutableTransaction tx(*block.vtx[0]);
2875 tx.vin[0].scriptWitness.stack.resize(1);
2876 tx.vin[0].scriptWitness.stack[0] = nonce;
2877 block.vtx[0] = MakeTransactionRef(std::move(tx));
2881 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2883 std::vector<unsigned char> commitment;
2884 int commitpos = GetWitnessCommitmentIndex(block);
2885 std::vector<unsigned char> ret(32, 0x00);
2886 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2887 if (commitpos == -1) {
2888 uint256 witnessroot = BlockWitnessMerkleRoot(block, NULL);
2889 CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
2890 CTxOut out;
2891 out.nValue = 0;
2892 out.scriptPubKey.resize(38);
2893 out.scriptPubKey[0] = OP_RETURN;
2894 out.scriptPubKey[1] = 0x24;
2895 out.scriptPubKey[2] = 0xaa;
2896 out.scriptPubKey[3] = 0x21;
2897 out.scriptPubKey[4] = 0xa9;
2898 out.scriptPubKey[5] = 0xed;
2899 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2900 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2901 CMutableTransaction tx(*block.vtx[0]);
2902 tx.vout.push_back(out);
2903 block.vtx[0] = MakeTransactionRef(std::move(tx));
2906 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2907 return commitment;
2910 /** Context-dependent validity checks.
2911 * By "context", we mean only the previous block headers, but not the UTXO
2912 * set; UTXO-related validity checks are done in ConnectBlock(). */
2913 static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2915 assert(pindexPrev != NULL);
2916 const int nHeight = pindexPrev->nHeight + 1;
2917 // Check proof of work
2918 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2919 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2921 // Check timestamp against prev
2922 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2923 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2925 // Check timestamp
2926 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
2927 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
2929 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2930 // check for version 2, 3 and 4 upgrades
2931 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
2932 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
2933 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
2934 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
2935 strprintf("rejected nVersion=0x%08x block", block.nVersion));
2937 return true;
2940 static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
2942 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2944 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
2945 int nLockTimeFlags = 0;
2946 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
2947 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
2950 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
2951 ? pindexPrev->GetMedianTimePast()
2952 : block.GetBlockTime();
2954 // Check that all transactions are finalized
2955 for (const auto& tx : block.vtx) {
2956 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
2957 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
2961 // Enforce rule that the coinbase starts with serialized block height
2962 if (nHeight >= consensusParams.BIP34Height)
2964 CScript expect = CScript() << nHeight;
2965 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
2966 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
2967 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
2971 // Validation for witness commitments.
2972 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
2973 // coinbase (where 0x0000....0000 is used instead).
2974 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
2975 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
2976 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
2977 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
2978 // multiple, the last one is used.
2979 bool fHaveWitness = false;
2980 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
2981 int commitpos = GetWitnessCommitmentIndex(block);
2982 if (commitpos != -1) {
2983 bool malleated = false;
2984 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
2985 // The malleation check is ignored; as the transaction tree itself
2986 // already does not permit it, it is impossible to trigger in the
2987 // witness tree.
2988 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
2989 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
2991 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
2992 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
2993 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
2995 fHaveWitness = true;
2999 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3000 if (!fHaveWitness) {
3001 for (const auto& tx : block.vtx) {
3002 if (tx->HasWitness()) {
3003 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
3008 // After the coinbase witness nonce and commitment are verified,
3009 // we can check if the block weight passes (before we've checked the
3010 // coinbase witness, it would be possible for the weight to be too
3011 // large by filling up the coinbase witness, which doesn't change
3012 // the block hash, so we couldn't mark the block as permanently
3013 // failed).
3014 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3015 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
3018 return true;
3021 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3023 AssertLockHeld(cs_main);
3024 // Check for duplicate
3025 uint256 hash = block.GetHash();
3026 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3027 CBlockIndex *pindex = NULL;
3028 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3030 if (miSelf != mapBlockIndex.end()) {
3031 // Block header is already known.
3032 pindex = miSelf->second;
3033 if (ppindex)
3034 *ppindex = pindex;
3035 if (pindex->nStatus & BLOCK_FAILED_MASK)
3036 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3037 return true;
3040 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3041 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3043 // Get prev block index
3044 CBlockIndex* pindexPrev = NULL;
3045 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3046 if (mi == mapBlockIndex.end())
3047 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
3048 pindexPrev = (*mi).second;
3049 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3050 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3052 assert(pindexPrev);
3053 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
3054 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3056 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
3057 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3059 if (pindex == NULL)
3060 pindex = AddToBlockIndex(block);
3062 if (ppindex)
3063 *ppindex = pindex;
3065 CheckBlockIndex(chainparams.GetConsensus());
3067 return true;
3070 // Exposed wrapper for AcceptBlockHeader
3071 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
3074 LOCK(cs_main);
3075 for (const CBlockHeader& header : headers) {
3076 CBlockIndex *pindex = NULL; // Use a temp pindex instead of ppindex to avoid a const_cast
3077 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
3078 return false;
3080 if (ppindex) {
3081 *ppindex = pindex;
3085 NotifyHeaderTip();
3086 return true;
3089 /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
3090 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3092 const CBlock& block = *pblock;
3094 if (fNewBlock) *fNewBlock = false;
3095 AssertLockHeld(cs_main);
3097 CBlockIndex *pindexDummy = NULL;
3098 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3100 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3101 return false;
3103 // Try to process all requested blocks that we don't have, but only
3104 // process an unrequested block if it's new and has enough work to
3105 // advance our tip, and isn't too many blocks ahead.
3106 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3107 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3108 // Blocks that are too out-of-order needlessly limit the effectiveness of
3109 // pruning, because pruning will not delete block files that contain any
3110 // blocks which are too close in height to the tip. Apply this test
3111 // regardless of whether pruning is enabled; it should generally be safe to
3112 // not process unrequested blocks.
3113 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3115 // TODO: Decouple this function from the block download logic by removing fRequested
3116 // This requires some new chain data structure to efficiently look up if a
3117 // block is in a chain leading to a candidate for best tip, despite not
3118 // being such a candidate itself.
3120 // TODO: deal better with return value and error conditions for duplicate
3121 // and unrequested blocks.
3122 if (fAlreadyHave) return true;
3123 if (!fRequested) { // If we didn't ask for it:
3124 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3125 if (!fHasMoreWork) return true; // Don't process less-work chains
3126 if (fTooFarAhead) return true; // Block height is too high
3128 if (fNewBlock) *fNewBlock = true;
3130 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3131 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3132 if (state.IsInvalid() && !state.CorruptionPossible()) {
3133 pindex->nStatus |= BLOCK_FAILED_VALID;
3134 setDirtyBlockIndex.insert(pindex);
3136 return error("%s: %s", __func__, FormatStateMessage(state));
3139 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3140 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3141 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3142 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3144 int nHeight = pindex->nHeight;
3146 // Write block to history file
3147 try {
3148 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3149 CDiskBlockPos blockPos;
3150 if (dbp != NULL)
3151 blockPos = *dbp;
3152 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3153 return error("AcceptBlock(): FindBlockPos failed");
3154 if (dbp == NULL)
3155 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3156 AbortNode(state, "Failed to write block");
3157 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3158 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3159 } catch (const std::runtime_error& e) {
3160 return AbortNode(state, std::string("System error: ") + e.what());
3163 if (fCheckForPruning)
3164 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3166 return true;
3169 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3172 CBlockIndex *pindex = NULL;
3173 if (fNewBlock) *fNewBlock = false;
3174 CValidationState state;
3175 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3176 // belt-and-suspenders.
3177 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3179 LOCK(cs_main);
3181 if (ret) {
3182 // Store to disk
3183 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, NULL, fNewBlock);
3185 CheckBlockIndex(chainparams.GetConsensus());
3186 if (!ret) {
3187 GetMainSignals().BlockChecked(*pblock, state);
3188 return error("%s: AcceptBlock FAILED", __func__);
3192 NotifyHeaderTip();
3194 CValidationState state; // Only used to report errors, not invalidity - ignore it
3195 if (!ActivateBestChain(state, chainparams, pblock))
3196 return error("%s: ActivateBestChain failed", __func__);
3198 return true;
3201 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3203 AssertLockHeld(cs_main);
3204 assert(pindexPrev && pindexPrev == chainActive.Tip());
3205 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
3206 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3208 CCoinsViewCache viewNew(pcoinsTip);
3209 CBlockIndex indexDummy(block);
3210 indexDummy.pprev = pindexPrev;
3211 indexDummy.nHeight = pindexPrev->nHeight + 1;
3213 // NOTE: CheckBlockHeader is called by CheckBlock
3214 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
3215 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3216 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3217 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3218 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3219 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3220 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3221 return false;
3222 assert(state.IsValid());
3224 return true;
3228 * BLOCK PRUNING CODE
3231 /* Calculate the amount of disk space the block & undo files currently use */
3232 static uint64_t CalculateCurrentUsage()
3234 uint64_t retval = 0;
3235 for (const CBlockFileInfo &file : vinfoBlockFile) {
3236 retval += file.nSize + file.nUndoSize;
3238 return retval;
3241 /* Prune a block file (modify associated database entries)*/
3242 void PruneOneBlockFile(const int fileNumber)
3244 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3245 CBlockIndex* pindex = it->second;
3246 if (pindex->nFile == fileNumber) {
3247 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3248 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3249 pindex->nFile = 0;
3250 pindex->nDataPos = 0;
3251 pindex->nUndoPos = 0;
3252 setDirtyBlockIndex.insert(pindex);
3254 // Prune from mapBlocksUnlinked -- any block we prune would have
3255 // to be downloaded again in order to consider its chain, at which
3256 // point it would be considered as a candidate for
3257 // mapBlocksUnlinked or setBlockIndexCandidates.
3258 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3259 while (range.first != range.second) {
3260 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3261 range.first++;
3262 if (_it->second == pindex) {
3263 mapBlocksUnlinked.erase(_it);
3269 vinfoBlockFile[fileNumber].SetNull();
3270 setDirtyFileInfo.insert(fileNumber);
3274 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3276 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3277 CDiskBlockPos pos(*it, 0);
3278 fs::remove(GetBlockPosFilename(pos, "blk"));
3279 fs::remove(GetBlockPosFilename(pos, "rev"));
3280 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3284 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3285 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3287 assert(fPruneMode && nManualPruneHeight > 0);
3289 LOCK2(cs_main, cs_LastBlockFile);
3290 if (chainActive.Tip() == NULL)
3291 return;
3293 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3294 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3295 int count=0;
3296 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3297 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3298 continue;
3299 PruneOneBlockFile(fileNumber);
3300 setFilesToPrune.insert(fileNumber);
3301 count++;
3303 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3306 /* This function is called from the RPC code for pruneblockchain */
3307 void PruneBlockFilesManual(int nManualPruneHeight)
3309 CValidationState state;
3310 const CChainParams& chainparams = Params();
3311 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
3315 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
3316 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
3317 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
3318 * (which in this case means the blockchain must be re-downloaded.)
3320 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
3321 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
3322 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
3323 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
3324 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
3325 * A db flag records the fact that at least some block files have been pruned.
3327 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
3329 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3331 LOCK2(cs_main, cs_LastBlockFile);
3332 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3333 return;
3335 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3336 return;
3339 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3340 uint64_t nCurrentUsage = CalculateCurrentUsage();
3341 // We don't check to prune until after we've allocated new space for files
3342 // So we should leave a buffer under our target to account for another allocation
3343 // before the next pruning.
3344 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3345 uint64_t nBytesToPrune;
3346 int count=0;
3348 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3349 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3350 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3352 if (vinfoBlockFile[fileNumber].nSize == 0)
3353 continue;
3355 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3356 break;
3358 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3359 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3360 continue;
3362 PruneOneBlockFile(fileNumber);
3363 // Queue up the files for removal
3364 setFilesToPrune.insert(fileNumber);
3365 nCurrentUsage -= nBytesToPrune;
3366 count++;
3370 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3371 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3372 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3373 nLastBlockWeCanPrune, count);
3376 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3378 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3380 // Check for nMinDiskSpace bytes (currently 50MB)
3381 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3382 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3384 return true;
3387 static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3389 if (pos.IsNull())
3390 return NULL;
3391 fs::path path = GetBlockPosFilename(pos, prefix);
3392 fs::create_directories(path.parent_path());
3393 FILE* file = fsbridge::fopen(path, "rb+");
3394 if (!file && !fReadOnly)
3395 file = fsbridge::fopen(path, "wb+");
3396 if (!file) {
3397 LogPrintf("Unable to open file %s\n", path.string());
3398 return NULL;
3400 if (pos.nPos) {
3401 if (fseek(file, pos.nPos, SEEK_SET)) {
3402 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3403 fclose(file);
3404 return NULL;
3407 return file;
3410 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3411 return OpenDiskFile(pos, "blk", fReadOnly);
3414 /** Open an undo file (rev?????.dat) */
3415 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3416 return OpenDiskFile(pos, "rev", fReadOnly);
3419 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3421 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3424 CBlockIndex * InsertBlockIndex(uint256 hash)
3426 if (hash.IsNull())
3427 return NULL;
3429 // Return existing
3430 BlockMap::iterator mi = mapBlockIndex.find(hash);
3431 if (mi != mapBlockIndex.end())
3432 return (*mi).second;
3434 // Create new
3435 CBlockIndex* pindexNew = new CBlockIndex();
3436 if (!pindexNew)
3437 throw std::runtime_error(std::string(__func__) + ": new CBlockIndex failed");
3438 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3439 pindexNew->phashBlock = &((*mi).first);
3441 return pindexNew;
3444 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3446 if (!pblocktree->LoadBlockIndexGuts(chainparams.GetConsensus(), InsertBlockIndex))
3447 return false;
3449 boost::this_thread::interruption_point();
3451 // Calculate nChainWork
3452 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3453 vSortedByHeight.reserve(mapBlockIndex.size());
3454 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3456 CBlockIndex* pindex = item.second;
3457 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3459 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3460 for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
3462 CBlockIndex* pindex = item.second;
3463 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3464 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3465 // We can link the chain of blocks for which we've received transactions at some point.
3466 // Pruned nodes may have deleted the block.
3467 if (pindex->nTx > 0) {
3468 if (pindex->pprev) {
3469 if (pindex->pprev->nChainTx) {
3470 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3471 } else {
3472 pindex->nChainTx = 0;
3473 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3475 } else {
3476 pindex->nChainTx = pindex->nTx;
3479 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3480 setBlockIndexCandidates.insert(pindex);
3481 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3482 pindexBestInvalid = pindex;
3483 if (pindex->pprev)
3484 pindex->BuildSkip();
3485 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3486 pindexBestHeader = pindex;
3489 // Load block file info
3490 pblocktree->ReadLastBlockFile(nLastBlockFile);
3491 vinfoBlockFile.resize(nLastBlockFile + 1);
3492 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3493 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3494 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3496 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3497 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3498 CBlockFileInfo info;
3499 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3500 vinfoBlockFile.push_back(info);
3501 } else {
3502 break;
3506 // Check presence of blk files
3507 LogPrintf("Checking all blk files are present...\n");
3508 std::set<int> setBlkDataFiles;
3509 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3511 CBlockIndex* pindex = item.second;
3512 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3513 setBlkDataFiles.insert(pindex->nFile);
3516 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3518 CDiskBlockPos pos(*it, 0);
3519 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3520 return false;
3524 // Check whether we have ever pruned block & undo files
3525 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3526 if (fHavePruned)
3527 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3529 // Check whether we need to continue reindexing
3530 bool fReindexing = false;
3531 pblocktree->ReadReindexing(fReindexing);
3532 fReindex |= fReindexing;
3534 // Check whether we have a transaction index
3535 pblocktree->ReadFlag("txindex", fTxIndex);
3536 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3538 return true;
3541 void LoadChainTip(const CChainParams& chainparams)
3543 if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return;
3545 // Load pointer to end of best chain
3546 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3547 if (it == mapBlockIndex.end())
3548 return;
3549 chainActive.SetTip(it->second);
3551 PruneBlockIndexCandidates();
3553 LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
3554 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3555 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3556 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3559 CVerifyDB::CVerifyDB()
3561 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3564 CVerifyDB::~CVerifyDB()
3566 uiInterface.ShowProgress("", 100);
3569 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3571 LOCK(cs_main);
3572 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3573 return true;
3575 // Verify blocks in the best chain
3576 if (nCheckDepth <= 0)
3577 nCheckDepth = 1000000000; // suffices until the year 19000
3578 if (nCheckDepth > chainActive.Height())
3579 nCheckDepth = chainActive.Height();
3580 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3581 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3582 CCoinsViewCache coins(coinsview);
3583 CBlockIndex* pindexState = chainActive.Tip();
3584 CBlockIndex* pindexFailure = NULL;
3585 int nGoodTransactions = 0;
3586 CValidationState state;
3587 int reportDone = 0;
3588 LogPrintf("[0%%]...");
3589 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3591 boost::this_thread::interruption_point();
3592 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3593 if (reportDone < percentageDone/10) {
3594 // report every 10% step
3595 LogPrintf("[%d%%]...", percentageDone);
3596 reportDone = percentageDone/10;
3598 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone);
3599 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3600 break;
3601 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3602 // If pruning, only go back as far as we have data.
3603 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3604 break;
3606 CBlock block;
3607 // check level 0: read from disk
3608 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3609 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3610 // check level 1: verify block validity
3611 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3612 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3613 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3614 // check level 2: verify undo validity
3615 if (nCheckLevel >= 2 && pindex) {
3616 CBlockUndo undo;
3617 CDiskBlockPos pos = pindex->GetUndoPos();
3618 if (!pos.IsNull()) {
3619 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3620 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3623 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3624 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3625 assert(coins.GetBestBlock() == pindex->GetBlockHash());
3626 DisconnectResult res = DisconnectBlock(block, pindex, coins);
3627 if (res == DISCONNECT_FAILED) {
3628 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3630 pindexState = pindex->pprev;
3631 if (res == DISCONNECT_UNCLEAN) {
3632 nGoodTransactions = 0;
3633 pindexFailure = pindex;
3634 } else {
3635 nGoodTransactions += block.vtx.size();
3638 if (ShutdownRequested())
3639 return true;
3641 if (pindexFailure)
3642 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3644 // check level 4: try reconnecting blocks
3645 if (nCheckLevel >= 4) {
3646 CBlockIndex *pindex = pindexState;
3647 while (pindex != chainActive.Tip()) {
3648 boost::this_thread::interruption_point();
3649 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3650 pindex = chainActive.Next(pindex);
3651 CBlock block;
3652 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3653 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3654 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3655 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3659 LogPrintf("[DONE].\n");
3660 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3662 return true;
3665 /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
3666 static bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
3668 // TODO: merge with ConnectBlock
3669 CBlock block;
3670 if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
3671 return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3674 for (const CTransactionRef& tx : block.vtx) {
3675 if (!tx->IsCoinBase()) {
3676 for (const CTxIn &txin : tx->vin) {
3677 inputs.SpendCoin(txin.prevout);
3680 // Pass check = true as every addition may be an overwrite.
3681 AddCoins(inputs, *tx, pindex->nHeight, true);
3683 return true;
3686 bool ReplayBlocks(const CChainParams& params, CCoinsView* view)
3688 LOCK(cs_main);
3690 CCoinsViewCache cache(view);
3692 std::vector<uint256> hashHeads = view->GetHeadBlocks();
3693 if (hashHeads.empty()) return true; // We're already in a consistent state.
3694 if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
3696 uiInterface.ShowProgress(_("Replaying blocks..."), 0);
3697 LogPrintf("Replaying blocks\n");
3699 const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
3700 const CBlockIndex* pindexNew; // New tip during the interrupted flush.
3701 const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
3703 if (mapBlockIndex.count(hashHeads[0]) == 0) {
3704 return error("ReplayBlocks(): reorganization to unknown block requested");
3706 pindexNew = mapBlockIndex[hashHeads[0]];
3708 if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
3709 if (mapBlockIndex.count(hashHeads[1]) == 0) {
3710 return error("ReplayBlocks(): reorganization from unknown block requested");
3712 pindexOld = mapBlockIndex[hashHeads[1]];
3713 pindexFork = LastCommonAncestor(pindexOld, pindexNew);
3714 assert(pindexFork != nullptr);
3717 // Rollback along the old branch.
3718 while (pindexOld != pindexFork) {
3719 if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
3720 CBlock block;
3721 if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
3722 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3724 LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
3725 DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
3726 if (res == DISCONNECT_FAILED) {
3727 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3729 // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
3730 // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
3731 // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
3732 // the result is still a version of the UTXO set with the effects of that block undone.
3734 pindexOld = pindexOld->pprev;
3737 // Roll forward from the forking point to the new tip.
3738 int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
3739 for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
3740 const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
3741 LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
3742 if (!RollforwardBlock(pindex, cache, params)) return false;
3745 cache.SetBestBlock(pindexNew->GetBlockHash());
3746 cache.Flush();
3747 uiInterface.ShowProgress("", 100);
3748 return true;
3751 bool RewindBlockIndex(const CChainParams& params)
3753 LOCK(cs_main);
3755 int nHeight = 1;
3756 while (nHeight <= chainActive.Height()) {
3757 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3758 break;
3760 nHeight++;
3763 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3764 CValidationState state;
3765 CBlockIndex* pindex = chainActive.Tip();
3766 while (chainActive.Height() >= nHeight) {
3767 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3768 // If pruning, don't try rewinding past the HAVE_DATA point;
3769 // since older blocks can't be served anyway, there's
3770 // no need to walk further, and trying to DisconnectTip()
3771 // will fail (and require a needless reindex/redownload
3772 // of the blockchain).
3773 break;
3775 if (!DisconnectTip(state, params, NULL)) {
3776 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3778 // Occasionally flush state to disk.
3779 if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
3780 return false;
3783 // Reduce validity flag and have-data flags.
3784 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3785 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3786 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3787 CBlockIndex* pindexIter = it->second;
3789 // Note: If we encounter an insufficiently validated block that
3790 // is on chainActive, it must be because we are a pruning node, and
3791 // this block or some successor doesn't HAVE_DATA, so we were unable to
3792 // rewind all the way. Blocks remaining on chainActive at this point
3793 // must not have their validity reduced.
3794 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3795 // Reduce validity
3796 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3797 // Remove have-data flags.
3798 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3799 // Remove storage location.
3800 pindexIter->nFile = 0;
3801 pindexIter->nDataPos = 0;
3802 pindexIter->nUndoPos = 0;
3803 // Remove various other things
3804 pindexIter->nTx = 0;
3805 pindexIter->nChainTx = 0;
3806 pindexIter->nSequenceId = 0;
3807 // Make sure it gets written.
3808 setDirtyBlockIndex.insert(pindexIter);
3809 // Update indexes
3810 setBlockIndexCandidates.erase(pindexIter);
3811 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3812 while (ret.first != ret.second) {
3813 if (ret.first->second == pindexIter) {
3814 mapBlocksUnlinked.erase(ret.first++);
3815 } else {
3816 ++ret.first;
3819 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3820 setBlockIndexCandidates.insert(pindexIter);
3824 PruneBlockIndexCandidates();
3826 CheckBlockIndex(params.GetConsensus());
3828 if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
3829 return false;
3832 return true;
3835 // May NOT be used after any connections are up as much
3836 // of the peer-processing logic assumes a consistent
3837 // block index state
3838 void UnloadBlockIndex()
3840 LOCK(cs_main);
3841 setBlockIndexCandidates.clear();
3842 chainActive.SetTip(NULL);
3843 pindexBestInvalid = NULL;
3844 pindexBestHeader = NULL;
3845 mempool.clear();
3846 mapBlocksUnlinked.clear();
3847 vinfoBlockFile.clear();
3848 nLastBlockFile = 0;
3849 nBlockSequenceId = 1;
3850 setDirtyBlockIndex.clear();
3851 setDirtyFileInfo.clear();
3852 versionbitscache.Clear();
3853 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3854 warningcache[b].clear();
3857 for (BlockMap::value_type& entry : mapBlockIndex) {
3858 delete entry.second;
3860 mapBlockIndex.clear();
3861 fHavePruned = false;
3864 bool LoadBlockIndex(const CChainParams& chainparams)
3866 // Load block index from databases
3867 if (!fReindex && !LoadBlockIndexDB(chainparams))
3868 return false;
3869 return true;
3872 bool InitBlockIndex(const CChainParams& chainparams)
3874 LOCK(cs_main);
3876 // Check whether we're already initialized
3877 if (chainActive.Genesis() != NULL)
3878 return true;
3880 // Use the provided setting for -txindex in the new database
3881 fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX);
3882 pblocktree->WriteFlag("txindex", fTxIndex);
3883 LogPrintf("Initializing databases...\n");
3885 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3886 if (!fReindex) {
3887 try {
3888 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3889 // Start new block file
3890 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3891 CDiskBlockPos blockPos;
3892 CValidationState state;
3893 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3894 return error("LoadBlockIndex(): FindBlockPos failed");
3895 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3896 return error("LoadBlockIndex(): writing genesis block to disk failed");
3897 CBlockIndex *pindex = AddToBlockIndex(block);
3898 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3899 return error("LoadBlockIndex(): genesis block not accepted");
3900 } catch (const std::runtime_error& e) {
3901 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3905 return true;
3908 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
3910 // Map of disk positions for blocks with unknown parent (only used for reindex)
3911 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3912 int64_t nStart = GetTimeMillis();
3914 int nLoaded = 0;
3915 try {
3916 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3917 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
3918 uint64_t nRewind = blkdat.GetPos();
3919 while (!blkdat.eof()) {
3920 boost::this_thread::interruption_point();
3922 blkdat.SetPos(nRewind);
3923 nRewind++; // start one byte further next time, in case of failure
3924 blkdat.SetLimit(); // remove former limit
3925 unsigned int nSize = 0;
3926 try {
3927 // locate a header
3928 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
3929 blkdat.FindByte(chainparams.MessageStart()[0]);
3930 nRewind = blkdat.GetPos()+1;
3931 blkdat >> FLATDATA(buf);
3932 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
3933 continue;
3934 // read size
3935 blkdat >> nSize;
3936 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3937 continue;
3938 } catch (const std::exception&) {
3939 // no valid block header found; don't complain
3940 break;
3942 try {
3943 // read block
3944 uint64_t nBlockPos = blkdat.GetPos();
3945 if (dbp)
3946 dbp->nPos = nBlockPos;
3947 blkdat.SetLimit(nBlockPos + nSize);
3948 blkdat.SetPos(nBlockPos);
3949 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3950 CBlock& block = *pblock;
3951 blkdat >> block;
3952 nRewind = blkdat.GetPos();
3954 // detect out of order blocks, and store them for later
3955 uint256 hash = block.GetHash();
3956 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3957 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3958 block.hashPrevBlock.ToString());
3959 if (dbp)
3960 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3961 continue;
3964 // process in case the block isn't known yet
3965 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3966 LOCK(cs_main);
3967 CValidationState state;
3968 if (AcceptBlock(pblock, state, chainparams, NULL, true, dbp, NULL))
3969 nLoaded++;
3970 if (state.IsError())
3971 break;
3972 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3973 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3976 // Activate the genesis block so normal node progress can continue
3977 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
3978 CValidationState state;
3979 if (!ActivateBestChain(state, chainparams)) {
3980 break;
3984 NotifyHeaderTip();
3986 // Recursively process earlier encountered successors of this block
3987 std::deque<uint256> queue;
3988 queue.push_back(hash);
3989 while (!queue.empty()) {
3990 uint256 head = queue.front();
3991 queue.pop_front();
3992 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3993 while (range.first != range.second) {
3994 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3995 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
3996 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
3998 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
3999 head.ToString());
4000 LOCK(cs_main);
4001 CValidationState dummy;
4002 if (AcceptBlock(pblockrecursive, dummy, chainparams, NULL, true, &it->second, NULL))
4004 nLoaded++;
4005 queue.push_back(pblockrecursive->GetHash());
4008 range.first++;
4009 mapBlocksUnknownParent.erase(it);
4010 NotifyHeaderTip();
4013 } catch (const std::exception& e) {
4014 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4017 } catch (const std::runtime_error& e) {
4018 AbortNode(std::string("System error: ") + e.what());
4020 if (nLoaded > 0)
4021 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4022 return nLoaded > 0;
4025 void static CheckBlockIndex(const Consensus::Params& consensusParams)
4027 if (!fCheckBlockIndex) {
4028 return;
4031 LOCK(cs_main);
4033 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4034 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4035 // iterating the block tree require that chainActive has been initialized.)
4036 if (chainActive.Height() < 0) {
4037 assert(mapBlockIndex.size() <= 1);
4038 return;
4041 // Build forward-pointing map of the entire block tree.
4042 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4043 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4044 forward.insert(std::make_pair(it->second->pprev, it->second));
4047 assert(forward.size() == mapBlockIndex.size());
4049 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4050 CBlockIndex *pindex = rangeGenesis.first->second;
4051 rangeGenesis.first++;
4052 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4054 // Iterate over the entire block tree, using depth-first search.
4055 // Along the way, remember whether there are blocks on the path from genesis
4056 // block being explored which are the first to have certain properties.
4057 size_t nNodes = 0;
4058 int nHeight = 0;
4059 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4060 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4061 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
4062 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4063 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4064 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4065 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4066 while (pindex != NULL) {
4067 nNodes++;
4068 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4069 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4070 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4071 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4072 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4073 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4074 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4076 // Begin: actual consistency checks.
4077 if (pindex->pprev == NULL) {
4078 // Genesis block checks.
4079 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4080 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4082 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)
4083 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4084 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4085 if (!fHavePruned) {
4086 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4087 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4088 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4089 } else {
4090 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4091 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4093 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4094 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4095 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4096 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4097 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4098 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4099 assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
4100 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4101 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4102 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4103 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4104 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4105 if (pindexFirstInvalid == NULL) {
4106 // Checks for not-invalid blocks.
4107 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4109 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4110 if (pindexFirstInvalid == NULL) {
4111 // If this block sorts at least as good as the current tip and
4112 // is valid and we have all data for its parents, it must be in
4113 // setBlockIndexCandidates. chainActive.Tip() must also be there
4114 // even if some data has been pruned.
4115 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4116 assert(setBlockIndexCandidates.count(pindex));
4118 // If some parent is missing, then it could be that this block was in
4119 // setBlockIndexCandidates but had to be removed because of the missing data.
4120 // In this case it must be in mapBlocksUnlinked -- see test below.
4122 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4123 assert(setBlockIndexCandidates.count(pindex) == 0);
4125 // Check whether this block is in mapBlocksUnlinked.
4126 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4127 bool foundInUnlinked = false;
4128 while (rangeUnlinked.first != rangeUnlinked.second) {
4129 assert(rangeUnlinked.first->first == pindex->pprev);
4130 if (rangeUnlinked.first->second == pindex) {
4131 foundInUnlinked = true;
4132 break;
4134 rangeUnlinked.first++;
4136 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4137 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4138 assert(foundInUnlinked);
4140 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4141 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4142 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4143 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4144 assert(fHavePruned); // We must have pruned.
4145 // This block may have entered mapBlocksUnlinked if:
4146 // - it has a descendant that at some point had more work than the
4147 // tip, and
4148 // - we tried switching to that descendant but were missing
4149 // data for some intermediate block between chainActive and the
4150 // tip.
4151 // So if this block is itself better than chainActive.Tip() and it wasn't in
4152 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4153 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4154 if (pindexFirstInvalid == NULL) {
4155 assert(foundInUnlinked);
4159 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4160 // End: actual consistency checks.
4162 // Try descending into the first subnode.
4163 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4164 if (range.first != range.second) {
4165 // A subnode was found.
4166 pindex = range.first->second;
4167 nHeight++;
4168 continue;
4170 // This is a leaf node.
4171 // Move upwards until we reach a node of which we have not yet visited the last child.
4172 while (pindex) {
4173 // We are going to either move to a parent or a sibling of pindex.
4174 // If pindex was the first with a certain property, unset the corresponding variable.
4175 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4176 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4177 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4178 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4179 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4180 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4181 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4182 // Find our parent.
4183 CBlockIndex* pindexPar = pindex->pprev;
4184 // Find which child we just visited.
4185 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4186 while (rangePar.first->second != pindex) {
4187 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4188 rangePar.first++;
4190 // Proceed to the next one.
4191 rangePar.first++;
4192 if (rangePar.first != rangePar.second) {
4193 // Move to the sibling.
4194 pindex = rangePar.first->second;
4195 break;
4196 } else {
4197 // Move up further.
4198 pindex = pindexPar;
4199 nHeight--;
4200 continue;
4205 // Check that we actually traversed the entire map.
4206 assert(nNodes == forward.size());
4209 std::string CBlockFileInfo::ToString() const
4211 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));
4214 CBlockFileInfo* GetBlockFileInfo(size_t n)
4216 return &vinfoBlockFile.at(n);
4219 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
4221 LOCK(cs_main);
4222 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4225 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
4227 LOCK(cs_main);
4228 return VersionBitsStatistics(chainActive.Tip(), params, pos);
4231 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
4233 LOCK(cs_main);
4234 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
4237 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4239 bool LoadMempool(void)
4241 const CChainParams& chainparams = Params();
4242 int64_t nExpiryTimeout = GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4243 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4244 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4245 if (file.IsNull()) {
4246 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4247 return false;
4250 int64_t count = 0;
4251 int64_t skipped = 0;
4252 int64_t failed = 0;
4253 int64_t nNow = GetTime();
4255 try {
4256 uint64_t version;
4257 file >> version;
4258 if (version != MEMPOOL_DUMP_VERSION) {
4259 return false;
4261 uint64_t num;
4262 file >> num;
4263 while (num--) {
4264 CTransactionRef tx;
4265 int64_t nTime;
4266 int64_t nFeeDelta;
4267 file >> tx;
4268 file >> nTime;
4269 file >> nFeeDelta;
4271 CAmount amountdelta = nFeeDelta;
4272 if (amountdelta) {
4273 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4275 CValidationState state;
4276 if (nTime + nExpiryTimeout > nNow) {
4277 LOCK(cs_main);
4278 AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, true, NULL, nTime, NULL, false, 0);
4279 if (state.IsValid()) {
4280 ++count;
4281 } else {
4282 ++failed;
4284 } else {
4285 ++skipped;
4287 if (ShutdownRequested())
4288 return false;
4290 std::map<uint256, CAmount> mapDeltas;
4291 file >> mapDeltas;
4293 for (const auto& i : mapDeltas) {
4294 mempool.PrioritiseTransaction(i.first, i.second);
4296 } catch (const std::exception& e) {
4297 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4298 return false;
4301 LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
4302 return true;
4305 void DumpMempool(void)
4307 int64_t start = GetTimeMicros();
4309 std::map<uint256, CAmount> mapDeltas;
4310 std::vector<TxMempoolInfo> vinfo;
4313 LOCK(mempool.cs);
4314 for (const auto &i : mempool.mapDeltas) {
4315 mapDeltas[i.first] = i.second;
4317 vinfo = mempool.infoAll();
4320 int64_t mid = GetTimeMicros();
4322 try {
4323 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4324 if (!filestr) {
4325 return;
4328 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4330 uint64_t version = MEMPOOL_DUMP_VERSION;
4331 file << version;
4333 file << (uint64_t)vinfo.size();
4334 for (const auto& i : vinfo) {
4335 file << *(i.tx);
4336 file << (int64_t)i.nTime;
4337 file << (int64_t)i.nFeeDelta;
4338 mapDeltas.erase(i.tx->GetHash());
4341 file << mapDeltas;
4342 FileCommit(file.Get());
4343 file.fclose();
4344 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4345 int64_t last = GetTimeMicros();
4346 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*0.000001, (last-mid)*0.000001);
4347 } catch (const std::exception& e) {
4348 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4352 //! Guess how far we are in the verification process at the given block index
4353 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4354 if (pindex == NULL)
4355 return 0.0;
4357 int64_t nNow = time(NULL);
4359 double fTxTotal;
4361 if (pindex->nChainTx <= data.nTxCount) {
4362 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4363 } else {
4364 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4367 return pindex->nChainTx / fTxTotal;
4370 class CMainCleanup
4372 public:
4373 CMainCleanup() {}
4374 ~CMainCleanup() {
4375 // block headers
4376 BlockMap::iterator it1 = mapBlockIndex.begin();
4377 for (; it1 != mapBlockIndex.end(); it1++)
4378 delete (*it1).second;
4379 mapBlockIndex.clear();
4381 } instance_of_cmaincleanup;