Merge #10574: Remove includes in .cpp files for things the corresponding .h file...
[bitcoinplatinum.git] / src / validation.cpp
blob75c40b22fc86d7a74473d73d815ec77b27823d08
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 <hash.h>
19 #include <init.h>
20 #include <policy/fees.h>
21 #include <policy/policy.h>
22 #include <policy/rbf.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 <warnings.h>
43 #include <sstream>
45 #include <boost/algorithm/string/replace.hpp>
46 #include <boost/algorithm/string/join.hpp>
47 #include <boost/thread.hpp>
49 #if defined(NDEBUG)
50 # error "Bitcoin cannot be compiled without assertions."
51 #endif
53 #define MICRO 0.000001
54 #define MILLI 0.001
56 /**
57 * Global state
59 namespace {
60 struct CBlockIndexWorkComparator
62 bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
63 // First sort by most total work, ...
64 if (pa->nChainWork > pb->nChainWork) return false;
65 if (pa->nChainWork < pb->nChainWork) return true;
67 // ... then by earliest time received, ...
68 if (pa->nSequenceId < pb->nSequenceId) return false;
69 if (pa->nSequenceId > pb->nSequenceId) return true;
71 // Use pointer address as tie breaker (should only happen with blocks
72 // loaded from disk, as those all have id 0).
73 if (pa < pb) return false;
74 if (pa > pb) return true;
76 // Identical blocks.
77 return false;
80 } // anon namespace
82 enum DisconnectResult
84 DISCONNECT_OK, // All good.
85 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
86 DISCONNECT_FAILED // Something else went wrong.
89 class ConnectTrace;
91 /**
92 * CChainState stores and provides an API to update our local knowledge of the
93 * current best chain and header tree.
95 * It generally provides access to the current block tree, as well as functions
96 * to provide new data, which it will appropriately validate and incorporate in
97 * its state as necessary.
99 * Eventually, the API here is targeted at being exposed externally as a
100 * consumable libconsensus library, so any functions added must only call
101 * other class member functions, pure functions in other parts of the consensus
102 * library, callbacks via the validation interface, or read/write-to-disk
103 * functions (eventually this will also be via callbacks).
105 class CChainState {
106 private:
108 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
109 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
110 * missing the data for the block.
112 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
115 * Every received block is assigned a unique and increasing identifier, so we
116 * know which one to give priority in case of a fork.
118 CCriticalSection cs_nBlockSequenceId;
119 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
120 int32_t nBlockSequenceId = 1;
121 /** Decreasing counter (used by subsequent preciousblock calls). */
122 int32_t nBlockReverseSequenceId = -1;
123 /** chainwork for the last block that preciousblock has been applied to. */
124 arith_uint256 nLastPreciousChainwork = 0;
126 /** In order to efficiently track invalidity of headers, we keep the set of
127 * blocks which we tried to connect and found to be invalid here (ie which
128 * were set to BLOCK_FAILED_VALID since the last restart). We can then
129 * walk this set and check if a new header is a descendant of something in
130 * this set, preventing us from having to walk mapBlockIndex when we try
131 * to connect a bad block and fail.
133 * While this is more complicated than marking everything which descends
134 * from an invalid block as invalid at the time we discover it to be
135 * invalid, doing so would require walking all of mapBlockIndex to find all
136 * descendants. Since this case should be very rare, keeping track of all
137 * BLOCK_FAILED_VALID blocks in a set should be just fine and work just as
138 * well.
140 * Because we already walk mapBlockIndex in height-order at startup, we go
141 * ahead and mark descendants of invalid blocks as FAILED_CHILD at that time,
142 * instead of putting things in this set.
144 std::set<CBlockIndex*> g_failed_blocks;
146 public:
147 CChain chainActive;
148 BlockMap mapBlockIndex;
149 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
150 CBlockIndex *pindexBestInvalid = nullptr;
152 bool LoadBlockIndex(const Consensus::Params& consensus_params, CBlockTreeDB& blocktree);
154 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock);
156 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex);
157 bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock);
159 // Block (dis)connection on a given view:
160 DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view);
161 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
162 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false);
164 // Block disconnection on our pcoinsTip:
165 bool DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool);
167 // Manual block validity manipulation:
168 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex);
169 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex);
170 bool ResetBlockFailureFlags(CBlockIndex *pindex);
172 bool ReplayBlocks(const CChainParams& params, CCoinsView* view);
173 bool RewindBlockIndex(const CChainParams& params);
174 bool LoadGenesisBlock(const CChainParams& chainparams);
176 void PruneBlockIndexCandidates();
178 void UnloadBlockIndex();
180 private:
181 bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace);
182 bool ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool);
184 CBlockIndex* AddToBlockIndex(const CBlockHeader& block);
185 /** Create a new block index entry for a given block hash */
186 CBlockIndex * InsertBlockIndex(const uint256& hash);
187 void CheckBlockIndex(const Consensus::Params& consensusParams);
189 void InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state);
190 CBlockIndex* FindMostWorkChain();
191 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams);
194 bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params);
195 } g_chainstate;
199 CCriticalSection cs_main;
201 BlockMap& mapBlockIndex = g_chainstate.mapBlockIndex;
202 CChain& chainActive = g_chainstate.chainActive;
203 CBlockIndex *pindexBestHeader = nullptr;
204 CWaitableCriticalSection csBestBlock;
205 CConditionVariable cvBlockChange;
206 int nScriptCheckThreads = 0;
207 std::atomic_bool fImporting(false);
208 std::atomic_bool fReindex(false);
209 bool fTxIndex = false;
210 bool fHavePruned = false;
211 bool fPruneMode = false;
212 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
213 bool fRequireStandard = true;
214 bool fCheckBlockIndex = false;
215 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
216 size_t nCoinCacheUsage = 5000 * 300;
217 uint64_t nPruneTarget = 0;
218 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
219 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
221 uint256 hashAssumeValid;
222 arith_uint256 nMinimumChainWork;
224 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
225 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
227 CBlockPolicyEstimator feeEstimator;
228 CTxMemPool mempool(&feeEstimator);
230 /** Constant stuff for coinbase transactions we create: */
231 CScript COINBASE_FLAGS;
233 const std::string strMessageMagic = "Bitcoin Signed Message:\n";
235 // Internal stuff
236 namespace {
237 CBlockIndex *&pindexBestInvalid = g_chainstate.pindexBestInvalid;
239 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
240 * Pruned nodes may have entries where B is missing data.
242 std::multimap<CBlockIndex*, CBlockIndex*>& mapBlocksUnlinked = g_chainstate.mapBlocksUnlinked;
244 CCriticalSection cs_LastBlockFile;
245 std::vector<CBlockFileInfo> vinfoBlockFile;
246 int nLastBlockFile = 0;
247 /** Global flag to indicate we should check to see if there are
248 * block/undo files that should be deleted. Set on startup
249 * or if we allocate more file space when we're in prune mode
251 bool fCheckForPruning = false;
253 /** Dirty block index entries. */
254 std::set<CBlockIndex*> setDirtyBlockIndex;
256 /** Dirty block file entries. */
257 std::set<int> setDirtyFileInfo;
258 } // anon namespace
260 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
262 // Find the first block the caller has in the main chain
263 for (const uint256& hash : locator.vHave) {
264 BlockMap::iterator mi = mapBlockIndex.find(hash);
265 if (mi != mapBlockIndex.end())
267 CBlockIndex* pindex = (*mi).second;
268 if (chain.Contains(pindex))
269 return pindex;
270 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
271 return chain.Tip();
275 return chain.Genesis();
278 std::unique_ptr<CCoinsViewDB> pcoinsdbview;
279 std::unique_ptr<CCoinsViewCache> pcoinsTip;
280 std::unique_ptr<CBlockTreeDB> pblocktree;
282 enum FlushStateMode {
283 FLUSH_STATE_NONE,
284 FLUSH_STATE_IF_NEEDED,
285 FLUSH_STATE_PERIODIC,
286 FLUSH_STATE_ALWAYS
289 // See definition for documentation
290 static bool FlushStateToDisk(const CChainParams& chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
291 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
292 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
293 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);
294 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
296 bool CheckFinalTx(const CTransaction &tx, int flags)
298 AssertLockHeld(cs_main);
300 // By convention a negative value for flags indicates that the
301 // current network-enforced consensus rules should be used. In
302 // a future soft-fork scenario that would mean checking which
303 // rules would be enforced for the next block and setting the
304 // appropriate flags. At the present time no soft-forks are
305 // scheduled, so no flags are set.
306 flags = std::max(flags, 0);
308 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
309 // nLockTime because when IsFinalTx() is called within
310 // CBlock::AcceptBlock(), the height of the block *being*
311 // evaluated is what is used. Thus if we want to know if a
312 // transaction can be part of the *next* block, we need to call
313 // IsFinalTx() with one more than chainActive.Height().
314 const int nBlockHeight = chainActive.Height() + 1;
316 // BIP113 requires that time-locked transactions have nLockTime set to
317 // less than the median time of the previous block they're contained in.
318 // When the next block is created its previous block will be the current
319 // chain tip, so we use that to calculate the median time passed to
320 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
321 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
322 ? chainActive.Tip()->GetMedianTimePast()
323 : GetAdjustedTime();
325 return IsFinalTx(tx, nBlockHeight, nBlockTime);
328 bool TestLockPointValidity(const LockPoints* lp)
330 AssertLockHeld(cs_main);
331 assert(lp);
332 // If there are relative lock times then the maxInputBlock will be set
333 // If there are no relative lock times, the LockPoints don't depend on the chain
334 if (lp->maxInputBlock) {
335 // Check whether chainActive is an extension of the block at which the LockPoints
336 // calculation was valid. If not LockPoints are no longer valid
337 if (!chainActive.Contains(lp->maxInputBlock)) {
338 return false;
342 // LockPoints still valid
343 return true;
346 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
348 AssertLockHeld(cs_main);
349 AssertLockHeld(mempool.cs);
351 CBlockIndex* tip = chainActive.Tip();
352 assert(tip != nullptr);
354 CBlockIndex index;
355 index.pprev = tip;
356 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
357 // height based locks because when SequenceLocks() is called within
358 // ConnectBlock(), the height of the block *being*
359 // evaluated is what is used.
360 // Thus if we want to know if a transaction can be part of the
361 // *next* block, we need to use one more than chainActive.Height()
362 index.nHeight = tip->nHeight + 1;
364 std::pair<int, int64_t> lockPair;
365 if (useExistingLockPoints) {
366 assert(lp);
367 lockPair.first = lp->height;
368 lockPair.second = lp->time;
370 else {
371 // pcoinsTip contains the UTXO set for chainActive.Tip()
372 CCoinsViewMemPool viewMemPool(pcoinsTip.get(), mempool);
373 std::vector<int> prevheights;
374 prevheights.resize(tx.vin.size());
375 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
376 const CTxIn& txin = tx.vin[txinIndex];
377 Coin coin;
378 if (!viewMemPool.GetCoin(txin.prevout, coin)) {
379 return error("%s: Missing input", __func__);
381 if (coin.nHeight == MEMPOOL_HEIGHT) {
382 // Assume all mempool transaction confirm in the next block
383 prevheights[txinIndex] = tip->nHeight + 1;
384 } else {
385 prevheights[txinIndex] = coin.nHeight;
388 lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
389 if (lp) {
390 lp->height = lockPair.first;
391 lp->time = lockPair.second;
392 // Also store the hash of the block with the highest height of
393 // all the blocks which have sequence locked prevouts.
394 // This hash needs to still be on the chain
395 // for these LockPoint calculations to be valid
396 // Note: It is impossible to correctly calculate a maxInputBlock
397 // if any of the sequence locked inputs depend on unconfirmed txs,
398 // except in the special case where the relative lock time/height
399 // is 0, which is equivalent to no sequence lock. Since we assume
400 // input height of tip+1 for mempool txs and test the resulting
401 // lockPair from CalculateSequenceLocks against tip+1. We know
402 // EvaluateSequenceLocks will fail if there was a non-zero sequence
403 // lock on a mempool input, so we can use the return value of
404 // CheckSequenceLocks to indicate the LockPoints validity
405 int maxInputHeight = 0;
406 for (int height : prevheights) {
407 // Can ignore mempool inputs since we'll fail if they had non-zero locks
408 if (height != tip->nHeight+1) {
409 maxInputHeight = std::max(maxInputHeight, height);
412 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
415 return EvaluateSequenceLocks(index, lockPair);
418 // Returns the script flags which should be checked for a given block
419 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
421 static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
422 int expired = pool.Expire(GetTime() - age);
423 if (expired != 0) {
424 LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
427 std::vector<COutPoint> vNoSpendsRemaining;
428 pool.TrimToSize(limit, &vNoSpendsRemaining);
429 for (const COutPoint& removed : vNoSpendsRemaining)
430 pcoinsTip->Uncache(removed);
433 /** Convert CValidationState to a human-readable message for logging */
434 std::string FormatStateMessage(const CValidationState &state)
436 return strprintf("%s%s (code %i)",
437 state.GetRejectReason(),
438 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
439 state.GetRejectCode());
442 static bool IsCurrentForFeeEstimation()
444 AssertLockHeld(cs_main);
445 if (IsInitialBlockDownload())
446 return false;
447 if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
448 return false;
449 if (chainActive.Height() < pindexBestHeader->nHeight - 1)
450 return false;
451 return true;
454 /* Make mempool consistent after a reorg, by re-adding or recursively erasing
455 * disconnected block transactions from the mempool, and also removing any
456 * other transactions from the mempool that are no longer valid given the new
457 * tip/height.
459 * Note: we assume that disconnectpool only contains transactions that are NOT
460 * confirmed in the current chain nor already in the mempool (otherwise,
461 * in-mempool descendants of such transactions would be removed).
463 * Passing fAddToMempool=false will skip trying to add the transactions back,
464 * and instead just erase from the mempool as needed.
467 void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
469 AssertLockHeld(cs_main);
470 std::vector<uint256> vHashUpdate;
471 // disconnectpool's insertion_order index sorts the entries from
472 // oldest to newest, but the oldest entry will be the last tx from the
473 // latest mined block that was disconnected.
474 // Iterate disconnectpool in reverse, so that we add transactions
475 // back to the mempool starting with the earliest transaction that had
476 // been previously seen in a block.
477 auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
478 while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
479 // ignore validation errors in resurrected transactions
480 CValidationState stateDummy;
481 if (!fAddToMempool || (*it)->IsCoinBase() ||
482 !AcceptToMemoryPool(mempool, stateDummy, *it, nullptr /* pfMissingInputs */,
483 nullptr /* plTxnReplaced */, true /* bypass_limits */, 0 /* nAbsurdFee */)) {
484 // If the transaction doesn't make it in to the mempool, remove any
485 // transactions that depend on it (which would now be orphans).
486 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
487 } else if (mempool.exists((*it)->GetHash())) {
488 vHashUpdate.push_back((*it)->GetHash());
490 ++it;
492 disconnectpool.queuedTx.clear();
493 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
494 // no in-mempool children, which is generally not true when adding
495 // previously-confirmed transactions back to the mempool.
496 // UpdateTransactionsFromBlock finds descendants of any transactions in
497 // the disconnectpool that were added back and cleans up the mempool state.
498 mempool.UpdateTransactionsFromBlock(vHashUpdate);
500 // We also need to remove any now-immature transactions
501 mempool.removeForReorg(pcoinsTip.get(), chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
502 // Re-limit mempool size, in case we added any transactions
503 LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
506 // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
507 // were somehow broken and returning the wrong scriptPubKeys
508 static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool& pool,
509 unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) {
510 AssertLockHeld(cs_main);
512 // pool.cs should be locked already, but go ahead and re-take the lock here
513 // to enforce that mempool doesn't change between when we check the view
514 // and when we actually call through to CheckInputs
515 LOCK(pool.cs);
517 assert(!tx.IsCoinBase());
518 for (const CTxIn& txin : tx.vin) {
519 const Coin& coin = view.AccessCoin(txin.prevout);
521 // At this point we haven't actually checked if the coins are all
522 // available (or shouldn't assume we have, since CheckInputs does).
523 // So we just return failure if the inputs are not available here,
524 // and then only have to check equivalence for available inputs.
525 if (coin.IsSpent()) return false;
527 const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
528 if (txFrom) {
529 assert(txFrom->GetHash() == txin.prevout.hash);
530 assert(txFrom->vout.size() > txin.prevout.n);
531 assert(txFrom->vout[txin.prevout.n] == coin.out);
532 } else {
533 const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout);
534 assert(!coinFromDisk.IsSpent());
535 assert(coinFromDisk.out == coin.out);
539 return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata);
542 static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx,
543 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
544 bool bypass_limits, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache)
546 const CTransaction& tx = *ptx;
547 const uint256 hash = tx.GetHash();
548 AssertLockHeld(cs_main);
549 if (pfMissingInputs)
550 *pfMissingInputs = false;
552 if (!CheckTransaction(tx, state))
553 return false; // state filled in by CheckTransaction
555 // Coinbase is only valid in a block, not as a loose transaction
556 if (tx.IsCoinBase())
557 return state.DoS(100, false, REJECT_INVALID, "coinbase");
559 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
560 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), chainparams.GetConsensus());
561 if (!gArgs.GetBoolArg("-prematurewitness", false) && tx.HasWitness() && !witnessEnabled) {
562 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
565 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
566 std::string reason;
567 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
568 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
570 // Only accept nLockTime-using transactions that can be mined in the next
571 // block; we don't want our mempool filled up with transactions that can't
572 // be mined yet.
573 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
574 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
576 // is it already in the memory pool?
577 if (pool.exists(hash)) {
578 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool");
581 // Check for conflicts with in-memory transactions
582 std::set<uint256> setConflicts;
584 LOCK(pool.cs); // protect pool.mapNextTx
585 for (const CTxIn &txin : tx.vin)
587 auto itConflicting = pool.mapNextTx.find(txin.prevout);
588 if (itConflicting != pool.mapNextTx.end())
590 const CTransaction *ptxConflicting = itConflicting->second;
591 if (!setConflicts.count(ptxConflicting->GetHash()))
593 // Allow opt-out of transaction replacement by setting
594 // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
596 // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
597 // non-replaceable transactions. All inputs rather than just one
598 // is for the sake of multi-party protocols, where we don't
599 // want a single party to be able to disable replacement.
601 // The opt-out ignores descendants as anyone relying on
602 // first-seen mempool behavior should be checking all
603 // unconfirmed ancestors anyway; doing otherwise is hopelessly
604 // insecure.
605 bool fReplacementOptOut = true;
606 if (fEnableReplacement)
608 for (const CTxIn &_txin : ptxConflicting->vin)
610 if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
612 fReplacementOptOut = false;
613 break;
617 if (fReplacementOptOut) {
618 return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict");
621 setConflicts.insert(ptxConflicting->GetHash());
628 CCoinsView dummy;
629 CCoinsViewCache view(&dummy);
631 LockPoints lp;
633 LOCK(pool.cs);
634 CCoinsViewMemPool viewMemPool(pcoinsTip.get(), pool);
635 view.SetBackend(viewMemPool);
637 // do all inputs exist?
638 for (const CTxIn txin : tx.vin) {
639 if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
640 coins_to_uncache.push_back(txin.prevout);
642 if (!view.HaveCoin(txin.prevout)) {
643 // Are inputs missing because we already have the tx?
644 for (size_t out = 0; out < tx.vout.size(); out++) {
645 // Optimistically just do efficient check of cache for outputs
646 if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
647 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
650 // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
651 if (pfMissingInputs) {
652 *pfMissingInputs = true;
654 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
658 // Bring the best block into scope
659 view.GetBestBlock();
661 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
662 view.SetBackend(dummy);
664 // Only accept BIP68 sequence locked transactions that can be mined in the next
665 // block; we don't want our mempool filled up with transactions that can't
666 // be mined yet.
667 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
668 // CoinsViewCache instead of create its own
669 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
670 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
672 } // end LOCK(pool.cs)
674 CAmount nFees = 0;
675 if (!Consensus::CheckTxInputs(tx, state, view, GetSpendHeight(view), nFees)) {
676 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
679 // Check for non-standard pay-to-script-hash in inputs
680 if (fRequireStandard && !AreInputsStandard(tx, view))
681 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
683 // Check for non-standard witness in P2WSH
684 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
685 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
687 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
689 // nModifiedFees includes any fee deltas from PrioritiseTransaction
690 CAmount nModifiedFees = nFees;
691 pool.ApplyDelta(hash, nModifiedFees);
693 // Keep track of transactions that spend a coinbase, which we re-scan
694 // during reorgs to ensure COINBASE_MATURITY is still met.
695 bool fSpendsCoinbase = false;
696 for (const CTxIn &txin : tx.vin) {
697 const Coin &coin = view.AccessCoin(txin.prevout);
698 if (coin.IsCoinBase()) {
699 fSpendsCoinbase = true;
700 break;
704 CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
705 fSpendsCoinbase, nSigOpsCost, lp);
706 unsigned int nSize = entry.GetTxSize();
708 // Check that the transaction doesn't have an excessive number of
709 // sigops, making it impossible to mine. Since the coinbase transaction
710 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
711 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
712 // merely non-standard transaction.
713 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
714 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
715 strprintf("%d", nSigOpsCost));
717 CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
718 if (!bypass_limits && mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
719 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
722 // No transactions are allowed below minRelayTxFee except from disconnected blocks
723 if (!bypass_limits && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
724 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
727 if (nAbsurdFee && nFees > nAbsurdFee)
728 return state.Invalid(false,
729 REJECT_HIGHFEE, "absurdly-high-fee",
730 strprintf("%d > %d", nFees, nAbsurdFee));
732 // Calculate in-mempool ancestors, up to a limit.
733 CTxMemPool::setEntries setAncestors;
734 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
735 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
736 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
737 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
738 std::string errString;
739 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
740 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
743 // A transaction that spends outputs that would be replaced by it is invalid. Now
744 // that we have the set of all ancestors we can detect this
745 // pathological case by making sure setConflicts and setAncestors don't
746 // intersect.
747 for (CTxMemPool::txiter ancestorIt : setAncestors)
749 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
750 if (setConflicts.count(hashAncestor))
752 return state.DoS(10, false,
753 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
754 strprintf("%s spends conflicting transaction %s",
755 hash.ToString(),
756 hashAncestor.ToString()));
760 // Check if it's economically rational to mine this transaction rather
761 // than the ones it replaces.
762 CAmount nConflictingFees = 0;
763 size_t nConflictingSize = 0;
764 uint64_t nConflictingCount = 0;
765 CTxMemPool::setEntries allConflicting;
767 // If we don't hold the lock allConflicting might be incomplete; the
768 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
769 // mempool consistency for us.
770 LOCK(pool.cs);
771 const bool fReplacementTransaction = setConflicts.size();
772 if (fReplacementTransaction)
774 CFeeRate newFeeRate(nModifiedFees, nSize);
775 std::set<uint256> setConflictsParents;
776 const int maxDescendantsToVisit = 100;
777 CTxMemPool::setEntries setIterConflicting;
778 for (const uint256 &hashConflicting : setConflicts)
780 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
781 if (mi == pool.mapTx.end())
782 continue;
784 // Save these to avoid repeated lookups
785 setIterConflicting.insert(mi);
787 // Don't allow the replacement to reduce the feerate of the
788 // mempool.
790 // We usually don't want to accept replacements with lower
791 // feerates than what they replaced as that would lower the
792 // feerate of the next block. Requiring that the feerate always
793 // be increased is also an easy-to-reason about way to prevent
794 // DoS attacks via replacements.
796 // The mining code doesn't (currently) take children into
797 // account (CPFP) so we only consider the feerates of
798 // transactions being directly replaced, not their indirect
799 // descendants. While that does mean high feerate children are
800 // ignored when deciding whether or not to replace, we do
801 // require the replacement to pay more overall fees too,
802 // mitigating most cases.
803 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
804 if (newFeeRate <= oldFeeRate)
806 return state.DoS(0, false,
807 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
808 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
809 hash.ToString(),
810 newFeeRate.ToString(),
811 oldFeeRate.ToString()));
814 for (const CTxIn &txin : mi->GetTx().vin)
816 setConflictsParents.insert(txin.prevout.hash);
819 nConflictingCount += mi->GetCountWithDescendants();
821 // This potentially overestimates the number of actual descendants
822 // but we just want to be conservative to avoid doing too much
823 // work.
824 if (nConflictingCount <= maxDescendantsToVisit) {
825 // If not too many to replace, then calculate the set of
826 // transactions that would have to be evicted
827 for (CTxMemPool::txiter it : setIterConflicting) {
828 pool.CalculateDescendants(it, allConflicting);
830 for (CTxMemPool::txiter it : allConflicting) {
831 nConflictingFees += it->GetModifiedFee();
832 nConflictingSize += it->GetTxSize();
834 } else {
835 return state.DoS(0, false,
836 REJECT_NONSTANDARD, "too many potential replacements", false,
837 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
838 hash.ToString(),
839 nConflictingCount,
840 maxDescendantsToVisit));
843 for (unsigned int j = 0; j < tx.vin.size(); j++)
845 // We don't want to accept replacements that require low
846 // feerate junk to be mined first. Ideally we'd keep track of
847 // the ancestor feerates and make the decision based on that,
848 // but for now requiring all new inputs to be confirmed works.
849 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
851 // Rather than check the UTXO set - potentially expensive -
852 // it's cheaper to just check if the new input refers to a
853 // tx that's in the mempool.
854 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
855 return state.DoS(0, false,
856 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
857 strprintf("replacement %s adds unconfirmed input, idx %d",
858 hash.ToString(), j));
862 // The replacement must pay greater fees than the transactions it
863 // replaces - if we did the bandwidth used by those conflicting
864 // transactions would not be paid for.
865 if (nModifiedFees < nConflictingFees)
867 return state.DoS(0, false,
868 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
869 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
870 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
873 // Finally in addition to paying more fees than the conflicts the
874 // new transaction must pay for its own bandwidth.
875 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
876 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
878 return state.DoS(0, false,
879 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
880 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
881 hash.ToString(),
882 FormatMoney(nDeltaFees),
883 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
887 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
888 if (!chainparams.RequireStandard()) {
889 scriptVerifyFlags = gArgs.GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
892 // Check against previous transactions
893 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
894 PrecomputedTransactionData txdata(tx);
895 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, txdata)) {
896 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
897 // need to turn both off, and compare against just turning off CLEANSTACK
898 // to see if the failure is specifically due to witness validation.
899 CValidationState stateDummy; // Want reported failures to be from first CheckInputs
900 if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
901 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
902 // Only the witness is missing, so the transaction itself may be fine.
903 state.SetCorruptionPossible();
905 return false; // state filled in by CheckInputs
908 // Check again against the current block tip's script verification
909 // flags to cache our script execution flags. This is, of course,
910 // useless if the next block has different script flags from the
911 // previous one, but because the cache tracks script flags for us it
912 // will auto-invalidate and we'll just have a few blocks of extra
913 // misses on soft-fork activation.
915 // This is also useful in case of bugs in the standard flags that cause
916 // transactions to pass as valid when they're actually invalid. For
917 // instance the STRICTENC flag was incorrectly allowing certain
918 // CHECKSIG NOT scripts to pass, even though they were invalid.
920 // There is a similar check in CreateNewBlock() to prevent creating
921 // invalid blocks (using TestBlockValidity), however allowing such
922 // transactions into the mempool can be exploited as a DoS attack.
923 unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus());
924 if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata))
926 // If we're using promiscuousmempoolflags, we may hit this normally
927 // Check if current block has some flags that scriptVerifyFlags
928 // does not before printing an ominous warning
929 if (!(~scriptVerifyFlags & currentBlockScriptVerifyFlags)) {
930 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against latest-block but not STANDARD flags %s, %s",
931 __func__, hash.ToString(), FormatStateMessage(state));
932 } else {
933 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, false, txdata)) {
934 return error("%s: ConnectInputs failed against MANDATORY but not STANDARD flags due to promiscuous mempool %s, %s",
935 __func__, hash.ToString(), FormatStateMessage(state));
936 } else {
937 LogPrintf("Warning: -promiscuousmempool flags set to not include currently enforced soft forks, this may break mining or otherwise cause instability!\n");
942 // Remove conflicting transactions from the mempool
943 for (const CTxMemPool::txiter it : allConflicting)
945 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
946 it->GetTx().GetHash().ToString(),
947 hash.ToString(),
948 FormatMoney(nModifiedFees - nConflictingFees),
949 (int)nSize - (int)nConflictingSize);
950 if (plTxnReplaced)
951 plTxnReplaced->push_back(it->GetSharedTx());
953 pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
955 // This transaction should only count for fee estimation if:
956 // - it isn't a BIP 125 replacement transaction (may not be widely supported)
957 // - it's not being readded during a reorg which bypasses typical mempool fee limits
958 // - the node is not behind
959 // - the transaction is not dependent on any other transactions in the mempool
960 bool validForFeeEstimation = !fReplacementTransaction && !bypass_limits && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
962 // Store transaction in memory
963 pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
965 // trim mempool and check if tx was trimmed
966 if (!bypass_limits) {
967 LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
968 if (!pool.exists(hash))
969 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
973 GetMainSignals().TransactionAddedToMempool(ptx);
975 return true;
978 /** (try to) add transaction to memory pool with a specified acceptance time **/
979 static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
980 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
981 bool bypass_limits, const CAmount nAbsurdFee)
983 std::vector<COutPoint> coins_to_uncache;
984 bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, pfMissingInputs, nAcceptTime, plTxnReplaced, bypass_limits, nAbsurdFee, coins_to_uncache);
985 if (!res) {
986 for (const COutPoint& hashTx : coins_to_uncache)
987 pcoinsTip->Uncache(hashTx);
989 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
990 CValidationState stateDummy;
991 FlushStateToDisk(chainparams, stateDummy, FLUSH_STATE_PERIODIC);
992 return res;
995 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
996 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
997 bool bypass_limits, const CAmount nAbsurdFee)
999 const CChainParams& chainparams = Params();
1000 return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, pfMissingInputs, GetTime(), plTxnReplaced, bypass_limits, nAbsurdFee);
1004 * Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock.
1005 * If blockIndex is provided, the transaction is fetched from the corresponding block.
1007 bool GetTransaction(const uint256& hash, CTransactionRef& txOut, const Consensus::Params& consensusParams, uint256& hashBlock, bool fAllowSlow, CBlockIndex* blockIndex)
1009 CBlockIndex* pindexSlow = blockIndex;
1011 LOCK(cs_main);
1013 if (!blockIndex) {
1014 CTransactionRef ptx = mempool.get(hash);
1015 if (ptx) {
1016 txOut = ptx;
1017 return true;
1020 if (fTxIndex) {
1021 CDiskTxPos postx;
1022 if (pblocktree->ReadTxIndex(hash, postx)) {
1023 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1024 if (file.IsNull())
1025 return error("%s: OpenBlockFile failed", __func__);
1026 CBlockHeader header;
1027 try {
1028 file >> header;
1029 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1030 file >> txOut;
1031 } catch (const std::exception& e) {
1032 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1034 hashBlock = header.GetHash();
1035 if (txOut->GetHash() != hash)
1036 return error("%s: txid mismatch", __func__);
1037 return true;
1040 // transaction not found in index, nothing more can be done
1041 return false;
1044 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1045 const Coin& coin = AccessByTxid(*pcoinsTip, hash);
1046 if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
1050 if (pindexSlow) {
1051 CBlock block;
1052 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
1053 for (const auto& tx : block.vtx) {
1054 if (tx->GetHash() == hash) {
1055 txOut = tx;
1056 hashBlock = pindexSlow->GetBlockHash();
1057 return true;
1063 return false;
1071 //////////////////////////////////////////////////////////////////////////////
1073 // CBlock and CBlockIndex
1076 static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1078 // Open history file to append
1079 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1080 if (fileout.IsNull())
1081 return error("WriteBlockToDisk: OpenBlockFile failed");
1083 // Write index header
1084 unsigned int nSize = GetSerializeSize(fileout, block);
1085 fileout << FLATDATA(messageStart) << nSize;
1087 // Write block
1088 long fileOutPos = ftell(fileout.Get());
1089 if (fileOutPos < 0)
1090 return error("WriteBlockToDisk: ftell failed");
1091 pos.nPos = (unsigned int)fileOutPos;
1092 fileout << block;
1094 return true;
1097 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
1099 block.SetNull();
1101 // Open history file to read
1102 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1103 if (filein.IsNull())
1104 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1106 // Read block
1107 try {
1108 filein >> block;
1110 catch (const std::exception& e) {
1111 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1114 // Check the header
1115 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1116 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1118 return true;
1121 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1123 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1124 return false;
1125 if (block.GetHash() != pindex->GetBlockHash())
1126 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1127 pindex->ToString(), pindex->GetBlockPos().ToString());
1128 return true;
1131 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1133 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1134 // Force block reward to zero when right shift is undefined.
1135 if (halvings >= 64)
1136 return 0;
1138 CAmount nSubsidy = 50 * COIN;
1139 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1140 nSubsidy >>= halvings;
1141 return nSubsidy;
1144 bool IsInitialBlockDownload()
1146 // Once this function has returned false, it must remain false.
1147 static std::atomic<bool> latchToFalse{false};
1148 // Optimization: pre-test latch before taking the lock.
1149 if (latchToFalse.load(std::memory_order_relaxed))
1150 return false;
1152 LOCK(cs_main);
1153 if (latchToFalse.load(std::memory_order_relaxed))
1154 return false;
1155 if (fImporting || fReindex)
1156 return true;
1157 if (chainActive.Tip() == nullptr)
1158 return true;
1159 if (chainActive.Tip()->nChainWork < nMinimumChainWork)
1160 return true;
1161 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1162 return true;
1163 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1164 latchToFalse.store(true, std::memory_order_relaxed);
1165 return false;
1168 CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
1170 static void AlertNotify(const std::string& strMessage)
1172 uiInterface.NotifyAlertChanged();
1173 std::string strCmd = gArgs.GetArg("-alertnotify", "");
1174 if (strCmd.empty()) return;
1176 // Alert text should be plain ascii coming from a trusted source, but to
1177 // be safe we first strip anything not in safeChars, then add single quotes around
1178 // the whole string before passing it to the shell:
1179 std::string singleQuote("'");
1180 std::string safeStatus = SanitizeString(strMessage);
1181 safeStatus = singleQuote+safeStatus+singleQuote;
1182 boost::replace_all(strCmd, "%s", safeStatus);
1184 boost::thread t(runCommand, strCmd); // thread runs free
1187 static void CheckForkWarningConditions()
1189 AssertLockHeld(cs_main);
1190 // Before we get past initial download, we cannot reliably alert about forks
1191 // (we assume we don't get stuck on a fork before finishing our initial sync)
1192 if (IsInitialBlockDownload())
1193 return;
1195 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1196 // of our head, drop it
1197 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1198 pindexBestForkTip = nullptr;
1200 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1202 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
1204 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1205 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1206 AlertNotify(warning);
1208 if (pindexBestForkTip && pindexBestForkBase)
1210 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__,
1211 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1212 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1213 SetfLargeWorkForkFound(true);
1215 else
1217 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1218 SetfLargeWorkInvalidChainFound(true);
1221 else
1223 SetfLargeWorkForkFound(false);
1224 SetfLargeWorkInvalidChainFound(false);
1228 static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1230 AssertLockHeld(cs_main);
1231 // If we are on a fork that is sufficiently large, set a warning flag
1232 CBlockIndex* pfork = pindexNewForkTip;
1233 CBlockIndex* plonger = chainActive.Tip();
1234 while (pfork && pfork != plonger)
1236 while (plonger && plonger->nHeight > pfork->nHeight)
1237 plonger = plonger->pprev;
1238 if (pfork == plonger)
1239 break;
1240 pfork = pfork->pprev;
1243 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1244 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1245 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1246 // hash rate operating on the fork.
1247 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1248 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1249 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1250 if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
1251 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1252 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1254 pindexBestForkTip = pindexNewForkTip;
1255 pindexBestForkBase = pfork;
1258 CheckForkWarningConditions();
1261 void static InvalidChainFound(CBlockIndex* pindexNew)
1263 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1264 pindexBestInvalid = pindexNew;
1266 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1267 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1268 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1269 pindexNew->GetBlockTime()));
1270 CBlockIndex *tip = chainActive.Tip();
1271 assert (tip);
1272 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1273 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1274 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1275 CheckForkWarningConditions();
1278 void CChainState::InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1279 if (!state.CorruptionPossible()) {
1280 pindex->nStatus |= BLOCK_FAILED_VALID;
1281 g_failed_blocks.insert(pindex);
1282 setDirtyBlockIndex.insert(pindex);
1283 setBlockIndexCandidates.erase(pindex);
1284 InvalidChainFound(pindex);
1288 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1290 // mark inputs spent
1291 if (!tx.IsCoinBase()) {
1292 txundo.vprevout.reserve(tx.vin.size());
1293 for (const CTxIn &txin : tx.vin) {
1294 txundo.vprevout.emplace_back();
1295 bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1296 assert(is_spent);
1299 // add outputs
1300 AddCoins(inputs, tx, nHeight);
1303 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1305 CTxUndo txundo;
1306 UpdateCoins(tx, inputs, txundo, nHeight);
1309 bool CScriptCheck::operator()() {
1310 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1311 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1312 return VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *txdata), &error);
1315 int GetSpendHeight(const CCoinsViewCache& inputs)
1317 LOCK(cs_main);
1318 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1319 return pindexPrev->nHeight + 1;
1323 static CuckooCache::cache<uint256, SignatureCacheHasher> scriptExecutionCache;
1324 static uint256 scriptExecutionCacheNonce(GetRandHash());
1326 void InitScriptExecutionCache() {
1327 // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1328 // setup_bytes creates the minimum possible cache (2 elements).
1329 size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
1330 size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
1331 LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1332 (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1336 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
1337 * This does not modify the UTXO set.
1339 * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
1340 * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
1341 * not pushed onto pvChecks/run.
1343 * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
1344 * which are matched. This is useful for checking blocks where we will likely never need the cache
1345 * entry again.
1347 * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
1349 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)
1351 if (!tx.IsCoinBase())
1353 if (pvChecks)
1354 pvChecks->reserve(tx.vin.size());
1356 // The first loop above does all the inexpensive checks.
1357 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1358 // Helps prevent CPU exhaustion attacks.
1360 // Skip script verification when connecting blocks under the
1361 // assumevalid block. Assuming the assumevalid block is valid this
1362 // is safe because block merkle hashes are still computed and checked,
1363 // Of course, if an assumed valid block is invalid due to false scriptSigs
1364 // this optimization would allow an invalid chain to be accepted.
1365 if (fScriptChecks) {
1366 // First check if script executions have been cached with the same
1367 // flags. Note that this assumes that the inputs provided are
1368 // correct (ie that the transaction hash which is in tx's prevouts
1369 // properly commits to the scriptPubKey in the inputs view of that
1370 // transaction).
1371 uint256 hashCacheEntry;
1372 // We only use the first 19 bytes of nonce to avoid a second SHA
1373 // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
1374 static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
1375 CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1376 AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1377 if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1378 return true;
1381 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1382 const COutPoint &prevout = tx.vin[i].prevout;
1383 const Coin& coin = inputs.AccessCoin(prevout);
1384 assert(!coin.IsSpent());
1386 // We very carefully only pass in things to CScriptCheck which
1387 // are clearly committed to by tx' witness hash. This provides
1388 // a sanity check that our caching is not introducing consensus
1389 // failures through additional data in, eg, the coins being
1390 // spent being checked as a part of CScriptCheck.
1392 // Verify signature
1393 CScriptCheck check(coin.out, tx, i, flags, cacheSigStore, &txdata);
1394 if (pvChecks) {
1395 pvChecks->push_back(CScriptCheck());
1396 check.swap(pvChecks->back());
1397 } else if (!check()) {
1398 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1399 // Check whether the failure was caused by a
1400 // non-mandatory script verification check, such as
1401 // non-standard DER encodings or non-null dummy
1402 // arguments; if so, don't trigger DoS protection to
1403 // avoid splitting the network between upgraded and
1404 // non-upgraded nodes.
1405 CScriptCheck check2(coin.out, tx, i,
1406 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1407 if (check2())
1408 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1410 // Failures of other flags indicate a transaction that is
1411 // invalid in new blocks, e.g. an invalid P2SH. We DoS ban
1412 // such nodes as they are not following the protocol. That
1413 // said during an upgrade careful thought should be taken
1414 // as to the correct behavior - we may want to continue
1415 // peering with non-upgraded nodes even after soft-fork
1416 // super-majority signaling has occurred.
1417 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1421 if (cacheFullScriptStore && !pvChecks) {
1422 // We executed all of the provided scripts, and were told to
1423 // cache the result. Do so now.
1424 scriptExecutionCache.insert(hashCacheEntry);
1429 return true;
1432 namespace {
1434 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1436 // Open history file to append
1437 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1438 if (fileout.IsNull())
1439 return error("%s: OpenUndoFile failed", __func__);
1441 // Write index header
1442 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1443 fileout << FLATDATA(messageStart) << nSize;
1445 // Write undo data
1446 long fileOutPos = ftell(fileout.Get());
1447 if (fileOutPos < 0)
1448 return error("%s: ftell failed", __func__);
1449 pos.nPos = (unsigned int)fileOutPos;
1450 fileout << blockundo;
1452 // calculate & write checksum
1453 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1454 hasher << hashBlock;
1455 hasher << blockundo;
1456 fileout << hasher.GetHash();
1458 return true;
1461 static bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex *pindex)
1463 CDiskBlockPos pos = pindex->GetUndoPos();
1464 if (pos.IsNull()) {
1465 return error("%s: no undo data available", __func__);
1468 // Open history file to read
1469 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1470 if (filein.IsNull())
1471 return error("%s: OpenUndoFile failed", __func__);
1473 // Read block
1474 uint256 hashChecksum;
1475 CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1476 try {
1477 verifier << pindex->pprev->GetBlockHash();
1478 verifier >> blockundo;
1479 filein >> hashChecksum;
1481 catch (const std::exception& e) {
1482 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1485 // Verify checksum
1486 if (hashChecksum != verifier.GetHash())
1487 return error("%s: Checksum mismatch", __func__);
1489 return true;
1492 /** Abort with a message */
1493 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1495 SetMiscWarning(strMessage);
1496 LogPrintf("*** %s\n", strMessage);
1497 uiInterface.ThreadSafeMessageBox(
1498 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1499 "", CClientUIInterface::MSG_ERROR);
1500 StartShutdown();
1501 return false;
1504 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1506 AbortNode(strMessage, userMessage);
1507 return state.Error(strMessage);
1510 } // namespace
1513 * Restore the UTXO in a Coin at a given COutPoint
1514 * @param undo The Coin to be restored.
1515 * @param view The coins view to which to apply the changes.
1516 * @param out The out point that corresponds to the tx input.
1517 * @return A DisconnectResult as an int
1519 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1521 bool fClean = true;
1523 if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1525 if (undo.nHeight == 0) {
1526 // Missing undo metadata (height and coinbase). Older versions included this
1527 // information only in undo records for the last spend of a transactions'
1528 // outputs. This implies that it must be present for some other output of the same tx.
1529 const Coin& alternate = AccessByTxid(view, out.hash);
1530 if (!alternate.IsSpent()) {
1531 undo.nHeight = alternate.nHeight;
1532 undo.fCoinBase = alternate.fCoinBase;
1533 } else {
1534 return DISCONNECT_FAILED; // adding output for transaction without known metadata
1537 // The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
1538 // sure that the coin did not already exist in the cache. As we have queried for that above
1539 // using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
1540 // it is an overwrite.
1541 view.AddCoin(out, std::move(undo), !fClean);
1543 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1546 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1547 * When FAILED is returned, view is left in an indeterminate state. */
1548 DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1550 bool fClean = true;
1552 CBlockUndo blockUndo;
1553 if (!UndoReadFromDisk(blockUndo, pindex)) {
1554 error("DisconnectBlock(): failure reading undo data");
1555 return DISCONNECT_FAILED;
1558 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1559 error("DisconnectBlock(): block and undo data inconsistent");
1560 return DISCONNECT_FAILED;
1563 // undo transactions in reverse order
1564 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1565 const CTransaction &tx = *(block.vtx[i]);
1566 uint256 hash = tx.GetHash();
1567 bool is_coinbase = tx.IsCoinBase();
1569 // Check that all outputs are available and match the outputs in the block itself
1570 // exactly.
1571 for (size_t o = 0; o < tx.vout.size(); o++) {
1572 if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1573 COutPoint out(hash, o);
1574 Coin coin;
1575 bool is_spent = view.SpendCoin(out, &coin);
1576 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1577 fClean = false; // transaction output mismatch
1582 // restore inputs
1583 if (i > 0) { // not coinbases
1584 CTxUndo &txundo = blockUndo.vtxundo[i-1];
1585 if (txundo.vprevout.size() != tx.vin.size()) {
1586 error("DisconnectBlock(): transaction and undo data inconsistent");
1587 return DISCONNECT_FAILED;
1589 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1590 const COutPoint &out = tx.vin[j].prevout;
1591 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1592 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1593 fClean = fClean && res != DISCONNECT_UNCLEAN;
1595 // At this point, all of txundo.vprevout should have been moved out.
1599 // move best block pointer to prevout block
1600 view.SetBestBlock(pindex->pprev->GetBlockHash());
1602 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1605 void static FlushBlockFile(bool fFinalize = false)
1607 LOCK(cs_LastBlockFile);
1609 CDiskBlockPos posOld(nLastBlockFile, 0);
1611 FILE *fileOld = OpenBlockFile(posOld);
1612 if (fileOld) {
1613 if (fFinalize)
1614 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1615 FileCommit(fileOld);
1616 fclose(fileOld);
1619 fileOld = OpenUndoFile(posOld);
1620 if (fileOld) {
1621 if (fFinalize)
1622 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1623 FileCommit(fileOld);
1624 fclose(fileOld);
1628 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1630 static bool WriteUndoDataForBlock(const CBlockUndo& blockundo, CValidationState& state, CBlockIndex* pindex, const CChainParams& chainparams)
1632 // Write undo information to disk
1633 if (pindex->GetUndoPos().IsNull()) {
1634 CDiskBlockPos _pos;
1635 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1636 return error("ConnectBlock(): FindUndoPos failed");
1637 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1638 return AbortNode(state, "Failed to write undo data");
1640 // update nUndoPos in block index
1641 pindex->nUndoPos = _pos.nPos;
1642 pindex->nStatus |= BLOCK_HAVE_UNDO;
1643 setDirtyBlockIndex.insert(pindex);
1646 return true;
1649 static bool WriteTxIndexDataForBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex)
1651 if (!fTxIndex) return true;
1653 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1654 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1655 vPos.reserve(block.vtx.size());
1656 for (const CTransactionRef& tx : block.vtx)
1658 vPos.push_back(std::make_pair(tx->GetHash(), pos));
1659 pos.nTxOffset += ::GetSerializeSize(*tx, SER_DISK, CLIENT_VERSION);
1662 if (!pblocktree->WriteTxIndex(vPos)) {
1663 return AbortNode(state, "Failed to write transaction index");
1666 return true;
1669 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1671 void ThreadScriptCheck() {
1672 RenameThread("bitcoin-scriptch");
1673 scriptcheckqueue.Thread();
1676 // Protected by cs_main
1677 VersionBitsCache versionbitscache;
1679 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1681 LOCK(cs_main);
1682 int32_t nVersion = VERSIONBITS_TOP_BITS;
1684 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1685 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1686 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1687 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1691 return nVersion;
1695 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1697 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1699 private:
1700 int bit;
1702 public:
1703 explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1705 int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1706 int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1707 int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1708 int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1710 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1712 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1713 ((pindex->nVersion >> bit) & 1) != 0 &&
1714 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1718 // Protected by cs_main
1719 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1721 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) {
1722 AssertLockHeld(cs_main);
1724 unsigned int flags = SCRIPT_VERIFY_NONE;
1726 // Start enforcing P2SH (BIP16)
1727 if (pindex->nHeight >= consensusparams.BIP16Height) {
1728 flags |= SCRIPT_VERIFY_P2SH;
1731 // Start enforcing the DERSIG (BIP66) rule
1732 if (pindex->nHeight >= consensusparams.BIP66Height) {
1733 flags |= SCRIPT_VERIFY_DERSIG;
1736 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1737 if (pindex->nHeight >= consensusparams.BIP65Height) {
1738 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1741 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1742 if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1743 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1746 // Start enforcing WITNESS rules using versionbits logic.
1747 if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
1748 flags |= SCRIPT_VERIFY_WITNESS;
1749 flags |= SCRIPT_VERIFY_NULLDUMMY;
1752 return flags;
1757 static int64_t nTimeCheck = 0;
1758 static int64_t nTimeForks = 0;
1759 static int64_t nTimeVerify = 0;
1760 static int64_t nTimeConnect = 0;
1761 static int64_t nTimeIndex = 0;
1762 static int64_t nTimeCallbacks = 0;
1763 static int64_t nTimeTotal = 0;
1764 static int64_t nBlocksTotal = 0;
1766 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1767 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1768 * can fail if those validity checks fail (among other reasons). */
1769 bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1770 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck)
1772 AssertLockHeld(cs_main);
1773 assert(pindex);
1774 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1775 assert((pindex->phashBlock == nullptr) ||
1776 (*pindex->phashBlock == block.GetHash()));
1777 int64_t nTimeStart = GetTimeMicros();
1779 // Check it again in case a previous version let a bad block in
1780 // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
1781 // ContextualCheckBlockHeader() here. This means that if we add a new
1782 // consensus rule that is enforced in one of those two functions, then we
1783 // may have let in a block that violates the rule prior to updating the
1784 // software, and we would NOT be enforcing the rule here. Fully solving
1785 // upgrade from one software version to the next after a consensus rule
1786 // change is potentially tricky and issue-specific (see RewindBlockIndex()
1787 // for one general approach that was used for BIP 141 deployment).
1788 // Also, currently the rule against blocks more than 2 hours in the future
1789 // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
1790 // re-enforce that rule here (at least until we make it impossible for
1791 // GetAdjustedTime() to go backward).
1792 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1793 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1795 // verify that the view's current state corresponds to the previous block
1796 uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
1797 assert(hashPrevBlock == view.GetBestBlock());
1799 // Special case for the genesis block, skipping connection of its transactions
1800 // (its coinbase is unspendable)
1801 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1802 if (!fJustCheck)
1803 view.SetBestBlock(pindex->GetBlockHash());
1804 return true;
1807 nBlocksTotal++;
1809 bool fScriptChecks = true;
1810 if (!hashAssumeValid.IsNull()) {
1811 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1812 // A suitable default value is included with the software and updated from time to time. Because validity
1813 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1814 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1815 // effectively caching the result of part of the verification.
1816 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1817 if (it != mapBlockIndex.end()) {
1818 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1819 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1820 pindexBestHeader->nChainWork >= nMinimumChainWork) {
1821 // This block is a member of the assumed verified chain and an ancestor of the best header.
1822 // The equivalent time check discourages hash power from extorting the network via DOS attack
1823 // into accepting an invalid block through telling users they must manually set assumevalid.
1824 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1825 // it hard to hide the implication of the demand. This also avoids having release candidates
1826 // that are hardly doing any signature verification at all in testing without having to
1827 // artificially set the default assumed verified block further back.
1828 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1829 // least as good as the expected chain.
1830 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1835 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1836 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
1838 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1839 // unless those are already completely spent.
1840 // If such overwrites are allowed, coinbases and transactions depending upon those
1841 // can be duplicated to remove the ability to spend the first instance -- even after
1842 // being sent to another address.
1843 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1844 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1845 // already refuses previously-known transaction ids entirely.
1846 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1847 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1848 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1849 // initial block download.
1850 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1851 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1852 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1854 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1855 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1856 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1857 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1858 // duplicate transactions descending from the known pairs either.
1859 // 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.
1860 assert(pindex->pprev);
1861 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1862 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1863 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1865 if (fEnforceBIP30) {
1866 for (const auto& tx : block.vtx) {
1867 for (size_t o = 0; o < tx->vout.size(); o++) {
1868 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
1869 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1870 REJECT_INVALID, "bad-txns-BIP30");
1876 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1877 int nLockTimeFlags = 0;
1878 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1879 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1882 // Get the script flags for this block
1883 unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
1885 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1886 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
1888 CBlockUndo blockundo;
1890 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
1892 std::vector<int> prevheights;
1893 CAmount nFees = 0;
1894 int nInputs = 0;
1895 int64_t nSigOpsCost = 0;
1896 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1897 std::vector<PrecomputedTransactionData> txdata;
1898 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1899 for (unsigned int i = 0; i < block.vtx.size(); i++)
1901 const CTransaction &tx = *(block.vtx[i]);
1903 nInputs += tx.vin.size();
1905 if (!tx.IsCoinBase())
1907 CAmount txfee = 0;
1908 if (!Consensus::CheckTxInputs(tx, state, view, pindex->nHeight, txfee)) {
1909 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
1911 nFees += txfee;
1912 if (!MoneyRange(nFees)) {
1913 return state.DoS(100, error("%s: accumulated fee in the block out of range.", __func__),
1914 REJECT_INVALID, "bad-txns-accumulated-fee-outofrange");
1917 // Check that transaction is BIP68 final
1918 // BIP68 lock checks (as opposed to nLockTime checks) must
1919 // be in ConnectBlock because they require the UTXO set
1920 prevheights.resize(tx.vin.size());
1921 for (size_t j = 0; j < tx.vin.size(); j++) {
1922 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
1925 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1926 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1927 REJECT_INVALID, "bad-txns-nonfinal");
1931 // GetTransactionSigOpCost counts 3 types of sigops:
1932 // * legacy (always)
1933 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1934 // * witness (when witness enabled in flags and excludes coinbase)
1935 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1936 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1937 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1938 REJECT_INVALID, "bad-blk-sigops");
1940 txdata.emplace_back(tx);
1941 if (!tx.IsCoinBase())
1943 std::vector<CScriptCheck> vChecks;
1944 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1945 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr))
1946 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1947 tx.GetHash().ToString(), FormatStateMessage(state));
1948 control.Add(vChecks);
1951 CTxUndo undoDummy;
1952 if (i > 0) {
1953 blockundo.vtxundo.push_back(CTxUndo());
1955 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1957 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1958 LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(), MILLI * (nTime3 - nTime2), MILLI * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : MILLI * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * MICRO, nTimeConnect * MILLI / nBlocksTotal);
1960 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1961 if (block.vtx[0]->GetValueOut() > blockReward)
1962 return state.DoS(100,
1963 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1964 block.vtx[0]->GetValueOut(), blockReward),
1965 REJECT_INVALID, "bad-cb-amount");
1967 if (!control.Wait())
1968 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1969 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1970 LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1, MILLI * (nTime4 - nTime2), nInputs <= 1 ? 0 : MILLI * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * MICRO, nTimeVerify * MILLI / nBlocksTotal);
1972 if (fJustCheck)
1973 return true;
1975 if (!WriteUndoDataForBlock(blockundo, state, pindex, chainparams))
1976 return false;
1978 if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
1979 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1980 setDirtyBlockIndex.insert(pindex);
1983 if (!WriteTxIndexDataForBlock(block, state, pindex))
1984 return false;
1986 assert(pindex->phashBlock);
1987 // add this block to the view's block chain
1988 view.SetBestBlock(pindex->GetBlockHash());
1990 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1991 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
1993 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1994 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
1996 return true;
2000 * Update the on-disk chain state.
2001 * The caches and indexes are flushed depending on the mode we're called with
2002 * if they're too large, if it's been a while since the last write,
2003 * or always and in all cases if we're in prune mode and are deleting files.
2005 bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
2006 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
2007 LOCK(cs_main);
2008 static int64_t nLastWrite = 0;
2009 static int64_t nLastFlush = 0;
2010 static int64_t nLastSetChain = 0;
2011 std::set<int> setFilesToPrune;
2012 bool fFlushForPrune = false;
2013 bool fDoFullFlush = false;
2014 int64_t nNow = 0;
2015 try {
2017 LOCK(cs_LastBlockFile);
2018 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
2019 if (nManualPruneHeight > 0) {
2020 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
2021 } else {
2022 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
2023 fCheckForPruning = false;
2025 if (!setFilesToPrune.empty()) {
2026 fFlushForPrune = true;
2027 if (!fHavePruned) {
2028 pblocktree->WriteFlag("prunedblockfiles", true);
2029 fHavePruned = true;
2033 nNow = GetTimeMicros();
2034 // Avoid writing/flushing immediately after startup.
2035 if (nLastWrite == 0) {
2036 nLastWrite = nNow;
2038 if (nLastFlush == 0) {
2039 nLastFlush = nNow;
2041 if (nLastSetChain == 0) {
2042 nLastSetChain = nNow;
2044 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
2045 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2046 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
2047 // 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).
2048 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
2049 // The cache is over the limit, we have to write now.
2050 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
2051 // 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.
2052 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2053 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2054 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2055 // Combine all conditions that result in a full cache flush.
2056 fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2057 // Write blocks and block index to disk.
2058 if (fDoFullFlush || fPeriodicWrite) {
2059 // Depend on nMinDiskSpace to ensure we can write block index
2060 if (!CheckDiskSpace(0))
2061 return state.Error("out of disk space");
2062 // First make sure all block and undo data is flushed to disk.
2063 FlushBlockFile();
2064 // Then update all block file information (which may refer to block and undo files).
2066 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2067 vFiles.reserve(setDirtyFileInfo.size());
2068 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2069 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
2070 setDirtyFileInfo.erase(it++);
2072 std::vector<const CBlockIndex*> vBlocks;
2073 vBlocks.reserve(setDirtyBlockIndex.size());
2074 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2075 vBlocks.push_back(*it);
2076 setDirtyBlockIndex.erase(it++);
2078 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2079 return AbortNode(state, "Failed to write to block index database");
2082 // Finally remove any pruned files
2083 if (fFlushForPrune)
2084 UnlinkPrunedFiles(setFilesToPrune);
2085 nLastWrite = nNow;
2087 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2088 if (fDoFullFlush) {
2089 // Typical Coin structures on disk are around 48 bytes in size.
2090 // Pushing a new one to the database can cause it to be written
2091 // twice (once in the log, and once in the tables). This is already
2092 // an overestimation, as most will delete an existing entry or
2093 // overwrite one. Still, use a conservative safety factor of 2.
2094 if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
2095 return state.Error("out of disk space");
2096 // Flush the chainstate (which may refer to block index entries).
2097 if (!pcoinsTip->Flush())
2098 return AbortNode(state, "Failed to write to coin database");
2099 nLastFlush = nNow;
2102 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
2103 // Update best block in wallet (so we can detect restored wallets).
2104 GetMainSignals().SetBestChain(chainActive.GetLocator());
2105 nLastSetChain = nNow;
2107 } catch (const std::runtime_error& e) {
2108 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2110 return true;
2113 void FlushStateToDisk() {
2114 CValidationState state;
2115 const CChainParams& chainparams = Params();
2116 FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
2119 void PruneAndFlush() {
2120 CValidationState state;
2121 fCheckForPruning = true;
2122 const CChainParams& chainparams = Params();
2123 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
2126 static void DoWarning(const std::string& strWarning)
2128 static bool fWarned = false;
2129 SetMiscWarning(strWarning);
2130 if (!fWarned) {
2131 AlertNotify(strWarning);
2132 fWarned = true;
2136 /** Check warning conditions and do some notifications on new chain tip set. */
2137 void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainParams) {
2138 // New best block
2139 mempool.AddTransactionsUpdated(1);
2141 cvBlockChange.notify_all();
2143 std::vector<std::string> warningMessages;
2144 if (!IsInitialBlockDownload())
2146 int nUpgraded = 0;
2147 const CBlockIndex* pindex = pindexNew;
2148 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2149 WarningBitsConditionChecker checker(bit);
2150 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2151 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2152 const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2153 if (state == THRESHOLD_ACTIVE) {
2154 DoWarning(strWarning);
2155 } else {
2156 warningMessages.push_back(strWarning);
2160 // Check the version of the last 100 blocks to see if we need to upgrade:
2161 for (int i = 0; i < 100 && pindex != nullptr; i++)
2163 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2164 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2165 ++nUpgraded;
2166 pindex = pindex->pprev;
2168 if (nUpgraded > 0)
2169 warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
2170 if (nUpgraded > 100/2)
2172 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2173 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2174 DoWarning(strWarning);
2177 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
2178 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, pindexNew->nVersion,
2179 log(pindexNew->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
2180 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->GetBlockTime()),
2181 GuessVerificationProgress(chainParams.TxData(), pindexNew), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2182 if (!warningMessages.empty())
2183 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2184 LogPrintf("\n");
2188 /** Disconnect chainActive's tip.
2189 * After calling, the mempool will be in an inconsistent state, with
2190 * transactions from disconnected blocks being added to disconnectpool. You
2191 * should make the mempool consistent again by calling UpdateMempoolForReorg.
2192 * with cs_main held.
2194 * If disconnectpool is nullptr, then no disconnected transactions are added to
2195 * disconnectpool (note that the caller is responsible for mempool consistency
2196 * in any case).
2198 bool CChainState::DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
2200 CBlockIndex *pindexDelete = chainActive.Tip();
2201 assert(pindexDelete);
2202 // Read block from disk.
2203 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2204 CBlock& block = *pblock;
2205 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2206 return AbortNode(state, "Failed to read block");
2207 // Apply the block atomically to the chain state.
2208 int64_t nStart = GetTimeMicros();
2210 CCoinsViewCache view(pcoinsTip.get());
2211 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2212 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2213 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2214 bool flushed = view.Flush();
2215 assert(flushed);
2217 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
2218 // Write the chain state to disk, if necessary.
2219 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2220 return false;
2222 if (disconnectpool) {
2223 // Save transactions to re-add to mempool at end of reorg
2224 for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2225 disconnectpool->addTransaction(*it);
2227 while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2228 // Drop the earliest entry, and remove its children from the mempool.
2229 auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2230 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
2231 disconnectpool->removeEntry(it);
2235 chainActive.SetTip(pindexDelete->pprev);
2237 UpdateTip(pindexDelete->pprev, chainparams);
2238 // Let wallets know transactions went from 1-confirmed to
2239 // 0-confirmed or conflicted:
2240 GetMainSignals().BlockDisconnected(pblock);
2241 return true;
2244 static int64_t nTimeReadFromDisk = 0;
2245 static int64_t nTimeConnectTotal = 0;
2246 static int64_t nTimeFlush = 0;
2247 static int64_t nTimeChainState = 0;
2248 static int64_t nTimePostConnect = 0;
2250 struct PerBlockConnectTrace {
2251 CBlockIndex* pindex = nullptr;
2252 std::shared_ptr<const CBlock> pblock;
2253 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
2254 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
2257 * Used to track blocks whose transactions were applied to the UTXO state as a
2258 * part of a single ActivateBestChainStep call.
2260 * This class also tracks transactions that are removed from the mempool as
2261 * conflicts (per block) and can be used to pass all those transactions
2262 * through SyncTransaction.
2264 * This class assumes (and asserts) that the conflicted transactions for a given
2265 * block are added via mempool callbacks prior to the BlockConnected() associated
2266 * with those transactions. If any transactions are marked conflicted, it is
2267 * assumed that an associated block will always be added.
2269 * This class is single-use, once you call GetBlocksConnected() you have to throw
2270 * it away and make a new one.
2272 class ConnectTrace {
2273 private:
2274 std::vector<PerBlockConnectTrace> blocksConnected;
2275 CTxMemPool &pool;
2277 public:
2278 explicit ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
2279 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2282 ~ConnectTrace() {
2283 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2286 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2287 assert(!blocksConnected.back().pindex);
2288 assert(pindex);
2289 assert(pblock);
2290 blocksConnected.back().pindex = pindex;
2291 blocksConnected.back().pblock = std::move(pblock);
2292 blocksConnected.emplace_back();
2295 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2296 // We always keep one extra block at the end of our list because
2297 // blocks are added after all the conflicted transactions have
2298 // been filled in. Thus, the last entry should always be an empty
2299 // one waiting for the transactions from the next block. We pop
2300 // the last entry here to make sure the list we return is sane.
2301 assert(!blocksConnected.back().pindex);
2302 assert(blocksConnected.back().conflictedTxs->empty());
2303 blocksConnected.pop_back();
2304 return blocksConnected;
2307 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
2308 assert(!blocksConnected.back().pindex);
2309 if (reason == MemPoolRemovalReason::CONFLICT) {
2310 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2316 * Connect a new block to chainActive. pblock is either nullptr or a pointer to a CBlock
2317 * corresponding to pindexNew, to bypass loading it again from disk.
2319 * The block is added to connectTrace if connection succeeds.
2321 bool CChainState::ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
2323 assert(pindexNew->pprev == chainActive.Tip());
2324 // Read block from disk.
2325 int64_t nTime1 = GetTimeMicros();
2326 std::shared_ptr<const CBlock> pthisBlock;
2327 if (!pblock) {
2328 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2329 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2330 return AbortNode(state, "Failed to read block");
2331 pthisBlock = pblockNew;
2332 } else {
2333 pthisBlock = pblock;
2335 const CBlock& blockConnecting = *pthisBlock;
2336 // Apply the block atomically to the chain state.
2337 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2338 int64_t nTime3;
2339 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
2341 CCoinsViewCache view(pcoinsTip.get());
2342 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2343 GetMainSignals().BlockChecked(blockConnecting, state);
2344 if (!rv) {
2345 if (state.IsInvalid())
2346 InvalidBlockFound(pindexNew, state);
2347 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2349 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2350 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
2351 bool flushed = view.Flush();
2352 assert(flushed);
2354 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2355 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
2356 // Write the chain state to disk, if necessary.
2357 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2358 return false;
2359 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2360 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
2361 // Remove conflicting transactions from the mempool.;
2362 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2363 disconnectpool.removeForBlock(blockConnecting.vtx);
2364 // Update chainActive & related variables.
2365 chainActive.SetTip(pindexNew);
2366 UpdateTip(pindexNew, chainparams);
2368 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2369 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
2370 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
2372 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2373 return true;
2377 * Return the tip of the chain with the most work in it, that isn't
2378 * known to be invalid (it's however far from certain to be valid).
2380 CBlockIndex* CChainState::FindMostWorkChain() {
2381 do {
2382 CBlockIndex *pindexNew = nullptr;
2384 // Find the best candidate header.
2386 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2387 if (it == setBlockIndexCandidates.rend())
2388 return nullptr;
2389 pindexNew = *it;
2392 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2393 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2394 CBlockIndex *pindexTest = pindexNew;
2395 bool fInvalidAncestor = false;
2396 while (pindexTest && !chainActive.Contains(pindexTest)) {
2397 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2399 // Pruned nodes may have entries in setBlockIndexCandidates for
2400 // which block files have been deleted. Remove those as candidates
2401 // for the most work chain if we come across them; we can't switch
2402 // to a chain unless we have all the non-active-chain parent blocks.
2403 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2404 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2405 if (fFailedChain || fMissingData) {
2406 // Candidate chain is not usable (either invalid or missing data)
2407 if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2408 pindexBestInvalid = pindexNew;
2409 CBlockIndex *pindexFailed = pindexNew;
2410 // Remove the entire chain from the set.
2411 while (pindexTest != pindexFailed) {
2412 if (fFailedChain) {
2413 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2414 } else if (fMissingData) {
2415 // If we're missing data, then add back to mapBlocksUnlinked,
2416 // so that if the block arrives in the future we can try adding
2417 // to setBlockIndexCandidates again.
2418 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2420 setBlockIndexCandidates.erase(pindexFailed);
2421 pindexFailed = pindexFailed->pprev;
2423 setBlockIndexCandidates.erase(pindexTest);
2424 fInvalidAncestor = true;
2425 break;
2427 pindexTest = pindexTest->pprev;
2429 if (!fInvalidAncestor)
2430 return pindexNew;
2431 } while(true);
2434 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2435 void CChainState::PruneBlockIndexCandidates() {
2436 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2437 // reorganization to a better block fails.
2438 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2439 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2440 setBlockIndexCandidates.erase(it++);
2442 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2443 assert(!setBlockIndexCandidates.empty());
2447 * Try to make some progress towards making pindexMostWork the active block.
2448 * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
2450 bool CChainState::ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2452 AssertLockHeld(cs_main);
2453 const CBlockIndex *pindexOldTip = chainActive.Tip();
2454 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2456 // Disconnect active blocks which are no longer in the best chain.
2457 bool fBlocksDisconnected = false;
2458 DisconnectedBlockTransactions disconnectpool;
2459 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2460 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2461 // This is likely a fatal error, but keep the mempool consistent,
2462 // just in case. Only remove from the mempool in this case.
2463 UpdateMempoolForReorg(disconnectpool, false);
2464 return false;
2466 fBlocksDisconnected = true;
2469 // Build list of new blocks to connect.
2470 std::vector<CBlockIndex*> vpindexToConnect;
2471 bool fContinue = true;
2472 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2473 while (fContinue && nHeight != pindexMostWork->nHeight) {
2474 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2475 // a few blocks along the way.
2476 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2477 vpindexToConnect.clear();
2478 vpindexToConnect.reserve(nTargetHeight - nHeight);
2479 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2480 while (pindexIter && pindexIter->nHeight != nHeight) {
2481 vpindexToConnect.push_back(pindexIter);
2482 pindexIter = pindexIter->pprev;
2484 nHeight = nTargetHeight;
2486 // Connect new blocks.
2487 for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
2488 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2489 if (state.IsInvalid()) {
2490 // The block violates a consensus rule.
2491 if (!state.CorruptionPossible())
2492 InvalidChainFound(vpindexToConnect.back());
2493 state = CValidationState();
2494 fInvalidFound = true;
2495 fContinue = false;
2496 break;
2497 } else {
2498 // A system error occurred (disk space, database error, ...).
2499 // Make the mempool consistent with the current tip, just in case
2500 // any observers try to use it before shutdown.
2501 UpdateMempoolForReorg(disconnectpool, false);
2502 return false;
2504 } else {
2505 PruneBlockIndexCandidates();
2506 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2507 // We're in a better position than we were. Return temporarily to release the lock.
2508 fContinue = false;
2509 break;
2515 if (fBlocksDisconnected) {
2516 // If any blocks were disconnected, disconnectpool may be non empty. Add
2517 // any disconnected transactions back to the mempool.
2518 UpdateMempoolForReorg(disconnectpool, true);
2520 mempool.check(pcoinsTip.get());
2522 // Callbacks/notifications for a new best chain.
2523 if (fInvalidFound)
2524 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2525 else
2526 CheckForkWarningConditions();
2528 return true;
2531 static void NotifyHeaderTip() {
2532 bool fNotify = false;
2533 bool fInitialBlockDownload = false;
2534 static CBlockIndex* pindexHeaderOld = nullptr;
2535 CBlockIndex* pindexHeader = nullptr;
2537 LOCK(cs_main);
2538 pindexHeader = pindexBestHeader;
2540 if (pindexHeader != pindexHeaderOld) {
2541 fNotify = true;
2542 fInitialBlockDownload = IsInitialBlockDownload();
2543 pindexHeaderOld = pindexHeader;
2546 // Send block tip changed notifications without cs_main
2547 if (fNotify) {
2548 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2553 * Make the best chain active, in multiple steps. The result is either failure
2554 * or an activated best chain. pblock is either nullptr or a pointer to a block
2555 * that is already loaded (to avoid loading it again from disk).
2557 bool CChainState::ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2558 // Note that while we're often called here from ProcessNewBlock, this is
2559 // far from a guarantee. Things in the P2P/RPC will often end up calling
2560 // us in the middle of ProcessNewBlock - do not assume pblock is set
2561 // sanely for performance or correctness!
2563 CBlockIndex *pindexMostWork = nullptr;
2564 CBlockIndex *pindexNewTip = nullptr;
2565 int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2566 do {
2567 boost::this_thread::interruption_point();
2568 if (ShutdownRequested())
2569 break;
2571 const CBlockIndex *pindexFork;
2572 bool fInitialDownload;
2574 LOCK(cs_main);
2575 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2577 CBlockIndex *pindexOldTip = chainActive.Tip();
2578 if (pindexMostWork == nullptr) {
2579 pindexMostWork = FindMostWorkChain();
2582 // Whether we have anything to do at all.
2583 if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip())
2584 return true;
2586 bool fInvalidFound = false;
2587 std::shared_ptr<const CBlock> nullBlockPtr;
2588 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2589 return false;
2591 if (fInvalidFound) {
2592 // Wipe cache, we may need another branch now.
2593 pindexMostWork = nullptr;
2595 pindexNewTip = chainActive.Tip();
2596 pindexFork = chainActive.FindFork(pindexOldTip);
2597 fInitialDownload = IsInitialBlockDownload();
2599 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2600 assert(trace.pblock && trace.pindex);
2601 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, trace.conflictedTxs);
2604 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2606 // Notifications/callbacks that can run without cs_main
2608 // Notify external listeners about the new tip.
2609 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2611 // Always notify the UI if a new block tip was connected
2612 if (pindexFork != pindexNewTip) {
2613 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2616 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2617 } while (pindexNewTip != pindexMostWork);
2618 CheckBlockIndex(chainparams.GetConsensus());
2620 // Write changes periodically to disk, after relay.
2621 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
2622 return false;
2625 return true;
2627 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2628 return g_chainstate.ActivateBestChain(state, chainparams, std::move(pblock));
2631 bool CChainState::PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2634 LOCK(cs_main);
2635 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2636 // Nothing to do, this block is not at the tip.
2637 return true;
2639 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2640 // The chain has been extended since the last call, reset the counter.
2641 nBlockReverseSequenceId = -1;
2643 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2644 setBlockIndexCandidates.erase(pindex);
2645 pindex->nSequenceId = nBlockReverseSequenceId;
2646 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2647 // We can't keep reducing the counter if somebody really wants to
2648 // call preciousblock 2**31-1 times on the same set of tips...
2649 nBlockReverseSequenceId--;
2651 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2652 setBlockIndexCandidates.insert(pindex);
2653 PruneBlockIndexCandidates();
2657 return ActivateBestChain(state, params, std::shared_ptr<const CBlock>());
2659 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex) {
2660 return g_chainstate.PreciousBlock(state, params, pindex);
2663 bool CChainState::InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2665 AssertLockHeld(cs_main);
2667 // We first disconnect backwards and then mark the blocks as invalid.
2668 // This prevents a case where pruned nodes may fail to invalidateblock
2669 // and be left unable to start as they have no tip candidates (as there
2670 // are no blocks that meet the "have data and are not invalid per
2671 // nStatus" criteria for inclusion in setBlockIndexCandidates).
2673 bool pindex_was_in_chain = false;
2674 CBlockIndex *invalid_walk_tip = chainActive.Tip();
2676 DisconnectedBlockTransactions disconnectpool;
2677 while (chainActive.Contains(pindex)) {
2678 pindex_was_in_chain = true;
2679 // ActivateBestChain considers blocks already in chainActive
2680 // unconditionally valid already, so force disconnect away from it.
2681 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2682 // It's probably hopeless to try to make the mempool consistent
2683 // here if DisconnectTip failed, but we can try.
2684 UpdateMempoolForReorg(disconnectpool, false);
2685 return false;
2689 // Now mark the blocks we just disconnected as descendants invalid
2690 // (note this may not be all descendants).
2691 while (pindex_was_in_chain && invalid_walk_tip != pindex) {
2692 invalid_walk_tip->nStatus |= BLOCK_FAILED_CHILD;
2693 setDirtyBlockIndex.insert(invalid_walk_tip);
2694 setBlockIndexCandidates.erase(invalid_walk_tip);
2695 invalid_walk_tip = invalid_walk_tip->pprev;
2698 // Mark the block itself as invalid.
2699 pindex->nStatus |= BLOCK_FAILED_VALID;
2700 setDirtyBlockIndex.insert(pindex);
2701 setBlockIndexCandidates.erase(pindex);
2702 g_failed_blocks.insert(pindex);
2704 // DisconnectTip will add transactions to disconnectpool; try to add these
2705 // back to the mempool.
2706 UpdateMempoolForReorg(disconnectpool, true);
2708 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2709 // add it again.
2710 BlockMap::iterator it = mapBlockIndex.begin();
2711 while (it != mapBlockIndex.end()) {
2712 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2713 setBlockIndexCandidates.insert(it->second);
2715 it++;
2718 InvalidChainFound(pindex);
2719 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2720 return true;
2722 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex) {
2723 return g_chainstate.InvalidateBlock(state, chainparams, pindex);
2726 bool CChainState::ResetBlockFailureFlags(CBlockIndex *pindex) {
2727 AssertLockHeld(cs_main);
2729 int nHeight = pindex->nHeight;
2731 // Remove the invalidity flag from this block and all its descendants.
2732 BlockMap::iterator it = mapBlockIndex.begin();
2733 while (it != mapBlockIndex.end()) {
2734 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2735 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2736 setDirtyBlockIndex.insert(it->second);
2737 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2738 setBlockIndexCandidates.insert(it->second);
2740 if (it->second == pindexBestInvalid) {
2741 // Reset invalid block marker if it was pointing to one of those.
2742 pindexBestInvalid = nullptr;
2744 g_failed_blocks.erase(it->second);
2746 it++;
2749 // Remove the invalidity flag from all ancestors too.
2750 while (pindex != nullptr) {
2751 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2752 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2753 setDirtyBlockIndex.insert(pindex);
2755 pindex = pindex->pprev;
2757 return true;
2759 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2760 return g_chainstate.ResetBlockFailureFlags(pindex);
2763 CBlockIndex* CChainState::AddToBlockIndex(const CBlockHeader& block)
2765 // Check for duplicate
2766 uint256 hash = block.GetHash();
2767 BlockMap::iterator it = mapBlockIndex.find(hash);
2768 if (it != mapBlockIndex.end())
2769 return it->second;
2771 // Construct new block index object
2772 CBlockIndex* pindexNew = new CBlockIndex(block);
2773 // We assign the sequence id to blocks only when the full data is available,
2774 // to avoid miners withholding blocks but broadcasting headers, to get a
2775 // competitive advantage.
2776 pindexNew->nSequenceId = 0;
2777 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2778 pindexNew->phashBlock = &((*mi).first);
2779 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2780 if (miPrev != mapBlockIndex.end())
2782 pindexNew->pprev = (*miPrev).second;
2783 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2784 pindexNew->BuildSkip();
2786 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2787 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2788 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2789 if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2790 pindexBestHeader = pindexNew;
2792 setDirtyBlockIndex.insert(pindexNew);
2794 return pindexNew;
2797 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2798 bool CChainState::ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2800 pindexNew->nTx = block.vtx.size();
2801 pindexNew->nChainTx = 0;
2802 pindexNew->nFile = pos.nFile;
2803 pindexNew->nDataPos = pos.nPos;
2804 pindexNew->nUndoPos = 0;
2805 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2806 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2807 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2809 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2810 setDirtyBlockIndex.insert(pindexNew);
2812 if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
2813 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2814 std::deque<CBlockIndex*> queue;
2815 queue.push_back(pindexNew);
2817 // Recursively process any descendant blocks that now may be eligible to be connected.
2818 while (!queue.empty()) {
2819 CBlockIndex *pindex = queue.front();
2820 queue.pop_front();
2821 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2823 LOCK(cs_nBlockSequenceId);
2824 pindex->nSequenceId = nBlockSequenceId++;
2826 if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2827 setBlockIndexCandidates.insert(pindex);
2829 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2830 while (range.first != range.second) {
2831 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2832 queue.push_back(it->second);
2833 range.first++;
2834 mapBlocksUnlinked.erase(it);
2837 } else {
2838 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2839 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2843 return true;
2846 static bool FindBlockPos(CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2848 LOCK(cs_LastBlockFile);
2850 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2851 if (vinfoBlockFile.size() <= nFile) {
2852 vinfoBlockFile.resize(nFile + 1);
2855 if (!fKnown) {
2856 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2857 nFile++;
2858 if (vinfoBlockFile.size() <= nFile) {
2859 vinfoBlockFile.resize(nFile + 1);
2862 pos.nFile = nFile;
2863 pos.nPos = vinfoBlockFile[nFile].nSize;
2866 if ((int)nFile != nLastBlockFile) {
2867 if (!fKnown) {
2868 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2870 FlushBlockFile(!fKnown);
2871 nLastBlockFile = nFile;
2874 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2875 if (fKnown)
2876 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2877 else
2878 vinfoBlockFile[nFile].nSize += nAddSize;
2880 if (!fKnown) {
2881 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2882 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2883 if (nNewChunks > nOldChunks) {
2884 if (fPruneMode)
2885 fCheckForPruning = true;
2886 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2887 FILE *file = OpenBlockFile(pos);
2888 if (file) {
2889 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2890 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2891 fclose(file);
2894 else
2895 return error("out of disk space");
2899 setDirtyFileInfo.insert(nFile);
2900 return true;
2903 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2905 pos.nFile = nFile;
2907 LOCK(cs_LastBlockFile);
2909 unsigned int nNewSize;
2910 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2911 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2912 setDirtyFileInfo.insert(nFile);
2914 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2915 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2916 if (nNewChunks > nOldChunks) {
2917 if (fPruneMode)
2918 fCheckForPruning = true;
2919 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2920 FILE *file = OpenUndoFile(pos);
2921 if (file) {
2922 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2923 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2924 fclose(file);
2927 else
2928 return state.Error("out of disk space");
2931 return true;
2934 static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
2936 // Check proof of work matches claimed amount
2937 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2938 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2940 return true;
2943 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2945 // These are checks that are independent of context.
2947 if (block.fChecked)
2948 return true;
2950 // Check that the header is valid (particularly PoW). This is mostly
2951 // redundant with the call in AcceptBlockHeader.
2952 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2953 return false;
2955 // Check the merkle root.
2956 if (fCheckMerkleRoot) {
2957 bool mutated;
2958 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2959 if (block.hashMerkleRoot != hashMerkleRoot2)
2960 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2962 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2963 // of transactions in a block without affecting the merkle root of a block,
2964 // while still invalidating it.
2965 if (mutated)
2966 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2969 // All potential-corruption validation must be done before we do any
2970 // transaction validation, as otherwise we may mark the header as invalid
2971 // because we receive the wrong transactions for it.
2972 // Note that witness malleability is checked in ContextualCheckBlock, so no
2973 // checks that use witness data may be performed here.
2975 // Size limits
2976 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)
2977 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2979 // First transaction must be coinbase, the rest must not be
2980 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2981 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2982 for (unsigned int i = 1; i < block.vtx.size(); i++)
2983 if (block.vtx[i]->IsCoinBase())
2984 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2986 // Check transactions
2987 for (const auto& tx : block.vtx)
2988 if (!CheckTransaction(*tx, state, false))
2989 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2990 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2992 unsigned int nSigOps = 0;
2993 for (const auto& tx : block.vtx)
2995 nSigOps += GetLegacySigOpCount(*tx);
2997 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2998 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
3000 if (fCheckPOW && fCheckMerkleRoot)
3001 block.fChecked = true;
3003 return true;
3006 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
3008 LOCK(cs_main);
3009 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
3012 // Compute at which vout of the block's coinbase transaction the witness
3013 // commitment occurs, or -1 if not found.
3014 static int GetWitnessCommitmentIndex(const CBlock& block)
3016 int commitpos = -1;
3017 if (!block.vtx.empty()) {
3018 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
3019 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) {
3020 commitpos = o;
3024 return commitpos;
3027 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
3029 int commitpos = GetWitnessCommitmentIndex(block);
3030 static const std::vector<unsigned char> nonce(32, 0x00);
3031 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
3032 CMutableTransaction tx(*block.vtx[0]);
3033 tx.vin[0].scriptWitness.stack.resize(1);
3034 tx.vin[0].scriptWitness.stack[0] = nonce;
3035 block.vtx[0] = MakeTransactionRef(std::move(tx));
3039 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
3041 std::vector<unsigned char> commitment;
3042 int commitpos = GetWitnessCommitmentIndex(block);
3043 std::vector<unsigned char> ret(32, 0x00);
3044 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
3045 if (commitpos == -1) {
3046 uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
3047 CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
3048 CTxOut out;
3049 out.nValue = 0;
3050 out.scriptPubKey.resize(38);
3051 out.scriptPubKey[0] = OP_RETURN;
3052 out.scriptPubKey[1] = 0x24;
3053 out.scriptPubKey[2] = 0xaa;
3054 out.scriptPubKey[3] = 0x21;
3055 out.scriptPubKey[4] = 0xa9;
3056 out.scriptPubKey[5] = 0xed;
3057 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
3058 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
3059 CMutableTransaction tx(*block.vtx[0]);
3060 tx.vout.push_back(out);
3061 block.vtx[0] = MakeTransactionRef(std::move(tx));
3064 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
3065 return commitment;
3068 /** Context-dependent validity checks.
3069 * By "context", we mean only the previous block headers, but not the UTXO
3070 * set; UTXO-related validity checks are done in ConnectBlock().
3071 * NOTE: This function is not currently invoked by ConnectBlock(), so we
3072 * should consider upgrade issues if we change which consensus rules are
3073 * enforced in this function (eg by adding a new consensus rule). See comment
3074 * in ConnectBlock().
3075 * Note that -reindex-chainstate skips the validation that happens here!
3077 static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
3079 assert(pindexPrev != nullptr);
3080 const int nHeight = pindexPrev->nHeight + 1;
3082 // Check proof of work
3083 const Consensus::Params& consensusParams = params.GetConsensus();
3084 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3085 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
3087 // Check against checkpoints
3088 if (fCheckpointsEnabled) {
3089 // Don't accept any forks from the main chain prior to last checkpoint.
3090 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
3091 // MapBlockIndex.
3092 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(params.Checkpoints());
3093 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3094 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
3097 // Check timestamp against prev
3098 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3099 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
3101 // Check timestamp
3102 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
3103 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
3105 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
3106 // check for version 2, 3 and 4 upgrades
3107 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
3108 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
3109 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
3110 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
3111 strprintf("rejected nVersion=0x%08x block", block.nVersion));
3113 return true;
3116 /** NOTE: This function is not currently invoked by ConnectBlock(), so we
3117 * should consider upgrade issues if we change which consensus rules are
3118 * enforced in this function (eg by adding a new consensus rule). See comment
3119 * in ConnectBlock().
3120 * Note that -reindex-chainstate skips the validation that happens here!
3122 static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
3124 const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
3126 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
3127 int nLockTimeFlags = 0;
3128 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
3129 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
3132 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3133 ? pindexPrev->GetMedianTimePast()
3134 : block.GetBlockTime();
3136 // Check that all transactions are finalized
3137 for (const auto& tx : block.vtx) {
3138 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
3139 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
3143 // Enforce rule that the coinbase starts with serialized block height
3144 if (nHeight >= consensusParams.BIP34Height)
3146 CScript expect = CScript() << nHeight;
3147 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
3148 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
3149 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
3153 // Validation for witness commitments.
3154 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
3155 // coinbase (where 0x0000....0000 is used instead).
3156 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
3157 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
3158 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
3159 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
3160 // multiple, the last one is used.
3161 bool fHaveWitness = false;
3162 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
3163 int commitpos = GetWitnessCommitmentIndex(block);
3164 if (commitpos != -1) {
3165 bool malleated = false;
3166 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
3167 // The malleation check is ignored; as the transaction tree itself
3168 // already does not permit it, it is impossible to trigger in the
3169 // witness tree.
3170 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3171 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
3173 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
3174 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3175 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
3177 fHaveWitness = true;
3181 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3182 if (!fHaveWitness) {
3183 for (const auto& tx : block.vtx) {
3184 if (tx->HasWitness()) {
3185 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
3190 // After the coinbase witness nonce and commitment are verified,
3191 // we can check if the block weight passes (before we've checked the
3192 // coinbase witness, it would be possible for the weight to be too
3193 // large by filling up the coinbase witness, which doesn't change
3194 // the block hash, so we couldn't mark the block as permanently
3195 // failed).
3196 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3197 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
3200 return true;
3203 bool CChainState::AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3205 AssertLockHeld(cs_main);
3206 // Check for duplicate
3207 uint256 hash = block.GetHash();
3208 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3209 CBlockIndex *pindex = nullptr;
3210 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3212 if (miSelf != mapBlockIndex.end()) {
3213 // Block header is already known.
3214 pindex = miSelf->second;
3215 if (ppindex)
3216 *ppindex = pindex;
3217 if (pindex->nStatus & BLOCK_FAILED_MASK)
3218 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3219 return true;
3222 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3223 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3225 // Get prev block index
3226 CBlockIndex* pindexPrev = nullptr;
3227 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3228 if (mi == mapBlockIndex.end())
3229 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
3230 pindexPrev = (*mi).second;
3231 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3232 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3233 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3234 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3236 if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
3237 for (const CBlockIndex* failedit : g_failed_blocks) {
3238 if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
3239 assert(failedit->nStatus & BLOCK_FAILED_VALID);
3240 CBlockIndex* invalid_walk = pindexPrev;
3241 while (invalid_walk != failedit) {
3242 invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
3243 setDirtyBlockIndex.insert(invalid_walk);
3244 invalid_walk = invalid_walk->pprev;
3246 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3251 if (pindex == nullptr)
3252 pindex = AddToBlockIndex(block);
3254 if (ppindex)
3255 *ppindex = pindex;
3257 CheckBlockIndex(chainparams.GetConsensus());
3259 return true;
3262 // Exposed wrapper for AcceptBlockHeader
3263 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex, CBlockHeader *first_invalid)
3265 if (first_invalid != nullptr) first_invalid->SetNull();
3267 LOCK(cs_main);
3268 for (const CBlockHeader& header : headers) {
3269 CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3270 if (!g_chainstate.AcceptBlockHeader(header, state, chainparams, &pindex)) {
3271 if (first_invalid) *first_invalid = header;
3272 return false;
3274 if (ppindex) {
3275 *ppindex = pindex;
3279 NotifyHeaderTip();
3280 return true;
3283 /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
3284 static CDiskBlockPos SaveBlockToDisk(const CBlock& block, int nHeight, const CChainParams& chainparams, const CDiskBlockPos* dbp) {
3285 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3286 CDiskBlockPos blockPos;
3287 if (dbp != nullptr)
3288 blockPos = *dbp;
3289 if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr)) {
3290 error("%s: FindBlockPos failed", __func__);
3291 return CDiskBlockPos();
3293 if (dbp == nullptr) {
3294 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) {
3295 AbortNode("Failed to write block");
3296 return CDiskBlockPos();
3299 return blockPos;
3302 /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
3303 bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3305 const CBlock& block = *pblock;
3307 if (fNewBlock) *fNewBlock = false;
3308 AssertLockHeld(cs_main);
3310 CBlockIndex *pindexDummy = nullptr;
3311 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3313 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3314 return false;
3316 // Try to process all requested blocks that we don't have, but only
3317 // process an unrequested block if it's new and has enough work to
3318 // advance our tip, and isn't too many blocks ahead.
3319 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3320 bool fHasMoreOrSameWork = (chainActive.Tip() ? pindex->nChainWork >= chainActive.Tip()->nChainWork : true);
3321 // Blocks that are too out-of-order needlessly limit the effectiveness of
3322 // pruning, because pruning will not delete block files that contain any
3323 // blocks which are too close in height to the tip. Apply this test
3324 // regardless of whether pruning is enabled; it should generally be safe to
3325 // not process unrequested blocks.
3326 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3328 // TODO: Decouple this function from the block download logic by removing fRequested
3329 // This requires some new chain data structure to efficiently look up if a
3330 // block is in a chain leading to a candidate for best tip, despite not
3331 // being such a candidate itself.
3333 // TODO: deal better with return value and error conditions for duplicate
3334 // and unrequested blocks.
3335 if (fAlreadyHave) return true;
3336 if (!fRequested) { // If we didn't ask for it:
3337 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3338 if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
3339 if (fTooFarAhead) return true; // Block height is too high
3341 // Protect against DoS attacks from low-work chains.
3342 // If our tip is behind, a peer could try to send us
3343 // low-work blocks on a fake chain that we would never
3344 // request; don't process these.
3345 if (pindex->nChainWork < nMinimumChainWork) return true;
3347 if (fNewBlock) *fNewBlock = true;
3349 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3350 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3351 if (state.IsInvalid() && !state.CorruptionPossible()) {
3352 pindex->nStatus |= BLOCK_FAILED_VALID;
3353 setDirtyBlockIndex.insert(pindex);
3355 return error("%s: %s", __func__, FormatStateMessage(state));
3358 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3359 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3360 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3361 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3363 // Write block to history file
3364 try {
3365 CDiskBlockPos blockPos = SaveBlockToDisk(block, pindex->nHeight, chainparams, dbp);
3366 if (blockPos.IsNull()) {
3367 state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
3368 return false;
3370 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3371 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3372 } catch (const std::runtime_error& e) {
3373 return AbortNode(state, std::string("System error: ") + e.what());
3376 if (fCheckForPruning)
3377 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3379 CheckBlockIndex(chainparams.GetConsensus());
3381 return true;
3384 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3387 CBlockIndex *pindex = nullptr;
3388 if (fNewBlock) *fNewBlock = false;
3389 CValidationState state;
3390 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3391 // belt-and-suspenders.
3392 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3394 LOCK(cs_main);
3396 if (ret) {
3397 // Store to disk
3398 ret = g_chainstate.AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
3400 if (!ret) {
3401 GetMainSignals().BlockChecked(*pblock, state);
3402 return error("%s: AcceptBlock FAILED (%s)", __func__, state.GetDebugMessage());
3406 NotifyHeaderTip();
3408 CValidationState state; // Only used to report errors, not invalidity - ignore it
3409 if (!g_chainstate.ActivateBestChain(state, chainparams, pblock))
3410 return error("%s: ActivateBestChain failed", __func__);
3412 return true;
3415 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3417 AssertLockHeld(cs_main);
3418 assert(pindexPrev && pindexPrev == chainActive.Tip());
3419 CCoinsViewCache viewNew(pcoinsTip.get());
3420 CBlockIndex indexDummy(block);
3421 indexDummy.pprev = pindexPrev;
3422 indexDummy.nHeight = pindexPrev->nHeight + 1;
3424 // NOTE: CheckBlockHeader is called by CheckBlock
3425 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3426 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3427 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3428 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3429 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3430 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3431 if (!g_chainstate.ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3432 return false;
3433 assert(state.IsValid());
3435 return true;
3439 * BLOCK PRUNING CODE
3442 /* Calculate the amount of disk space the block & undo files currently use */
3443 uint64_t CalculateCurrentUsage()
3445 LOCK(cs_LastBlockFile);
3447 uint64_t retval = 0;
3448 for (const CBlockFileInfo &file : vinfoBlockFile) {
3449 retval += file.nSize + file.nUndoSize;
3451 return retval;
3454 /* Prune a block file (modify associated database entries)*/
3455 void PruneOneBlockFile(const int fileNumber)
3457 LOCK(cs_LastBlockFile);
3459 for (const auto& entry : mapBlockIndex) {
3460 CBlockIndex* pindex = entry.second;
3461 if (pindex->nFile == fileNumber) {
3462 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3463 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3464 pindex->nFile = 0;
3465 pindex->nDataPos = 0;
3466 pindex->nUndoPos = 0;
3467 setDirtyBlockIndex.insert(pindex);
3469 // Prune from mapBlocksUnlinked -- any block we prune would have
3470 // to be downloaded again in order to consider its chain, at which
3471 // point it would be considered as a candidate for
3472 // mapBlocksUnlinked or setBlockIndexCandidates.
3473 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3474 while (range.first != range.second) {
3475 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3476 range.first++;
3477 if (_it->second == pindex) {
3478 mapBlocksUnlinked.erase(_it);
3484 vinfoBlockFile[fileNumber].SetNull();
3485 setDirtyFileInfo.insert(fileNumber);
3489 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3491 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3492 CDiskBlockPos pos(*it, 0);
3493 fs::remove(GetBlockPosFilename(pos, "blk"));
3494 fs::remove(GetBlockPosFilename(pos, "rev"));
3495 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3499 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3500 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3502 assert(fPruneMode && nManualPruneHeight > 0);
3504 LOCK2(cs_main, cs_LastBlockFile);
3505 if (chainActive.Tip() == nullptr)
3506 return;
3508 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3509 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3510 int count=0;
3511 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3512 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3513 continue;
3514 PruneOneBlockFile(fileNumber);
3515 setFilesToPrune.insert(fileNumber);
3516 count++;
3518 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3521 /* This function is called from the RPC code for pruneblockchain */
3522 void PruneBlockFilesManual(int nManualPruneHeight)
3524 CValidationState state;
3525 const CChainParams& chainparams = Params();
3526 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
3530 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
3531 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
3532 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
3533 * (which in this case means the blockchain must be re-downloaded.)
3535 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
3536 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
3537 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
3538 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
3539 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
3540 * A db flag records the fact that at least some block files have been pruned.
3542 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
3544 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3546 LOCK2(cs_main, cs_LastBlockFile);
3547 if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
3548 return;
3550 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3551 return;
3554 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3555 uint64_t nCurrentUsage = CalculateCurrentUsage();
3556 // We don't check to prune until after we've allocated new space for files
3557 // So we should leave a buffer under our target to account for another allocation
3558 // before the next pruning.
3559 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3560 uint64_t nBytesToPrune;
3561 int count=0;
3563 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3564 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3565 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3567 if (vinfoBlockFile[fileNumber].nSize == 0)
3568 continue;
3570 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3571 break;
3573 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3574 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3575 continue;
3577 PruneOneBlockFile(fileNumber);
3578 // Queue up the files for removal
3579 setFilesToPrune.insert(fileNumber);
3580 nCurrentUsage -= nBytesToPrune;
3581 count++;
3585 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3586 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3587 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3588 nLastBlockWeCanPrune, count);
3591 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3593 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3595 // Check for nMinDiskSpace bytes (currently 50MB)
3596 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3597 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3599 return true;
3602 static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3604 if (pos.IsNull())
3605 return nullptr;
3606 fs::path path = GetBlockPosFilename(pos, prefix);
3607 fs::create_directories(path.parent_path());
3608 FILE* file = fsbridge::fopen(path, fReadOnly ? "rb": "rb+");
3609 if (!file && !fReadOnly)
3610 file = fsbridge::fopen(path, "wb+");
3611 if (!file) {
3612 LogPrintf("Unable to open file %s\n", path.string());
3613 return nullptr;
3615 if (pos.nPos) {
3616 if (fseek(file, pos.nPos, SEEK_SET)) {
3617 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3618 fclose(file);
3619 return nullptr;
3622 return file;
3625 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3626 return OpenDiskFile(pos, "blk", fReadOnly);
3629 /** Open an undo file (rev?????.dat) */
3630 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3631 return OpenDiskFile(pos, "rev", fReadOnly);
3634 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3636 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3639 CBlockIndex * CChainState::InsertBlockIndex(const uint256& hash)
3641 if (hash.IsNull())
3642 return nullptr;
3644 // Return existing
3645 BlockMap::iterator mi = mapBlockIndex.find(hash);
3646 if (mi != mapBlockIndex.end())
3647 return (*mi).second;
3649 // Create new
3650 CBlockIndex* pindexNew = new CBlockIndex();
3651 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3652 pindexNew->phashBlock = &((*mi).first);
3654 return pindexNew;
3657 bool CChainState::LoadBlockIndex(const Consensus::Params& consensus_params, CBlockTreeDB& blocktree)
3659 if (!blocktree.LoadBlockIndexGuts(consensus_params, [this](const uint256& hash){ return this->InsertBlockIndex(hash); }))
3660 return false;
3662 boost::this_thread::interruption_point();
3664 // Calculate nChainWork
3665 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3666 vSortedByHeight.reserve(mapBlockIndex.size());
3667 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3669 CBlockIndex* pindex = item.second;
3670 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3672 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3673 for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
3675 CBlockIndex* pindex = item.second;
3676 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3677 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3678 // We can link the chain of blocks for which we've received transactions at some point.
3679 // Pruned nodes may have deleted the block.
3680 if (pindex->nTx > 0) {
3681 if (pindex->pprev) {
3682 if (pindex->pprev->nChainTx) {
3683 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3684 } else {
3685 pindex->nChainTx = 0;
3686 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3688 } else {
3689 pindex->nChainTx = pindex->nTx;
3692 if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
3693 pindex->nStatus |= BLOCK_FAILED_CHILD;
3694 setDirtyBlockIndex.insert(pindex);
3696 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
3697 setBlockIndexCandidates.insert(pindex);
3698 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3699 pindexBestInvalid = pindex;
3700 if (pindex->pprev)
3701 pindex->BuildSkip();
3702 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3703 pindexBestHeader = pindex;
3706 return true;
3709 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3711 if (!g_chainstate.LoadBlockIndex(chainparams.GetConsensus(), *pblocktree))
3712 return false;
3714 // Load block file info
3715 pblocktree->ReadLastBlockFile(nLastBlockFile);
3716 vinfoBlockFile.resize(nLastBlockFile + 1);
3717 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3718 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3719 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3721 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3722 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3723 CBlockFileInfo info;
3724 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3725 vinfoBlockFile.push_back(info);
3726 } else {
3727 break;
3731 // Check presence of blk files
3732 LogPrintf("Checking all blk files are present...\n");
3733 std::set<int> setBlkDataFiles;
3734 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3736 CBlockIndex* pindex = item.second;
3737 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3738 setBlkDataFiles.insert(pindex->nFile);
3741 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3743 CDiskBlockPos pos(*it, 0);
3744 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3745 return false;
3749 // Check whether we have ever pruned block & undo files
3750 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3751 if (fHavePruned)
3752 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3754 // Check whether we need to continue reindexing
3755 bool fReindexing = false;
3756 pblocktree->ReadReindexing(fReindexing);
3757 if(fReindexing) fReindex = true;
3759 // Check whether we have a transaction index
3760 pblocktree->ReadFlag("txindex", fTxIndex);
3761 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3763 return true;
3766 bool LoadChainTip(const CChainParams& chainparams)
3768 if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
3770 if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
3771 // In case we just added the genesis block, connect it now, so
3772 // that we always have a chainActive.Tip() when we return.
3773 LogPrintf("%s: Connecting genesis block...\n", __func__);
3774 CValidationState state;
3775 if (!ActivateBestChain(state, chainparams)) {
3776 return false;
3780 // Load pointer to end of best chain
3781 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3782 if (it == mapBlockIndex.end())
3783 return false;
3784 chainActive.SetTip(it->second);
3786 g_chainstate.PruneBlockIndexCandidates();
3788 LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
3789 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3790 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3791 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3792 return true;
3795 CVerifyDB::CVerifyDB()
3797 uiInterface.ShowProgress(_("Verifying blocks..."), 0, false);
3800 CVerifyDB::~CVerifyDB()
3802 uiInterface.ShowProgress("", 100, false);
3805 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3807 LOCK(cs_main);
3808 if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
3809 return true;
3811 // Verify blocks in the best chain
3812 if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height())
3813 nCheckDepth = chainActive.Height();
3814 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3815 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3816 CCoinsViewCache coins(coinsview);
3817 CBlockIndex* pindexState = chainActive.Tip();
3818 CBlockIndex* pindexFailure = nullptr;
3819 int nGoodTransactions = 0;
3820 CValidationState state;
3821 int reportDone = 0;
3822 LogPrintf("[0%%]...");
3823 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3825 boost::this_thread::interruption_point();
3826 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3827 if (reportDone < percentageDone/10) {
3828 // report every 10% step
3829 LogPrintf("[%d%%]...", percentageDone);
3830 reportDone = percentageDone/10;
3832 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false);
3833 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3834 break;
3835 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3836 // If pruning, only go back as far as we have data.
3837 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3838 break;
3840 CBlock block;
3841 // check level 0: read from disk
3842 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3843 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3844 // check level 1: verify block validity
3845 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3846 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3847 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3848 // check level 2: verify undo validity
3849 if (nCheckLevel >= 2 && pindex) {
3850 CBlockUndo undo;
3851 if (!pindex->GetUndoPos().IsNull()) {
3852 if (!UndoReadFromDisk(undo, pindex)) {
3853 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3857 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3858 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3859 assert(coins.GetBestBlock() == pindex->GetBlockHash());
3860 DisconnectResult res = g_chainstate.DisconnectBlock(block, pindex, coins);
3861 if (res == DISCONNECT_FAILED) {
3862 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3864 pindexState = pindex->pprev;
3865 if (res == DISCONNECT_UNCLEAN) {
3866 nGoodTransactions = 0;
3867 pindexFailure = pindex;
3868 } else {
3869 nGoodTransactions += block.vtx.size();
3872 if (ShutdownRequested())
3873 return true;
3875 if (pindexFailure)
3876 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3878 // check level 4: try reconnecting blocks
3879 if (nCheckLevel >= 4) {
3880 CBlockIndex *pindex = pindexState;
3881 while (pindex != chainActive.Tip()) {
3882 boost::this_thread::interruption_point();
3883 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))), false);
3884 pindex = chainActive.Next(pindex);
3885 CBlock block;
3886 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3887 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3888 if (!g_chainstate.ConnectBlock(block, state, pindex, coins, chainparams))
3889 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3893 LogPrintf("[DONE].\n");
3894 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3896 return true;
3899 /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
3900 bool CChainState::RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
3902 // TODO: merge with ConnectBlock
3903 CBlock block;
3904 if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
3905 return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3908 for (const CTransactionRef& tx : block.vtx) {
3909 if (!tx->IsCoinBase()) {
3910 for (const CTxIn &txin : tx->vin) {
3911 inputs.SpendCoin(txin.prevout);
3914 // Pass check = true as every addition may be an overwrite.
3915 AddCoins(inputs, *tx, pindex->nHeight, true);
3917 return true;
3920 bool CChainState::ReplayBlocks(const CChainParams& params, CCoinsView* view)
3922 LOCK(cs_main);
3924 CCoinsViewCache cache(view);
3926 std::vector<uint256> hashHeads = view->GetHeadBlocks();
3927 if (hashHeads.empty()) return true; // We're already in a consistent state.
3928 if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
3930 uiInterface.ShowProgress(_("Replaying blocks..."), 0, false);
3931 LogPrintf("Replaying blocks\n");
3933 const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
3934 const CBlockIndex* pindexNew; // New tip during the interrupted flush.
3935 const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
3937 if (mapBlockIndex.count(hashHeads[0]) == 0) {
3938 return error("ReplayBlocks(): reorganization to unknown block requested");
3940 pindexNew = mapBlockIndex[hashHeads[0]];
3942 if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
3943 if (mapBlockIndex.count(hashHeads[1]) == 0) {
3944 return error("ReplayBlocks(): reorganization from unknown block requested");
3946 pindexOld = mapBlockIndex[hashHeads[1]];
3947 pindexFork = LastCommonAncestor(pindexOld, pindexNew);
3948 assert(pindexFork != nullptr);
3951 // Rollback along the old branch.
3952 while (pindexOld != pindexFork) {
3953 if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
3954 CBlock block;
3955 if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
3956 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3958 LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
3959 DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
3960 if (res == DISCONNECT_FAILED) {
3961 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3963 // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
3964 // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
3965 // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
3966 // the result is still a version of the UTXO set with the effects of that block undone.
3968 pindexOld = pindexOld->pprev;
3971 // Roll forward from the forking point to the new tip.
3972 int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
3973 for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
3974 const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
3975 LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
3976 if (!RollforwardBlock(pindex, cache, params)) return false;
3979 cache.SetBestBlock(pindexNew->GetBlockHash());
3980 cache.Flush();
3981 uiInterface.ShowProgress("", 100, false);
3982 return true;
3985 bool ReplayBlocks(const CChainParams& params, CCoinsView* view) {
3986 return g_chainstate.ReplayBlocks(params, view);
3989 bool CChainState::RewindBlockIndex(const CChainParams& params)
3991 LOCK(cs_main);
3993 // Note that during -reindex-chainstate we are called with an empty chainActive!
3995 int nHeight = 1;
3996 while (nHeight <= chainActive.Height()) {
3997 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3998 break;
4000 nHeight++;
4003 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
4004 CValidationState state;
4005 CBlockIndex* pindex = chainActive.Tip();
4006 while (chainActive.Height() >= nHeight) {
4007 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
4008 // If pruning, don't try rewinding past the HAVE_DATA point;
4009 // since older blocks can't be served anyway, there's
4010 // no need to walk further, and trying to DisconnectTip()
4011 // will fail (and require a needless reindex/redownload
4012 // of the blockchain).
4013 break;
4015 if (!DisconnectTip(state, params, nullptr)) {
4016 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
4018 // Occasionally flush state to disk.
4019 if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
4020 return false;
4023 // Reduce validity flag and have-data flags.
4024 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
4025 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
4026 for (const auto& entry : mapBlockIndex) {
4027 CBlockIndex* pindexIter = entry.second;
4029 // Note: If we encounter an insufficiently validated block that
4030 // is on chainActive, it must be because we are a pruning node, and
4031 // this block or some successor doesn't HAVE_DATA, so we were unable to
4032 // rewind all the way. Blocks remaining on chainActive at this point
4033 // must not have their validity reduced.
4034 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
4035 // Reduce validity
4036 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
4037 // Remove have-data flags.
4038 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
4039 // Remove storage location.
4040 pindexIter->nFile = 0;
4041 pindexIter->nDataPos = 0;
4042 pindexIter->nUndoPos = 0;
4043 // Remove various other things
4044 pindexIter->nTx = 0;
4045 pindexIter->nChainTx = 0;
4046 pindexIter->nSequenceId = 0;
4047 // Make sure it gets written.
4048 setDirtyBlockIndex.insert(pindexIter);
4049 // Update indexes
4050 setBlockIndexCandidates.erase(pindexIter);
4051 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
4052 while (ret.first != ret.second) {
4053 if (ret.first->second == pindexIter) {
4054 mapBlocksUnlinked.erase(ret.first++);
4055 } else {
4056 ++ret.first;
4059 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
4060 setBlockIndexCandidates.insert(pindexIter);
4064 if (chainActive.Tip() != nullptr) {
4065 // We can't prune block index candidates based on our tip if we have
4066 // no tip due to chainActive being empty!
4067 PruneBlockIndexCandidates();
4069 CheckBlockIndex(params.GetConsensus());
4072 return true;
4075 bool RewindBlockIndex(const CChainParams& params) {
4076 if (!g_chainstate.RewindBlockIndex(params)) {
4077 return false;
4080 if (chainActive.Tip() != nullptr) {
4081 // FlushStateToDisk can possibly read chainActive. Be conservative
4082 // and skip it here, we're about to -reindex-chainstate anyway, so
4083 // it'll get called a bunch real soon.
4084 CValidationState state;
4085 if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
4086 return false;
4090 return true;
4093 void CChainState::UnloadBlockIndex() {
4094 nBlockSequenceId = 1;
4095 g_failed_blocks.clear();
4096 setBlockIndexCandidates.clear();
4099 // May NOT be used after any connections are up as much
4100 // of the peer-processing logic assumes a consistent
4101 // block index state
4102 void UnloadBlockIndex()
4104 LOCK(cs_main);
4105 chainActive.SetTip(nullptr);
4106 pindexBestInvalid = nullptr;
4107 pindexBestHeader = nullptr;
4108 mempool.clear();
4109 mapBlocksUnlinked.clear();
4110 vinfoBlockFile.clear();
4111 nLastBlockFile = 0;
4112 setDirtyBlockIndex.clear();
4113 setDirtyFileInfo.clear();
4114 versionbitscache.Clear();
4115 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
4116 warningcache[b].clear();
4119 for (BlockMap::value_type& entry : mapBlockIndex) {
4120 delete entry.second;
4122 mapBlockIndex.clear();
4123 fHavePruned = false;
4125 g_chainstate.UnloadBlockIndex();
4128 bool LoadBlockIndex(const CChainParams& chainparams)
4130 // Load block index from databases
4131 bool needs_init = fReindex;
4132 if (!fReindex) {
4133 bool ret = LoadBlockIndexDB(chainparams);
4134 if (!ret) return false;
4135 needs_init = mapBlockIndex.empty();
4138 if (needs_init) {
4139 // Everything here is for *new* reindex/DBs. Thus, though
4140 // LoadBlockIndexDB may have set fReindex if we shut down
4141 // mid-reindex previously, we don't check fReindex and
4142 // instead only check it prior to LoadBlockIndexDB to set
4143 // needs_init.
4145 LogPrintf("Initializing databases...\n");
4146 // Use the provided setting for -txindex in the new database
4147 fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
4148 pblocktree->WriteFlag("txindex", fTxIndex);
4150 return true;
4153 bool CChainState::LoadGenesisBlock(const CChainParams& chainparams)
4155 LOCK(cs_main);
4157 // Check whether we're already initialized by checking for genesis in
4158 // mapBlockIndex. Note that we can't use chainActive here, since it is
4159 // set based on the coins db, not the block index db, which is the only
4160 // thing loaded at this point.
4161 if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
4162 return true;
4164 try {
4165 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
4166 CDiskBlockPos blockPos = SaveBlockToDisk(block, 0, chainparams, nullptr);
4167 if (blockPos.IsNull())
4168 return error("%s: writing genesis block to disk failed", __func__);
4169 CBlockIndex *pindex = AddToBlockIndex(block);
4170 CValidationState state;
4171 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
4172 return error("%s: genesis block not accepted", __func__);
4173 } catch (const std::runtime_error& e) {
4174 return error("%s: failed to write genesis block: %s", __func__, e.what());
4177 return true;
4180 bool LoadGenesisBlock(const CChainParams& chainparams)
4182 return g_chainstate.LoadGenesisBlock(chainparams);
4185 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
4187 // Map of disk positions for blocks with unknown parent (only used for reindex)
4188 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4189 int64_t nStart = GetTimeMillis();
4191 int nLoaded = 0;
4192 try {
4193 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4194 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
4195 uint64_t nRewind = blkdat.GetPos();
4196 while (!blkdat.eof()) {
4197 boost::this_thread::interruption_point();
4199 blkdat.SetPos(nRewind);
4200 nRewind++; // start one byte further next time, in case of failure
4201 blkdat.SetLimit(); // remove former limit
4202 unsigned int nSize = 0;
4203 try {
4204 // locate a header
4205 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
4206 blkdat.FindByte(chainparams.MessageStart()[0]);
4207 nRewind = blkdat.GetPos()+1;
4208 blkdat >> FLATDATA(buf);
4209 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
4210 continue;
4211 // read size
4212 blkdat >> nSize;
4213 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
4214 continue;
4215 } catch (const std::exception&) {
4216 // no valid block header found; don't complain
4217 break;
4219 try {
4220 // read block
4221 uint64_t nBlockPos = blkdat.GetPos();
4222 if (dbp)
4223 dbp->nPos = nBlockPos;
4224 blkdat.SetLimit(nBlockPos + nSize);
4225 blkdat.SetPos(nBlockPos);
4226 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4227 CBlock& block = *pblock;
4228 blkdat >> block;
4229 nRewind = blkdat.GetPos();
4231 // detect out of order blocks, and store them for later
4232 uint256 hash = block.GetHash();
4233 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4234 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4235 block.hashPrevBlock.ToString());
4236 if (dbp)
4237 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4238 continue;
4241 // process in case the block isn't known yet
4242 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4243 LOCK(cs_main);
4244 CValidationState state;
4245 if (g_chainstate.AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
4246 nLoaded++;
4247 if (state.IsError())
4248 break;
4249 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4250 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4253 // Activate the genesis block so normal node progress can continue
4254 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
4255 CValidationState state;
4256 if (!ActivateBestChain(state, chainparams)) {
4257 break;
4261 NotifyHeaderTip();
4263 // Recursively process earlier encountered successors of this block
4264 std::deque<uint256> queue;
4265 queue.push_back(hash);
4266 while (!queue.empty()) {
4267 uint256 head = queue.front();
4268 queue.pop_front();
4269 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4270 while (range.first != range.second) {
4271 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4272 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4273 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
4275 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4276 head.ToString());
4277 LOCK(cs_main);
4278 CValidationState dummy;
4279 if (g_chainstate.AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
4281 nLoaded++;
4282 queue.push_back(pblockrecursive->GetHash());
4285 range.first++;
4286 mapBlocksUnknownParent.erase(it);
4287 NotifyHeaderTip();
4290 } catch (const std::exception& e) {
4291 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4294 } catch (const std::runtime_error& e) {
4295 AbortNode(std::string("System error: ") + e.what());
4297 if (nLoaded > 0)
4298 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4299 return nLoaded > 0;
4302 void CChainState::CheckBlockIndex(const Consensus::Params& consensusParams)
4304 if (!fCheckBlockIndex) {
4305 return;
4308 LOCK(cs_main);
4310 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4311 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4312 // iterating the block tree require that chainActive has been initialized.)
4313 if (chainActive.Height() < 0) {
4314 assert(mapBlockIndex.size() <= 1);
4315 return;
4318 // Build forward-pointing map of the entire block tree.
4319 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4320 for (auto& entry : mapBlockIndex) {
4321 forward.insert(std::make_pair(entry.second->pprev, entry.second));
4324 assert(forward.size() == mapBlockIndex.size());
4326 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4327 CBlockIndex *pindex = rangeGenesis.first->second;
4328 rangeGenesis.first++;
4329 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4331 // Iterate over the entire block tree, using depth-first search.
4332 // Along the way, remember whether there are blocks on the path from genesis
4333 // block being explored which are the first to have certain properties.
4334 size_t nNodes = 0;
4335 int nHeight = 0;
4336 CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4337 CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4338 CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4339 CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4340 CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4341 CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4342 CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4343 while (pindex != nullptr) {
4344 nNodes++;
4345 if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4346 if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4347 if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4348 if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4349 if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4350 if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4351 if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4353 // Begin: actual consistency checks.
4354 if (pindex->pprev == nullptr) {
4355 // Genesis block checks.
4356 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4357 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4359 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)
4360 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4361 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4362 if (!fHavePruned) {
4363 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4364 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4365 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4366 } else {
4367 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4368 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4370 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4371 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4372 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4373 assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4374 assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
4375 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4376 assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
4377 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4378 assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
4379 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4380 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4381 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4382 if (pindexFirstInvalid == nullptr) {
4383 // Checks for not-invalid blocks.
4384 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4386 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
4387 if (pindexFirstInvalid == nullptr) {
4388 // If this block sorts at least as good as the current tip and
4389 // is valid and we have all data for its parents, it must be in
4390 // setBlockIndexCandidates. chainActive.Tip() must also be there
4391 // even if some data has been pruned.
4392 if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
4393 assert(setBlockIndexCandidates.count(pindex));
4395 // If some parent is missing, then it could be that this block was in
4396 // setBlockIndexCandidates but had to be removed because of the missing data.
4397 // In this case it must be in mapBlocksUnlinked -- see test below.
4399 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4400 assert(setBlockIndexCandidates.count(pindex) == 0);
4402 // Check whether this block is in mapBlocksUnlinked.
4403 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4404 bool foundInUnlinked = false;
4405 while (rangeUnlinked.first != rangeUnlinked.second) {
4406 assert(rangeUnlinked.first->first == pindex->pprev);
4407 if (rangeUnlinked.first->second == pindex) {
4408 foundInUnlinked = true;
4409 break;
4411 rangeUnlinked.first++;
4413 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4414 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4415 assert(foundInUnlinked);
4417 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4418 if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4419 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4420 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4421 assert(fHavePruned); // We must have pruned.
4422 // This block may have entered mapBlocksUnlinked if:
4423 // - it has a descendant that at some point had more work than the
4424 // tip, and
4425 // - we tried switching to that descendant but were missing
4426 // data for some intermediate block between chainActive and the
4427 // tip.
4428 // So if this block is itself better than chainActive.Tip() and it wasn't in
4429 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4430 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4431 if (pindexFirstInvalid == nullptr) {
4432 assert(foundInUnlinked);
4436 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4437 // End: actual consistency checks.
4439 // Try descending into the first subnode.
4440 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4441 if (range.first != range.second) {
4442 // A subnode was found.
4443 pindex = range.first->second;
4444 nHeight++;
4445 continue;
4447 // This is a leaf node.
4448 // Move upwards until we reach a node of which we have not yet visited the last child.
4449 while (pindex) {
4450 // We are going to either move to a parent or a sibling of pindex.
4451 // If pindex was the first with a certain property, unset the corresponding variable.
4452 if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4453 if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4454 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4455 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4456 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4457 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4458 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4459 // Find our parent.
4460 CBlockIndex* pindexPar = pindex->pprev;
4461 // Find which child we just visited.
4462 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4463 while (rangePar.first->second != pindex) {
4464 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4465 rangePar.first++;
4467 // Proceed to the next one.
4468 rangePar.first++;
4469 if (rangePar.first != rangePar.second) {
4470 // Move to the sibling.
4471 pindex = rangePar.first->second;
4472 break;
4473 } else {
4474 // Move up further.
4475 pindex = pindexPar;
4476 nHeight--;
4477 continue;
4482 // Check that we actually traversed the entire map.
4483 assert(nNodes == forward.size());
4486 std::string CBlockFileInfo::ToString() const
4488 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));
4491 CBlockFileInfo* GetBlockFileInfo(size_t n)
4493 LOCK(cs_LastBlockFile);
4495 return &vinfoBlockFile.at(n);
4498 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
4500 LOCK(cs_main);
4501 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4504 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
4506 LOCK(cs_main);
4507 return VersionBitsStatistics(chainActive.Tip(), params, pos);
4510 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
4512 LOCK(cs_main);
4513 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
4516 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4518 bool LoadMempool(void)
4520 const CChainParams& chainparams = Params();
4521 int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4522 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4523 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4524 if (file.IsNull()) {
4525 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4526 return false;
4529 int64_t count = 0;
4530 int64_t expired = 0;
4531 int64_t failed = 0;
4532 int64_t already_there = 0;
4533 int64_t nNow = GetTime();
4535 try {
4536 uint64_t version;
4537 file >> version;
4538 if (version != MEMPOOL_DUMP_VERSION) {
4539 return false;
4541 uint64_t num;
4542 file >> num;
4543 while (num--) {
4544 CTransactionRef tx;
4545 int64_t nTime;
4546 int64_t nFeeDelta;
4547 file >> tx;
4548 file >> nTime;
4549 file >> nFeeDelta;
4551 CAmount amountdelta = nFeeDelta;
4552 if (amountdelta) {
4553 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4555 CValidationState state;
4556 if (nTime + nExpiryTimeout > nNow) {
4557 LOCK(cs_main);
4558 AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, nullptr /* pfMissingInputs */, nTime,
4559 nullptr /* plTxnReplaced */, false /* bypass_limits */, 0 /* nAbsurdFee */);
4560 if (state.IsValid()) {
4561 ++count;
4562 } else {
4563 // mempool may contain the transaction already, e.g. from
4564 // wallet(s) having loaded it while we were processing
4565 // mempool transactions; consider these as valid, instead of
4566 // failed, but mark them as 'already there'
4567 if (mempool.exists(tx->GetHash())) {
4568 ++already_there;
4569 } else {
4570 ++failed;
4573 } else {
4574 ++expired;
4576 if (ShutdownRequested())
4577 return false;
4579 std::map<uint256, CAmount> mapDeltas;
4580 file >> mapDeltas;
4582 for (const auto& i : mapDeltas) {
4583 mempool.PrioritiseTransaction(i.first, i.second);
4585 } catch (const std::exception& e) {
4586 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4587 return false;
4590 LogPrintf("Imported mempool transactions from disk: %i succeeded, %i failed, %i expired, %i already there\n", count, failed, expired, already_there);
4591 return true;
4594 bool DumpMempool(void)
4596 int64_t start = GetTimeMicros();
4598 std::map<uint256, CAmount> mapDeltas;
4599 std::vector<TxMempoolInfo> vinfo;
4602 LOCK(mempool.cs);
4603 for (const auto &i : mempool.mapDeltas) {
4604 mapDeltas[i.first] = i.second;
4606 vinfo = mempool.infoAll();
4609 int64_t mid = GetTimeMicros();
4611 try {
4612 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4613 if (!filestr) {
4614 return false;
4617 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4619 uint64_t version = MEMPOOL_DUMP_VERSION;
4620 file << version;
4622 file << (uint64_t)vinfo.size();
4623 for (const auto& i : vinfo) {
4624 file << *(i.tx);
4625 file << (int64_t)i.nTime;
4626 file << (int64_t)i.nFeeDelta;
4627 mapDeltas.erase(i.tx->GetHash());
4630 file << mapDeltas;
4631 FileCommit(file.Get());
4632 file.fclose();
4633 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4634 int64_t last = GetTimeMicros();
4635 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
4636 } catch (const std::exception& e) {
4637 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4638 return false;
4640 return true;
4643 //! Guess how far we are in the verification process at the given block index
4644 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex *pindex) {
4645 if (pindex == nullptr)
4646 return 0.0;
4648 int64_t nNow = time(nullptr);
4650 double fTxTotal;
4652 if (pindex->nChainTx <= data.nTxCount) {
4653 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4654 } else {
4655 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4658 return pindex->nChainTx / fTxTotal;
4661 class CMainCleanup
4663 public:
4664 CMainCleanup() {}
4665 ~CMainCleanup() {
4666 // block headers
4667 BlockMap::iterator it1 = mapBlockIndex.begin();
4668 for (; it1 != mapBlockIndex.end(); it1++)
4669 delete (*it1).second;
4670 mapBlockIndex.clear();
4672 } instance_of_cmaincleanup;