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"
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"
20 #include "policy/fees.h"
21 #include "policy/policy.h"
23 #include "primitives/block.h"
24 #include "primitives/transaction.h"
26 #include "script/script.h"
27 #include "script/sigcache.h"
28 #include "script/standard.h"
30 #include "tinyformat.h"
32 #include "txmempool.h"
33 #include "ui_interface.h"
36 #include "utilmoneystr.h"
37 #include "utilstrencodings.h"
38 #include "validationinterface.h"
39 #include "versionbits.h"
45 #include <boost/algorithm/string/replace.hpp>
46 #include <boost/algorithm/string/join.hpp>
47 #include <boost/thread.hpp>
50 # error "Bitcoin cannot be compiled without assertions."
57 CCriticalSection cs_main
;
59 BlockMap mapBlockIndex
;
61 CBlockIndex
*pindexBestHeader
= NULL
;
62 CWaitableCriticalSection csBestBlock
;
63 CConditionVariable cvBlockChange
;
64 int nScriptCheckThreads
= 0;
65 std::atomic_bool
fImporting(false);
66 bool fReindex
= false;
67 bool fTxIndex
= false;
68 bool fHavePruned
= false;
69 bool fPruneMode
= false;
70 bool fIsBareMultisigStd
= DEFAULT_PERMIT_BAREMULTISIG
;
71 bool fRequireStandard
= true;
72 bool fCheckBlockIndex
= false;
73 bool fCheckpointsEnabled
= DEFAULT_CHECKPOINTS_ENABLED
;
74 size_t nCoinCacheUsage
= 5000 * 300;
75 uint64_t nPruneTarget
= 0;
76 int64_t nMaxTipAge
= DEFAULT_MAX_TIP_AGE
;
77 bool fEnableReplacement
= DEFAULT_ENABLE_REPLACEMENT
;
79 uint256 hashAssumeValid
;
81 CFeeRate minRelayTxFee
= CFeeRate(DEFAULT_MIN_RELAY_TX_FEE
);
82 CAmount maxTxFee
= DEFAULT_TRANSACTION_MAXFEE
;
84 CBlockPolicyEstimator feeEstimator
;
85 CTxMemPool
mempool(&feeEstimator
);
87 static void CheckBlockIndex(const Consensus::Params
& consensusParams
);
89 /** Constant stuff for coinbase transactions we create: */
90 CScript COINBASE_FLAGS
;
92 const std::string strMessageMagic
= "Bitcoin Signed Message:\n";
97 struct CBlockIndexWorkComparator
99 bool operator()(CBlockIndex
*pa
, CBlockIndex
*pb
) const {
100 // First sort by most total work, ...
101 if (pa
->nChainWork
> pb
->nChainWork
) return false;
102 if (pa
->nChainWork
< pb
->nChainWork
) return true;
104 // ... then by earliest time received, ...
105 if (pa
->nSequenceId
< pb
->nSequenceId
) return false;
106 if (pa
->nSequenceId
> pb
->nSequenceId
) return true;
108 // Use pointer address as tie breaker (should only happen with blocks
109 // loaded from disk, as those all have id 0).
110 if (pa
< pb
) return false;
111 if (pa
> pb
) return true;
118 CBlockIndex
*pindexBestInvalid
;
121 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
122 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
123 * missing the data for the block.
125 std::set
<CBlockIndex
*, CBlockIndexWorkComparator
> setBlockIndexCandidates
;
126 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
127 * Pruned nodes may have entries where B is missing data.
129 std::multimap
<CBlockIndex
*, CBlockIndex
*> mapBlocksUnlinked
;
131 CCriticalSection cs_LastBlockFile
;
132 std::vector
<CBlockFileInfo
> vinfoBlockFile
;
133 int nLastBlockFile
= 0;
134 /** Global flag to indicate we should check to see if there are
135 * block/undo files that should be deleted. Set on startup
136 * or if we allocate more file space when we're in prune mode
138 bool fCheckForPruning
= false;
141 * Every received block is assigned a unique and increasing identifier, so we
142 * know which one to give priority in case of a fork.
144 CCriticalSection cs_nBlockSequenceId
;
145 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
146 int32_t nBlockSequenceId
= 1;
147 /** Decreasing counter (used by subsequent preciousblock calls). */
148 int32_t nBlockReverseSequenceId
= -1;
149 /** chainwork for the last block that preciousblock has been applied to. */
150 arith_uint256 nLastPreciousChainwork
= 0;
152 /** Dirty block index entries. */
153 std::set
<CBlockIndex
*> setDirtyBlockIndex
;
155 /** Dirty block file entries. */
156 std::set
<int> setDirtyFileInfo
;
159 CBlockIndex
* FindForkInGlobalIndex(const CChain
& chain
, const CBlockLocator
& locator
)
161 // Find the first block the caller has in the main chain
162 for (const uint256
& hash
: locator
.vHave
) {
163 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
164 if (mi
!= mapBlockIndex
.end())
166 CBlockIndex
* pindex
= (*mi
).second
;
167 if (chain
.Contains(pindex
))
169 if (pindex
->GetAncestor(chain
.Height()) == chain
.Tip()) {
174 return chain
.Genesis();
177 CCoinsViewDB
*pcoinsdbview
= NULL
;
178 CCoinsViewCache
*pcoinsTip
= NULL
;
179 CBlockTreeDB
*pblocktree
= NULL
;
181 enum FlushStateMode
{
183 FLUSH_STATE_IF_NEEDED
,
184 FLUSH_STATE_PERIODIC
,
188 // See definition for documentation
189 static bool FlushStateToDisk(const CChainParams
& chainParams
, CValidationState
&state
, FlushStateMode mode
, int nManualPruneHeight
=0);
190 static void FindFilesToPruneManual(std::set
<int>& setFilesToPrune
, int nManualPruneHeight
);
191 static void FindFilesToPrune(std::set
<int>& setFilesToPrune
, uint64_t nPruneAfterHeight
);
192 static bool CheckInputs(const CTransaction
& tx
, CValidationState
&state
, const CCoinsViewCache
&inputs
, bool fScriptChecks
, unsigned int flags
, bool cacheStore
, PrecomputedTransactionData
& txdata
, std::vector
<CScriptCheck
> *pvChecks
= NULL
);
193 static FILE* OpenUndoFile(const CDiskBlockPos
&pos
, bool fReadOnly
= false);
195 bool CheckFinalTx(const CTransaction
&tx
, int flags
)
197 AssertLockHeld(cs_main
);
199 // By convention a negative value for flags indicates that the
200 // current network-enforced consensus rules should be used. In
201 // a future soft-fork scenario that would mean checking which
202 // rules would be enforced for the next block and setting the
203 // appropriate flags. At the present time no soft-forks are
204 // scheduled, so no flags are set.
205 flags
= std::max(flags
, 0);
207 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
208 // nLockTime because when IsFinalTx() is called within
209 // CBlock::AcceptBlock(), the height of the block *being*
210 // evaluated is what is used. Thus if we want to know if a
211 // transaction can be part of the *next* block, we need to call
212 // IsFinalTx() with one more than chainActive.Height().
213 const int nBlockHeight
= chainActive
.Height() + 1;
215 // BIP113 will require that time-locked transactions have nLockTime set to
216 // less than the median time of the previous block they're contained in.
217 // When the next block is created its previous block will be the current
218 // chain tip, so we use that to calculate the median time passed to
219 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
220 const int64_t nBlockTime
= (flags
& LOCKTIME_MEDIAN_TIME_PAST
)
221 ? chainActive
.Tip()->GetMedianTimePast()
224 return IsFinalTx(tx
, nBlockHeight
, nBlockTime
);
227 bool TestLockPointValidity(const LockPoints
* lp
)
229 AssertLockHeld(cs_main
);
231 // If there are relative lock times then the maxInputBlock will be set
232 // If there are no relative lock times, the LockPoints don't depend on the chain
233 if (lp
->maxInputBlock
) {
234 // Check whether chainActive is an extension of the block at which the LockPoints
235 // calculation was valid. If not LockPoints are no longer valid
236 if (!chainActive
.Contains(lp
->maxInputBlock
)) {
241 // LockPoints still valid
245 bool CheckSequenceLocks(const CTransaction
&tx
, int flags
, LockPoints
* lp
, bool useExistingLockPoints
)
247 AssertLockHeld(cs_main
);
248 AssertLockHeld(mempool
.cs
);
250 CBlockIndex
* tip
= chainActive
.Tip();
253 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
254 // height based locks because when SequenceLocks() is called within
255 // ConnectBlock(), the height of the block *being*
256 // evaluated is what is used.
257 // Thus if we want to know if a transaction can be part of the
258 // *next* block, we need to use one more than chainActive.Height()
259 index
.nHeight
= tip
->nHeight
+ 1;
261 std::pair
<int, int64_t> lockPair
;
262 if (useExistingLockPoints
) {
264 lockPair
.first
= lp
->height
;
265 lockPair
.second
= lp
->time
;
268 // pcoinsTip contains the UTXO set for chainActive.Tip()
269 CCoinsViewMemPool
viewMemPool(pcoinsTip
, mempool
);
270 std::vector
<int> prevheights
;
271 prevheights
.resize(tx
.vin
.size());
272 for (size_t txinIndex
= 0; txinIndex
< tx
.vin
.size(); txinIndex
++) {
273 const CTxIn
& txin
= tx
.vin
[txinIndex
];
275 if (!viewMemPool
.GetCoin(txin
.prevout
, coin
)) {
276 return error("%s: Missing input", __func__
);
278 if (coin
.nHeight
== MEMPOOL_HEIGHT
) {
279 // Assume all mempool transaction confirm in the next block
280 prevheights
[txinIndex
] = tip
->nHeight
+ 1;
282 prevheights
[txinIndex
] = coin
.nHeight
;
285 lockPair
= CalculateSequenceLocks(tx
, flags
, &prevheights
, index
);
287 lp
->height
= lockPair
.first
;
288 lp
->time
= lockPair
.second
;
289 // Also store the hash of the block with the highest height of
290 // all the blocks which have sequence locked prevouts.
291 // This hash needs to still be on the chain
292 // for these LockPoint calculations to be valid
293 // Note: It is impossible to correctly calculate a maxInputBlock
294 // if any of the sequence locked inputs depend on unconfirmed txs,
295 // except in the special case where the relative lock time/height
296 // is 0, which is equivalent to no sequence lock. Since we assume
297 // input height of tip+1 for mempool txs and test the resulting
298 // lockPair from CalculateSequenceLocks against tip+1. We know
299 // EvaluateSequenceLocks will fail if there was a non-zero sequence
300 // lock on a mempool input, so we can use the return value of
301 // CheckSequenceLocks to indicate the LockPoints validity
302 int maxInputHeight
= 0;
303 for (int height
: prevheights
) {
304 // Can ignore mempool inputs since we'll fail if they had non-zero locks
305 if (height
!= tip
->nHeight
+1) {
306 maxInputHeight
= std::max(maxInputHeight
, height
);
309 lp
->maxInputBlock
= tip
->GetAncestor(maxInputHeight
);
312 return EvaluateSequenceLocks(index
, lockPair
);
315 static void LimitMempoolSize(CTxMemPool
& pool
, size_t limit
, unsigned long age
) {
316 int expired
= pool
.Expire(GetTime() - age
);
318 LogPrint(BCLog::MEMPOOL
, "Expired %i transactions from the memory pool\n", expired
);
321 std::vector
<COutPoint
> vNoSpendsRemaining
;
322 pool
.TrimToSize(limit
, &vNoSpendsRemaining
);
323 for (const COutPoint
& removed
: vNoSpendsRemaining
)
324 pcoinsTip
->Uncache(removed
);
327 /** Convert CValidationState to a human-readable message for logging */
328 std::string
FormatStateMessage(const CValidationState
&state
)
330 return strprintf("%s%s (code %i)",
331 state
.GetRejectReason(),
332 state
.GetDebugMessage().empty() ? "" : ", "+state
.GetDebugMessage(),
333 state
.GetRejectCode());
336 static bool IsCurrentForFeeEstimation()
338 AssertLockHeld(cs_main
);
339 if (IsInitialBlockDownload())
341 if (chainActive
.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE
))
343 if (chainActive
.Height() < pindexBestHeader
->nHeight
- 1)
348 /* Make mempool consistent after a reorg, by re-adding or recursively erasing
349 * disconnected block transactions from the mempool, and also removing any
350 * other transactions from the mempool that are no longer valid given the new
353 * Note: we assume that disconnectpool only contains transactions that are NOT
354 * confirmed in the current chain nor already in the mempool (otherwise,
355 * in-mempool descendants of such transactions would be removed).
357 * Passing fAddToMempool=false will skip trying to add the transactions back,
358 * and instead just erase from the mempool as needed.
361 void UpdateMempoolForReorg(DisconnectedBlockTransactions
&disconnectpool
, bool fAddToMempool
)
363 AssertLockHeld(cs_main
);
364 std::vector
<uint256
> vHashUpdate
;
365 // disconnectpool's insertion_order index sorts the entries from
366 // oldest to newest, but the oldest entry will be the last tx from the
367 // latest mined block that was disconnected.
368 // Iterate disconnectpool in reverse, so that we add transactions
369 // back to the mempool starting with the earliest transaction that had
370 // been previously seen in a block.
371 auto it
= disconnectpool
.queuedTx
.get
<insertion_order
>().rbegin();
372 while (it
!= disconnectpool
.queuedTx
.get
<insertion_order
>().rend()) {
373 // ignore validation errors in resurrected transactions
374 CValidationState stateDummy
;
375 if (!fAddToMempool
|| (*it
)->IsCoinBase() || !AcceptToMemoryPool(mempool
, stateDummy
, *it
, false, NULL
, NULL
, true)) {
376 // If the transaction doesn't make it in to the mempool, remove any
377 // transactions that depend on it (which would now be orphans).
378 mempool
.removeRecursive(**it
, MemPoolRemovalReason::REORG
);
379 } else if (mempool
.exists((*it
)->GetHash())) {
380 vHashUpdate
.push_back((*it
)->GetHash());
384 disconnectpool
.queuedTx
.clear();
385 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
386 // no in-mempool children, which is generally not true when adding
387 // previously-confirmed transactions back to the mempool.
388 // UpdateTransactionsFromBlock finds descendants of any transactions in
389 // the disconnectpool that were added back and cleans up the mempool state.
390 mempool
.UpdateTransactionsFromBlock(vHashUpdate
);
392 // We also need to remove any now-immature transactions
393 mempool
.removeForReorg(pcoinsTip
, chainActive
.Tip()->nHeight
+ 1, STANDARD_LOCKTIME_VERIFY_FLAGS
);
394 // Re-limit mempool size, in case we added any transactions
395 LimitMempoolSize(mempool
, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY
) * 60 * 60);
398 static bool AcceptToMemoryPoolWorker(const CChainParams
& chainparams
, CTxMemPool
& pool
, CValidationState
& state
, const CTransactionRef
& ptx
, bool fLimitFree
,
399 bool* pfMissingInputs
, int64_t nAcceptTime
, std::list
<CTransactionRef
>* plTxnReplaced
,
400 bool fOverrideMempoolLimit
, const CAmount
& nAbsurdFee
, std::vector
<COutPoint
>& coins_to_uncache
)
402 const CTransaction
& tx
= *ptx
;
403 const uint256 hash
= tx
.GetHash();
404 AssertLockHeld(cs_main
);
406 *pfMissingInputs
= false;
408 if (!CheckTransaction(tx
, state
))
409 return false; // state filled in by CheckTransaction
411 // Coinbase is only valid in a block, not as a loose transaction
413 return state
.DoS(100, false, REJECT_INVALID
, "coinbase");
415 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
416 bool witnessEnabled
= IsWitnessEnabled(chainActive
.Tip(), chainparams
.GetConsensus());
417 if (!GetBoolArg("-prematurewitness",false) && tx
.HasWitness() && !witnessEnabled
) {
418 return state
.DoS(0, false, REJECT_NONSTANDARD
, "no-witness-yet", true);
421 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
423 if (fRequireStandard
&& !IsStandardTx(tx
, reason
, witnessEnabled
))
424 return state
.DoS(0, false, REJECT_NONSTANDARD
, reason
);
426 // Only accept nLockTime-using transactions that can be mined in the next
427 // block; we don't want our mempool filled up with transactions that can't
429 if (!CheckFinalTx(tx
, STANDARD_LOCKTIME_VERIFY_FLAGS
))
430 return state
.DoS(0, false, REJECT_NONSTANDARD
, "non-final");
432 // is it already in the memory pool?
433 if (pool
.exists(hash
))
434 return state
.Invalid(false, REJECT_ALREADY_KNOWN
, "txn-already-in-mempool");
436 // Check for conflicts with in-memory transactions
437 std::set
<uint256
> setConflicts
;
439 LOCK(pool
.cs
); // protect pool.mapNextTx
440 for (const CTxIn
&txin
: tx
.vin
)
442 auto itConflicting
= pool
.mapNextTx
.find(txin
.prevout
);
443 if (itConflicting
!= pool
.mapNextTx
.end())
445 const CTransaction
*ptxConflicting
= itConflicting
->second
;
446 if (!setConflicts
.count(ptxConflicting
->GetHash()))
448 // Allow opt-out of transaction replacement by setting
449 // nSequence >= maxint-1 on all inputs.
451 // maxint-1 is picked to still allow use of nLockTime by
452 // non-replaceable transactions. All inputs rather than just one
453 // is for the sake of multi-party protocols, where we don't
454 // want a single party to be able to disable replacement.
456 // The opt-out ignores descendants as anyone relying on
457 // first-seen mempool behavior should be checking all
458 // unconfirmed ancestors anyway; doing otherwise is hopelessly
460 bool fReplacementOptOut
= true;
461 if (fEnableReplacement
)
463 for (const CTxIn
&_txin
: ptxConflicting
->vin
)
465 if (_txin
.nSequence
< std::numeric_limits
<unsigned int>::max()-1)
467 fReplacementOptOut
= false;
472 if (fReplacementOptOut
)
473 return state
.Invalid(false, REJECT_CONFLICT
, "txn-mempool-conflict");
475 setConflicts
.insert(ptxConflicting
->GetHash());
483 CCoinsViewCache
view(&dummy
);
485 CAmount nValueIn
= 0;
489 CCoinsViewMemPool
viewMemPool(pcoinsTip
, pool
);
490 view
.SetBackend(viewMemPool
);
492 // do we already have it?
493 for (size_t out
= 0; out
< tx
.vout
.size(); out
++) {
494 COutPoint
outpoint(hash
, out
);
495 bool had_coin_in_cache
= pcoinsTip
->HaveCoinInCache(outpoint
);
496 if (view
.HaveCoin(outpoint
)) {
497 if (!had_coin_in_cache
) {
498 coins_to_uncache
.push_back(outpoint
);
500 return state
.Invalid(false, REJECT_ALREADY_KNOWN
, "txn-already-known");
504 // do all inputs exist?
505 for (const CTxIn txin
: tx
.vin
) {
506 if (!pcoinsTip
->HaveCoinInCache(txin
.prevout
)) {
507 coins_to_uncache
.push_back(txin
.prevout
);
509 if (!view
.HaveCoin(txin
.prevout
)) {
510 if (pfMissingInputs
) {
511 *pfMissingInputs
= true;
513 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
517 // Bring the best block into scope
520 nValueIn
= view
.GetValueIn(tx
);
522 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
523 view
.SetBackend(dummy
);
525 // Only accept BIP68 sequence locked transactions that can be mined in the next
526 // block; we don't want our mempool filled up with transactions that can't
528 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
529 // CoinsViewCache instead of create its own
530 if (!CheckSequenceLocks(tx
, STANDARD_LOCKTIME_VERIFY_FLAGS
, &lp
))
531 return state
.DoS(0, false, REJECT_NONSTANDARD
, "non-BIP68-final");
534 // Check for non-standard pay-to-script-hash in inputs
535 if (fRequireStandard
&& !AreInputsStandard(tx
, view
))
536 return state
.Invalid(false, REJECT_NONSTANDARD
, "bad-txns-nonstandard-inputs");
538 // Check for non-standard witness in P2WSH
539 if (tx
.HasWitness() && fRequireStandard
&& !IsWitnessStandard(tx
, view
))
540 return state
.DoS(0, false, REJECT_NONSTANDARD
, "bad-witness-nonstandard", true);
542 int64_t nSigOpsCost
= GetTransactionSigOpCost(tx
, view
, STANDARD_SCRIPT_VERIFY_FLAGS
);
544 CAmount nValueOut
= tx
.GetValueOut();
545 CAmount nFees
= nValueIn
-nValueOut
;
546 // nModifiedFees includes any fee deltas from PrioritiseTransaction
547 CAmount nModifiedFees
= nFees
;
548 pool
.ApplyDelta(hash
, nModifiedFees
);
550 // Keep track of transactions that spend a coinbase, which we re-scan
551 // during reorgs to ensure COINBASE_MATURITY is still met.
552 bool fSpendsCoinbase
= false;
553 for (const CTxIn
&txin
: tx
.vin
) {
554 const Coin
&coin
= view
.AccessCoin(txin
.prevout
);
555 if (coin
.IsCoinBase()) {
556 fSpendsCoinbase
= true;
561 CTxMemPoolEntry
entry(ptx
, nFees
, nAcceptTime
, chainActive
.Height(),
562 fSpendsCoinbase
, nSigOpsCost
, lp
);
563 unsigned int nSize
= entry
.GetTxSize();
565 // Check that the transaction doesn't have an excessive number of
566 // sigops, making it impossible to mine. Since the coinbase transaction
567 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
568 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
569 // merely non-standard transaction.
570 if (nSigOpsCost
> MAX_STANDARD_TX_SIGOPS_COST
)
571 return state
.DoS(0, false, REJECT_NONSTANDARD
, "bad-txns-too-many-sigops", false,
572 strprintf("%d", nSigOpsCost
));
574 CAmount mempoolRejectFee
= pool
.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000).GetFee(nSize
);
575 if (mempoolRejectFee
> 0 && nModifiedFees
< mempoolRejectFee
) {
576 return state
.DoS(0, false, REJECT_INSUFFICIENTFEE
, "mempool min fee not met", false, strprintf("%d < %d", nFees
, mempoolRejectFee
));
579 // No transactions are allowed below minRelayTxFee except from disconnected blocks
580 if (fLimitFree
&& nModifiedFees
< ::minRelayTxFee
.GetFee(nSize
)) {
581 return state
.DoS(0, false, REJECT_INSUFFICIENTFEE
, "min relay fee not met");
584 if (nAbsurdFee
&& nFees
> nAbsurdFee
)
585 return state
.Invalid(false,
586 REJECT_HIGHFEE
, "absurdly-high-fee",
587 strprintf("%d > %d", nFees
, nAbsurdFee
));
589 // Calculate in-mempool ancestors, up to a limit.
590 CTxMemPool::setEntries setAncestors
;
591 size_t nLimitAncestors
= GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT
);
592 size_t nLimitAncestorSize
= GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT
)*1000;
593 size_t nLimitDescendants
= GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT
);
594 size_t nLimitDescendantSize
= GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT
)*1000;
595 std::string errString
;
596 if (!pool
.CalculateMemPoolAncestors(entry
, setAncestors
, nLimitAncestors
, nLimitAncestorSize
, nLimitDescendants
, nLimitDescendantSize
, errString
)) {
597 return state
.DoS(0, false, REJECT_NONSTANDARD
, "too-long-mempool-chain", false, errString
);
600 // A transaction that spends outputs that would be replaced by it is invalid. Now
601 // that we have the set of all ancestors we can detect this
602 // pathological case by making sure setConflicts and setAncestors don't
604 for (CTxMemPool::txiter ancestorIt
: setAncestors
)
606 const uint256
&hashAncestor
= ancestorIt
->GetTx().GetHash();
607 if (setConflicts
.count(hashAncestor
))
609 return state
.DoS(10, false,
610 REJECT_INVALID
, "bad-txns-spends-conflicting-tx", false,
611 strprintf("%s spends conflicting transaction %s",
613 hashAncestor
.ToString()));
617 // Check if it's economically rational to mine this transaction rather
618 // than the ones it replaces.
619 CAmount nConflictingFees
= 0;
620 size_t nConflictingSize
= 0;
621 uint64_t nConflictingCount
= 0;
622 CTxMemPool::setEntries allConflicting
;
624 // If we don't hold the lock allConflicting might be incomplete; the
625 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
626 // mempool consistency for us.
628 const bool fReplacementTransaction
= setConflicts
.size();
629 if (fReplacementTransaction
)
631 CFeeRate
newFeeRate(nModifiedFees
, nSize
);
632 std::set
<uint256
> setConflictsParents
;
633 const int maxDescendantsToVisit
= 100;
634 CTxMemPool::setEntries setIterConflicting
;
635 for (const uint256
&hashConflicting
: setConflicts
)
637 CTxMemPool::txiter mi
= pool
.mapTx
.find(hashConflicting
);
638 if (mi
== pool
.mapTx
.end())
641 // Save these to avoid repeated lookups
642 setIterConflicting
.insert(mi
);
644 // Don't allow the replacement to reduce the feerate of the
647 // We usually don't want to accept replacements with lower
648 // feerates than what they replaced as that would lower the
649 // feerate of the next block. Requiring that the feerate always
650 // be increased is also an easy-to-reason about way to prevent
651 // DoS attacks via replacements.
653 // The mining code doesn't (currently) take children into
654 // account (CPFP) so we only consider the feerates of
655 // transactions being directly replaced, not their indirect
656 // descendants. While that does mean high feerate children are
657 // ignored when deciding whether or not to replace, we do
658 // require the replacement to pay more overall fees too,
659 // mitigating most cases.
660 CFeeRate
oldFeeRate(mi
->GetModifiedFee(), mi
->GetTxSize());
661 if (newFeeRate
<= oldFeeRate
)
663 return state
.DoS(0, false,
664 REJECT_INSUFFICIENTFEE
, "insufficient fee", false,
665 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
667 newFeeRate
.ToString(),
668 oldFeeRate
.ToString()));
671 for (const CTxIn
&txin
: mi
->GetTx().vin
)
673 setConflictsParents
.insert(txin
.prevout
.hash
);
676 nConflictingCount
+= mi
->GetCountWithDescendants();
678 // This potentially overestimates the number of actual descendants
679 // but we just want to be conservative to avoid doing too much
681 if (nConflictingCount
<= maxDescendantsToVisit
) {
682 // If not too many to replace, then calculate the set of
683 // transactions that would have to be evicted
684 for (CTxMemPool::txiter it
: setIterConflicting
) {
685 pool
.CalculateDescendants(it
, allConflicting
);
687 for (CTxMemPool::txiter it
: allConflicting
) {
688 nConflictingFees
+= it
->GetModifiedFee();
689 nConflictingSize
+= it
->GetTxSize();
692 return state
.DoS(0, false,
693 REJECT_NONSTANDARD
, "too many potential replacements", false,
694 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
697 maxDescendantsToVisit
));
700 for (unsigned int j
= 0; j
< tx
.vin
.size(); j
++)
702 // We don't want to accept replacements that require low
703 // feerate junk to be mined first. Ideally we'd keep track of
704 // the ancestor feerates and make the decision based on that,
705 // but for now requiring all new inputs to be confirmed works.
706 if (!setConflictsParents
.count(tx
.vin
[j
].prevout
.hash
))
708 // Rather than check the UTXO set - potentially expensive -
709 // it's cheaper to just check if the new input refers to a
710 // tx that's in the mempool.
711 if (pool
.mapTx
.find(tx
.vin
[j
].prevout
.hash
) != pool
.mapTx
.end())
712 return state
.DoS(0, false,
713 REJECT_NONSTANDARD
, "replacement-adds-unconfirmed", false,
714 strprintf("replacement %s adds unconfirmed input, idx %d",
715 hash
.ToString(), j
));
719 // The replacement must pay greater fees than the transactions it
720 // replaces - if we did the bandwidth used by those conflicting
721 // transactions would not be paid for.
722 if (nModifiedFees
< nConflictingFees
)
724 return state
.DoS(0, false,
725 REJECT_INSUFFICIENTFEE
, "insufficient fee", false,
726 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
727 hash
.ToString(), FormatMoney(nModifiedFees
), FormatMoney(nConflictingFees
)));
730 // Finally in addition to paying more fees than the conflicts the
731 // new transaction must pay for its own bandwidth.
732 CAmount nDeltaFees
= nModifiedFees
- nConflictingFees
;
733 if (nDeltaFees
< ::incrementalRelayFee
.GetFee(nSize
))
735 return state
.DoS(0, false,
736 REJECT_INSUFFICIENTFEE
, "insufficient fee", false,
737 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
739 FormatMoney(nDeltaFees
),
740 FormatMoney(::incrementalRelayFee
.GetFee(nSize
))));
744 unsigned int scriptVerifyFlags
= STANDARD_SCRIPT_VERIFY_FLAGS
;
745 if (!chainparams
.RequireStandard()) {
746 scriptVerifyFlags
= GetArg("-promiscuousmempoolflags", scriptVerifyFlags
);
749 // Check against previous transactions
750 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
751 PrecomputedTransactionData
txdata(tx
);
752 if (!CheckInputs(tx
, state
, view
, true, scriptVerifyFlags
, true, txdata
)) {
753 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
754 // need to turn both off, and compare against just turning off CLEANSTACK
755 // to see if the failure is specifically due to witness validation.
756 CValidationState stateDummy
; // Want reported failures to be from first CheckInputs
757 if (!tx
.HasWitness() && CheckInputs(tx
, stateDummy
, view
, true, scriptVerifyFlags
& ~(SCRIPT_VERIFY_WITNESS
| SCRIPT_VERIFY_CLEANSTACK
), true, txdata
) &&
758 !CheckInputs(tx
, stateDummy
, view
, true, scriptVerifyFlags
& ~SCRIPT_VERIFY_CLEANSTACK
, true, txdata
)) {
759 // Only the witness is missing, so the transaction itself may be fine.
760 state
.SetCorruptionPossible();
762 return false; // state filled in by CheckInputs
765 // Check again against just the consensus-critical mandatory script
766 // verification flags, in case of bugs in the standard flags that cause
767 // transactions to pass as valid when they're actually invalid. For
768 // instance the STRICTENC flag was incorrectly allowing certain
769 // CHECKSIG NOT scripts to pass, even though they were invalid.
771 // There is a similar check in CreateNewBlock() to prevent creating
772 // invalid blocks, however allowing such transactions into the mempool
773 // can be exploited as a DoS attack.
774 if (!CheckInputs(tx
, state
, view
, true, MANDATORY_SCRIPT_VERIFY_FLAGS
, true, txdata
))
776 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
777 __func__
, hash
.ToString(), FormatStateMessage(state
));
780 // Remove conflicting transactions from the mempool
781 for (const CTxMemPool::txiter it
: allConflicting
)
783 LogPrint(BCLog::MEMPOOL
, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
784 it
->GetTx().GetHash().ToString(),
786 FormatMoney(nModifiedFees
- nConflictingFees
),
787 (int)nSize
- (int)nConflictingSize
);
789 plTxnReplaced
->push_back(it
->GetSharedTx());
791 pool
.RemoveStaged(allConflicting
, false, MemPoolRemovalReason::REPLACED
);
793 // This transaction should only count for fee estimation if it isn't a
794 // BIP 125 replacement transaction (may not be widely supported), the
795 // node is not behind, and the transaction is not dependent on any other
796 // transactions in the mempool.
797 bool validForFeeEstimation
= !fReplacementTransaction
&& IsCurrentForFeeEstimation() && pool
.HasNoInputsOf(tx
);
799 // Store transaction in memory
800 pool
.addUnchecked(hash
, entry
, setAncestors
, validForFeeEstimation
);
802 // trim mempool and check if tx was trimmed
803 if (!fOverrideMempoolLimit
) {
804 LimitMempoolSize(pool
, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY
) * 60 * 60);
805 if (!pool
.exists(hash
))
806 return state
.DoS(0, false, REJECT_INSUFFICIENTFEE
, "mempool full");
810 GetMainSignals().TransactionAddedToMempool(ptx
);
815 /** (try to) add transaction to memory pool with a specified acceptance time **/
816 static bool AcceptToMemoryPoolWithTime(const CChainParams
& chainparams
, CTxMemPool
& pool
, CValidationState
&state
, const CTransactionRef
&tx
, bool fLimitFree
,
817 bool* pfMissingInputs
, int64_t nAcceptTime
, std::list
<CTransactionRef
>* plTxnReplaced
,
818 bool fOverrideMempoolLimit
, const CAmount nAbsurdFee
)
820 std::vector
<COutPoint
> coins_to_uncache
;
821 bool res
= AcceptToMemoryPoolWorker(chainparams
, pool
, state
, tx
, fLimitFree
, pfMissingInputs
, nAcceptTime
, plTxnReplaced
, fOverrideMempoolLimit
, nAbsurdFee
, coins_to_uncache
);
823 for (const COutPoint
& hashTx
: coins_to_uncache
)
824 pcoinsTip
->Uncache(hashTx
);
826 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
827 CValidationState stateDummy
;
828 FlushStateToDisk(chainparams
, stateDummy
, FLUSH_STATE_PERIODIC
);
832 bool AcceptToMemoryPool(CTxMemPool
& pool
, CValidationState
&state
, const CTransactionRef
&tx
, bool fLimitFree
,
833 bool* pfMissingInputs
, std::list
<CTransactionRef
>* plTxnReplaced
,
834 bool fOverrideMempoolLimit
, const CAmount nAbsurdFee
)
836 const CChainParams
& chainparams
= Params();
837 return AcceptToMemoryPoolWithTime(chainparams
, pool
, state
, tx
, fLimitFree
, pfMissingInputs
, GetTime(), plTxnReplaced
, fOverrideMempoolLimit
, nAbsurdFee
);
840 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
841 bool GetTransaction(const uint256
&hash
, CTransactionRef
&txOut
, const Consensus::Params
& consensusParams
, uint256
&hashBlock
, bool fAllowSlow
)
843 CBlockIndex
*pindexSlow
= NULL
;
847 CTransactionRef ptx
= mempool
.get(hash
);
856 if (pblocktree
->ReadTxIndex(hash
, postx
)) {
857 CAutoFile
file(OpenBlockFile(postx
, true), SER_DISK
, CLIENT_VERSION
);
859 return error("%s: OpenBlockFile failed", __func__
);
863 fseek(file
.Get(), postx
.nTxOffset
, SEEK_CUR
);
865 } catch (const std::exception
& e
) {
866 return error("%s: Deserialize or I/O error - %s", __func__
, e
.what());
868 hashBlock
= header
.GetHash();
869 if (txOut
->GetHash() != hash
)
870 return error("%s: txid mismatch", __func__
);
875 if (fAllowSlow
) { // use coin database to locate block that contains transaction, and scan it
876 const Coin
& coin
= AccessByTxid(*pcoinsTip
, hash
);
877 if (!coin
.IsSpent()) pindexSlow
= chainActive
[coin
.nHeight
];
882 if (ReadBlockFromDisk(block
, pindexSlow
, consensusParams
)) {
883 for (const auto& tx
: block
.vtx
) {
884 if (tx
->GetHash() == hash
) {
886 hashBlock
= pindexSlow
->GetBlockHash();
901 //////////////////////////////////////////////////////////////////////////////
903 // CBlock and CBlockIndex
906 static bool WriteBlockToDisk(const CBlock
& block
, CDiskBlockPos
& pos
, const CMessageHeader::MessageStartChars
& messageStart
)
908 // Open history file to append
909 CAutoFile
fileout(OpenBlockFile(pos
), SER_DISK
, CLIENT_VERSION
);
910 if (fileout
.IsNull())
911 return error("WriteBlockToDisk: OpenBlockFile failed");
913 // Write index header
914 unsigned int nSize
= GetSerializeSize(fileout
, block
);
915 fileout
<< FLATDATA(messageStart
) << nSize
;
918 long fileOutPos
= ftell(fileout
.Get());
920 return error("WriteBlockToDisk: ftell failed");
921 pos
.nPos
= (unsigned int)fileOutPos
;
927 bool ReadBlockFromDisk(CBlock
& block
, const CDiskBlockPos
& pos
, const Consensus::Params
& consensusParams
)
931 // Open history file to read
932 CAutoFile
filein(OpenBlockFile(pos
, true), SER_DISK
, CLIENT_VERSION
);
934 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos
.ToString());
940 catch (const std::exception
& e
) {
941 return error("%s: Deserialize or I/O error - %s at %s", __func__
, e
.what(), pos
.ToString());
945 if (!CheckProofOfWork(block
.GetHash(), block
.nBits
, consensusParams
))
946 return error("ReadBlockFromDisk: Errors in block header at %s", pos
.ToString());
951 bool ReadBlockFromDisk(CBlock
& block
, const CBlockIndex
* pindex
, const Consensus::Params
& consensusParams
)
953 if (!ReadBlockFromDisk(block
, pindex
->GetBlockPos(), consensusParams
))
955 if (block
.GetHash() != pindex
->GetBlockHash())
956 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
957 pindex
->ToString(), pindex
->GetBlockPos().ToString());
961 CAmount
GetBlockSubsidy(int nHeight
, const Consensus::Params
& consensusParams
)
963 int halvings
= nHeight
/ consensusParams
.nSubsidyHalvingInterval
;
964 // Force block reward to zero when right shift is undefined.
968 CAmount nSubsidy
= 50 * COIN
;
969 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
970 nSubsidy
>>= halvings
;
974 bool IsInitialBlockDownload()
976 const CChainParams
& chainParams
= Params();
978 // Once this function has returned false, it must remain false.
979 static std::atomic
<bool> latchToFalse
{false};
980 // Optimization: pre-test latch before taking the lock.
981 if (latchToFalse
.load(std::memory_order_relaxed
))
985 if (latchToFalse
.load(std::memory_order_relaxed
))
987 if (fImporting
|| fReindex
)
989 if (chainActive
.Tip() == NULL
)
991 if (chainActive
.Tip()->nChainWork
< UintToArith256(chainParams
.GetConsensus().nMinimumChainWork
))
993 if (chainActive
.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge
))
995 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
996 latchToFalse
.store(true, std::memory_order_relaxed
);
1000 CBlockIndex
*pindexBestForkTip
= NULL
, *pindexBestForkBase
= NULL
;
1002 static void AlertNotify(const std::string
& strMessage
)
1004 uiInterface
.NotifyAlertChanged();
1005 std::string strCmd
= GetArg("-alertnotify", "");
1006 if (strCmd
.empty()) return;
1008 // Alert text should be plain ascii coming from a trusted source, but to
1009 // be safe we first strip anything not in safeChars, then add single quotes around
1010 // the whole string before passing it to the shell:
1011 std::string
singleQuote("'");
1012 std::string safeStatus
= SanitizeString(strMessage
);
1013 safeStatus
= singleQuote
+safeStatus
+singleQuote
;
1014 boost::replace_all(strCmd
, "%s", safeStatus
);
1016 boost::thread
t(runCommand
, strCmd
); // thread runs free
1019 static void CheckForkWarningConditions()
1021 AssertLockHeld(cs_main
);
1022 // Before we get past initial download, we cannot reliably alert about forks
1023 // (we assume we don't get stuck on a fork before finishing our initial sync)
1024 if (IsInitialBlockDownload())
1027 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1028 // of our head, drop it
1029 if (pindexBestForkTip
&& chainActive
.Height() - pindexBestForkTip
->nHeight
>= 72)
1030 pindexBestForkTip
= NULL
;
1032 if (pindexBestForkTip
|| (pindexBestInvalid
&& pindexBestInvalid
->nChainWork
> chainActive
.Tip()->nChainWork
+ (GetBlockProof(*chainActive
.Tip()) * 6)))
1034 if (!GetfLargeWorkForkFound() && pindexBestForkBase
)
1036 std::string warning
= std::string("'Warning: Large-work fork detected, forking after block ") +
1037 pindexBestForkBase
->phashBlock
->ToString() + std::string("'");
1038 AlertNotify(warning
);
1040 if (pindexBestForkTip
&& pindexBestForkBase
)
1042 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__
,
1043 pindexBestForkBase
->nHeight
, pindexBestForkBase
->phashBlock
->ToString(),
1044 pindexBestForkTip
->nHeight
, pindexBestForkTip
->phashBlock
->ToString());
1045 SetfLargeWorkForkFound(true);
1049 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__
);
1050 SetfLargeWorkInvalidChainFound(true);
1055 SetfLargeWorkForkFound(false);
1056 SetfLargeWorkInvalidChainFound(false);
1060 static void CheckForkWarningConditionsOnNewFork(CBlockIndex
* pindexNewForkTip
)
1062 AssertLockHeld(cs_main
);
1063 // If we are on a fork that is sufficiently large, set a warning flag
1064 CBlockIndex
* pfork
= pindexNewForkTip
;
1065 CBlockIndex
* plonger
= chainActive
.Tip();
1066 while (pfork
&& pfork
!= plonger
)
1068 while (plonger
&& plonger
->nHeight
> pfork
->nHeight
)
1069 plonger
= plonger
->pprev
;
1070 if (pfork
== plonger
)
1072 pfork
= pfork
->pprev
;
1075 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1076 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1077 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1078 // hash rate operating on the fork.
1079 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1080 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1081 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1082 if (pfork
&& (!pindexBestForkTip
|| (pindexBestForkTip
&& pindexNewForkTip
->nHeight
> pindexBestForkTip
->nHeight
)) &&
1083 pindexNewForkTip
->nChainWork
- pfork
->nChainWork
> (GetBlockProof(*pfork
) * 7) &&
1084 chainActive
.Height() - pindexNewForkTip
->nHeight
< 72)
1086 pindexBestForkTip
= pindexNewForkTip
;
1087 pindexBestForkBase
= pfork
;
1090 CheckForkWarningConditions();
1093 void static InvalidChainFound(CBlockIndex
* pindexNew
)
1095 if (!pindexBestInvalid
|| pindexNew
->nChainWork
> pindexBestInvalid
->nChainWork
)
1096 pindexBestInvalid
= pindexNew
;
1098 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__
,
1099 pindexNew
->GetBlockHash().ToString(), pindexNew
->nHeight
,
1100 log(pindexNew
->nChainWork
.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1101 pindexNew
->GetBlockTime()));
1102 CBlockIndex
*tip
= chainActive
.Tip();
1104 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__
,
1105 tip
->GetBlockHash().ToString(), chainActive
.Height(), log(tip
->nChainWork
.getdouble())/log(2.0),
1106 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip
->GetBlockTime()));
1107 CheckForkWarningConditions();
1110 void static InvalidBlockFound(CBlockIndex
*pindex
, const CValidationState
&state
) {
1111 if (!state
.CorruptionPossible()) {
1112 pindex
->nStatus
|= BLOCK_FAILED_VALID
;
1113 setDirtyBlockIndex
.insert(pindex
);
1114 setBlockIndexCandidates
.erase(pindex
);
1115 InvalidChainFound(pindex
);
1119 void UpdateCoins(const CTransaction
& tx
, CCoinsViewCache
& inputs
, CTxUndo
&txundo
, int nHeight
)
1121 // mark inputs spent
1122 if (!tx
.IsCoinBase()) {
1123 txundo
.vprevout
.reserve(tx
.vin
.size());
1124 for (const CTxIn
&txin
: tx
.vin
) {
1125 txundo
.vprevout
.emplace_back();
1126 inputs
.SpendCoin(txin
.prevout
, &txundo
.vprevout
.back());
1130 AddCoins(inputs
, tx
, nHeight
);
1133 void UpdateCoins(const CTransaction
& tx
, CCoinsViewCache
& inputs
, int nHeight
)
1136 UpdateCoins(tx
, inputs
, txundo
, nHeight
);
1139 bool CScriptCheck::operator()() {
1140 const CScript
&scriptSig
= ptxTo
->vin
[nIn
].scriptSig
;
1141 const CScriptWitness
*witness
= &ptxTo
->vin
[nIn
].scriptWitness
;
1142 return VerifyScript(scriptSig
, scriptPubKey
, witness
, nFlags
, CachingTransactionSignatureChecker(ptxTo
, nIn
, amount
, cacheStore
, *txdata
), &error
);
1145 int GetSpendHeight(const CCoinsViewCache
& inputs
)
1148 CBlockIndex
* pindexPrev
= mapBlockIndex
.find(inputs
.GetBestBlock())->second
;
1149 return pindexPrev
->nHeight
+ 1;
1153 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
1154 * This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
1155 * instead of being performed inline.
1157 static bool CheckInputs(const CTransaction
& tx
, CValidationState
&state
, const CCoinsViewCache
&inputs
, bool fScriptChecks
, unsigned int flags
, bool cacheStore
, PrecomputedTransactionData
& txdata
, std::vector
<CScriptCheck
> *pvChecks
)
1159 if (!tx
.IsCoinBase())
1161 if (!Consensus::CheckTxInputs(tx
, state
, inputs
, GetSpendHeight(inputs
)))
1165 pvChecks
->reserve(tx
.vin
.size());
1167 // The first loop above does all the inexpensive checks.
1168 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1169 // Helps prevent CPU exhaustion attacks.
1171 // Skip script verification when connecting blocks under the
1172 // assumevalid block. Assuming the assumevalid block is valid this
1173 // is safe because block merkle hashes are still computed and checked,
1174 // Of course, if an assumed valid block is invalid due to false scriptSigs
1175 // this optimization would allow an invalid chain to be accepted.
1176 if (fScriptChecks
) {
1177 for (unsigned int i
= 0; i
< tx
.vin
.size(); i
++) {
1178 const COutPoint
&prevout
= tx
.vin
[i
].prevout
;
1179 const Coin
& coin
= inputs
.AccessCoin(prevout
);
1180 assert(!coin
.IsSpent());
1182 // We very carefully only pass in things to CScriptCheck which
1183 // are clearly committed to by tx' witness hash. This provides
1184 // a sanity check that our caching is not introducing consensus
1185 // failures through additional data in, eg, the coins being
1186 // spent being checked as a part of CScriptCheck.
1187 const CScript
& scriptPubKey
= coin
.out
.scriptPubKey
;
1188 const CAmount amount
= coin
.out
.nValue
;
1191 CScriptCheck
check(scriptPubKey
, amount
, tx
, i
, flags
, cacheStore
, &txdata
);
1193 pvChecks
->push_back(CScriptCheck());
1194 check
.swap(pvChecks
->back());
1195 } else if (!check()) {
1196 if (flags
& STANDARD_NOT_MANDATORY_VERIFY_FLAGS
) {
1197 // Check whether the failure was caused by a
1198 // non-mandatory script verification check, such as
1199 // non-standard DER encodings or non-null dummy
1200 // arguments; if so, don't trigger DoS protection to
1201 // avoid splitting the network between upgraded and
1202 // non-upgraded nodes.
1203 CScriptCheck
check2(scriptPubKey
, amount
, tx
, i
,
1204 flags
& ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS
, cacheStore
, &txdata
);
1206 return state
.Invalid(false, REJECT_NONSTANDARD
, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check
.GetScriptError())));
1208 // Failures of other flags indicate a transaction that is
1209 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1210 // such nodes as they are not following the protocol. That
1211 // said during an upgrade careful thought should be taken
1212 // as to the correct behavior - we may want to continue
1213 // peering with non-upgraded nodes even after soft-fork
1214 // super-majority signaling has occurred.
1215 return state
.DoS(100,false, REJECT_INVALID
, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check
.GetScriptError())));
1226 bool UndoWriteToDisk(const CBlockUndo
& blockundo
, CDiskBlockPos
& pos
, const uint256
& hashBlock
, const CMessageHeader::MessageStartChars
& messageStart
)
1228 // Open history file to append
1229 CAutoFile
fileout(OpenUndoFile(pos
), SER_DISK
, CLIENT_VERSION
);
1230 if (fileout
.IsNull())
1231 return error("%s: OpenUndoFile failed", __func__
);
1233 // Write index header
1234 unsigned int nSize
= GetSerializeSize(fileout
, blockundo
);
1235 fileout
<< FLATDATA(messageStart
) << nSize
;
1238 long fileOutPos
= ftell(fileout
.Get());
1240 return error("%s: ftell failed", __func__
);
1241 pos
.nPos
= (unsigned int)fileOutPos
;
1242 fileout
<< blockundo
;
1244 // calculate & write checksum
1245 CHashWriter
hasher(SER_GETHASH
, PROTOCOL_VERSION
);
1246 hasher
<< hashBlock
;
1247 hasher
<< blockundo
;
1248 fileout
<< hasher
.GetHash();
1253 bool UndoReadFromDisk(CBlockUndo
& blockundo
, const CDiskBlockPos
& pos
, const uint256
& hashBlock
)
1255 // Open history file to read
1256 CAutoFile
filein(OpenUndoFile(pos
, true), SER_DISK
, CLIENT_VERSION
);
1257 if (filein
.IsNull())
1258 return error("%s: OpenUndoFile failed", __func__
);
1261 uint256 hashChecksum
;
1262 CHashVerifier
<CAutoFile
> verifier(&filein
); // We need a CHashVerifier as reserializing may lose data
1264 verifier
<< hashBlock
;
1265 verifier
>> blockundo
;
1266 filein
>> hashChecksum
;
1268 catch (const std::exception
& e
) {
1269 return error("%s: Deserialize or I/O error - %s", __func__
, e
.what());
1273 if (hashChecksum
!= verifier
.GetHash())
1274 return error("%s: Checksum mismatch", __func__
);
1279 /** Abort with a message */
1280 bool AbortNode(const std::string
& strMessage
, const std::string
& userMessage
="")
1282 SetMiscWarning(strMessage
);
1283 LogPrintf("*** %s\n", strMessage
);
1284 uiInterface
.ThreadSafeMessageBox(
1285 userMessage
.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage
,
1286 "", CClientUIInterface::MSG_ERROR
);
1291 bool AbortNode(CValidationState
& state
, const std::string
& strMessage
, const std::string
& userMessage
="")
1293 AbortNode(strMessage
, userMessage
);
1294 return state
.Error(strMessage
);
1299 enum DisconnectResult
1301 DISCONNECT_OK
, // All good.
1302 DISCONNECT_UNCLEAN
, // Rolled back, but UTXO set was inconsistent with block.
1303 DISCONNECT_FAILED
// Something else went wrong.
1307 * Restore the UTXO in a Coin at a given COutPoint
1308 * @param undo The Coin to be restored.
1309 * @param view The coins view to which to apply the changes.
1310 * @param out The out point that corresponds to the tx input.
1311 * @return A DisconnectResult as an int
1313 int ApplyTxInUndo(Coin
&& undo
, CCoinsViewCache
& view
, const COutPoint
& out
)
1317 if (view
.HaveCoin(out
)) fClean
= false; // overwriting transaction output
1319 if (undo
.nHeight
== 0) {
1320 // Missing undo metadata (height and coinbase). Older versions included this
1321 // information only in undo records for the last spend of a transactions'
1322 // outputs. This implies that it must be present for some other output of the same tx.
1323 const Coin
& alternate
= AccessByTxid(view
, out
.hash
);
1324 if (!alternate
.IsSpent()) {
1325 undo
.nHeight
= alternate
.nHeight
;
1326 undo
.fCoinBase
= alternate
.fCoinBase
;
1328 return DISCONNECT_FAILED
; // adding output for transaction without known metadata
1331 view
.AddCoin(out
, std::move(undo
), undo
.fCoinBase
);
1333 return fClean
? DISCONNECT_OK
: DISCONNECT_UNCLEAN
;
1336 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1337 * When UNCLEAN or FAILED is returned, view is left in an indeterminate state. */
1338 static DisconnectResult
DisconnectBlock(const CBlock
& block
, const CBlockIndex
* pindex
, CCoinsViewCache
& view
)
1340 assert(pindex
->GetBlockHash() == view
.GetBestBlock());
1344 CBlockUndo blockUndo
;
1345 CDiskBlockPos pos
= pindex
->GetUndoPos();
1347 error("DisconnectBlock(): no undo data available");
1348 return DISCONNECT_FAILED
;
1350 if (!UndoReadFromDisk(blockUndo
, pos
, pindex
->pprev
->GetBlockHash())) {
1351 error("DisconnectBlock(): failure reading undo data");
1352 return DISCONNECT_FAILED
;
1355 if (blockUndo
.vtxundo
.size() + 1 != block
.vtx
.size()) {
1356 error("DisconnectBlock(): block and undo data inconsistent");
1357 return DISCONNECT_FAILED
;
1360 // undo transactions in reverse order
1361 for (int i
= block
.vtx
.size() - 1; i
>= 0; i
--) {
1362 const CTransaction
&tx
= *(block
.vtx
[i
]);
1363 uint256 hash
= tx
.GetHash();
1365 // Check that all outputs are available and match the outputs in the block itself
1367 for (size_t o
= 0; o
< tx
.vout
.size(); o
++) {
1368 if (!tx
.vout
[o
].scriptPubKey
.IsUnspendable()) {
1369 COutPoint
out(hash
, o
);
1371 view
.SpendCoin(out
, &coin
);
1372 if (tx
.vout
[o
] != coin
.out
) {
1373 fClean
= false; // transaction output mismatch
1379 if (i
> 0) { // not coinbases
1380 CTxUndo
&txundo
= blockUndo
.vtxundo
[i
-1];
1381 if (txundo
.vprevout
.size() != tx
.vin
.size()) {
1382 error("DisconnectBlock(): transaction and undo data inconsistent");
1383 return DISCONNECT_FAILED
;
1385 for (unsigned int j
= tx
.vin
.size(); j
-- > 0;) {
1386 const COutPoint
&out
= tx
.vin
[j
].prevout
;
1387 int res
= ApplyTxInUndo(std::move(txundo
.vprevout
[j
]), view
, out
);
1388 if (res
== DISCONNECT_FAILED
) return DISCONNECT_FAILED
;
1389 fClean
= fClean
&& res
!= DISCONNECT_UNCLEAN
;
1391 // At this point, all of txundo.vprevout should have been moved out.
1395 // move best block pointer to prevout block
1396 view
.SetBestBlock(pindex
->pprev
->GetBlockHash());
1398 return fClean
? DISCONNECT_OK
: DISCONNECT_UNCLEAN
;
1401 void static FlushBlockFile(bool fFinalize
= false)
1403 LOCK(cs_LastBlockFile
);
1405 CDiskBlockPos
posOld(nLastBlockFile
, 0);
1407 FILE *fileOld
= OpenBlockFile(posOld
);
1410 TruncateFile(fileOld
, vinfoBlockFile
[nLastBlockFile
].nSize
);
1411 FileCommit(fileOld
);
1415 fileOld
= OpenUndoFile(posOld
);
1418 TruncateFile(fileOld
, vinfoBlockFile
[nLastBlockFile
].nUndoSize
);
1419 FileCommit(fileOld
);
1424 static bool FindUndoPos(CValidationState
&state
, int nFile
, CDiskBlockPos
&pos
, unsigned int nAddSize
);
1426 static CCheckQueue
<CScriptCheck
> scriptcheckqueue(128);
1428 void ThreadScriptCheck() {
1429 RenameThread("bitcoin-scriptch");
1430 scriptcheckqueue
.Thread();
1433 // Protected by cs_main
1434 VersionBitsCache versionbitscache
;
1436 int32_t ComputeBlockVersion(const CBlockIndex
* pindexPrev
, const Consensus::Params
& params
)
1439 int32_t nVersion
= VERSIONBITS_TOP_BITS
;
1441 for (int i
= 0; i
< (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS
; i
++) {
1442 ThresholdState state
= VersionBitsState(pindexPrev
, params
, (Consensus::DeploymentPos
)i
, versionbitscache
);
1443 if (state
== THRESHOLD_LOCKED_IN
|| state
== THRESHOLD_STARTED
) {
1444 nVersion
|= VersionBitsMask(params
, (Consensus::DeploymentPos
)i
);
1452 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1454 class WarningBitsConditionChecker
: public AbstractThresholdConditionChecker
1460 WarningBitsConditionChecker(int bitIn
) : bit(bitIn
) {}
1462 int64_t BeginTime(const Consensus::Params
& params
) const { return 0; }
1463 int64_t EndTime(const Consensus::Params
& params
) const { return std::numeric_limits
<int64_t>::max(); }
1464 int Period(const Consensus::Params
& params
) const { return params
.nMinerConfirmationWindow
; }
1465 int Threshold(const Consensus::Params
& params
) const { return params
.nRuleChangeActivationThreshold
; }
1467 bool Condition(const CBlockIndex
* pindex
, const Consensus::Params
& params
) const
1469 return ((pindex
->nVersion
& VERSIONBITS_TOP_MASK
) == VERSIONBITS_TOP_BITS
) &&
1470 ((pindex
->nVersion
>> bit
) & 1) != 0 &&
1471 ((ComputeBlockVersion(pindex
->pprev
, params
) >> bit
) & 1) == 0;
1475 // Protected by cs_main
1476 static ThresholdConditionCache warningcache
[VERSIONBITS_NUM_BITS
];
1478 static int64_t nTimeCheck
= 0;
1479 static int64_t nTimeForks
= 0;
1480 static int64_t nTimeVerify
= 0;
1481 static int64_t nTimeConnect
= 0;
1482 static int64_t nTimeIndex
= 0;
1483 static int64_t nTimeCallbacks
= 0;
1484 static int64_t nTimeTotal
= 0;
1486 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1487 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1488 * can fail if those validity checks fail (among other reasons). */
1489 static bool ConnectBlock(const CBlock
& block
, CValidationState
& state
, CBlockIndex
* pindex
,
1490 CCoinsViewCache
& view
, const CChainParams
& chainparams
, bool fJustCheck
= false)
1492 AssertLockHeld(cs_main
);
1494 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1495 assert((pindex
->phashBlock
== NULL
) ||
1496 (*pindex
->phashBlock
== block
.GetHash()));
1497 int64_t nTimeStart
= GetTimeMicros();
1499 // Check it again in case a previous version let a bad block in
1500 if (!CheckBlock(block
, state
, chainparams
.GetConsensus(), !fJustCheck
, !fJustCheck
))
1501 return error("%s: Consensus::CheckBlock: %s", __func__
, FormatStateMessage(state
));
1503 // verify that the view's current state corresponds to the previous block
1504 uint256 hashPrevBlock
= pindex
->pprev
== NULL
? uint256() : pindex
->pprev
->GetBlockHash();
1505 assert(hashPrevBlock
== view
.GetBestBlock());
1507 // Special case for the genesis block, skipping connection of its transactions
1508 // (its coinbase is unspendable)
1509 if (block
.GetHash() == chainparams
.GetConsensus().hashGenesisBlock
) {
1511 view
.SetBestBlock(pindex
->GetBlockHash());
1515 bool fScriptChecks
= true;
1516 if (!hashAssumeValid
.IsNull()) {
1517 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1518 // A suitable default value is included with the software and updated from time to time. Because validity
1519 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1520 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1521 // effectively caching the result of part of the verification.
1522 BlockMap::const_iterator it
= mapBlockIndex
.find(hashAssumeValid
);
1523 if (it
!= mapBlockIndex
.end()) {
1524 if (it
->second
->GetAncestor(pindex
->nHeight
) == pindex
&&
1525 pindexBestHeader
->GetAncestor(pindex
->nHeight
) == pindex
&&
1526 pindexBestHeader
->nChainWork
>= UintToArith256(chainparams
.GetConsensus().nMinimumChainWork
)) {
1527 // This block is a member of the assumed verified chain and an ancestor of the best header.
1528 // The equivalent time check discourages hash power from extorting the network via DOS attack
1529 // into accepting an invalid block through telling users they must manually set assumevalid.
1530 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1531 // it hard to hide the implication of the demand. This also avoids having release candidates
1532 // that are hardly doing any signature verification at all in testing without having to
1533 // artificially set the default assumed verified block further back.
1534 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1535 // least as good as the expected chain.
1536 fScriptChecks
= (GetBlockProofEquivalentTime(*pindexBestHeader
, *pindex
, *pindexBestHeader
, chainparams
.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1541 int64_t nTime1
= GetTimeMicros(); nTimeCheck
+= nTime1
- nTimeStart
;
1542 LogPrint(BCLog::BENCH
, " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1
- nTimeStart
), nTimeCheck
* 0.000001);
1544 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1545 // unless those are already completely spent.
1546 // If such overwrites are allowed, coinbases and transactions depending upon those
1547 // can be duplicated to remove the ability to spend the first instance -- even after
1548 // being sent to another address.
1549 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1550 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1551 // already refuses previously-known transaction ids entirely.
1552 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1553 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1554 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1555 // initial block download.
1556 bool fEnforceBIP30
= (!pindex
->phashBlock
) || // Enforce on CreateNewBlock invocations which don't have a hash.
1557 !((pindex
->nHeight
==91842 && pindex
->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1558 (pindex
->nHeight
==91880 && pindex
->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1560 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1561 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1562 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1563 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1564 // duplicate transactions descending from the known pairs either.
1565 // 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.
1566 CBlockIndex
*pindexBIP34height
= pindex
->pprev
->GetAncestor(chainparams
.GetConsensus().BIP34Height
);
1567 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1568 fEnforceBIP30
= fEnforceBIP30
&& (!pindexBIP34height
|| !(pindexBIP34height
->GetBlockHash() == chainparams
.GetConsensus().BIP34Hash
));
1570 if (fEnforceBIP30
) {
1571 for (const auto& tx
: block
.vtx
) {
1572 for (size_t o
= 0; o
< tx
->vout
.size(); o
++) {
1573 if (view
.HaveCoin(COutPoint(tx
->GetHash(), o
))) {
1574 return state
.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1575 REJECT_INVALID
, "bad-txns-BIP30");
1581 // BIP16 didn't become active until Apr 1 2012
1582 int64_t nBIP16SwitchTime
= 1333238400;
1583 bool fStrictPayToScriptHash
= (pindex
->GetBlockTime() >= nBIP16SwitchTime
);
1585 unsigned int flags
= fStrictPayToScriptHash
? SCRIPT_VERIFY_P2SH
: SCRIPT_VERIFY_NONE
;
1587 // Start enforcing the DERSIG (BIP66) rule
1588 if (pindex
->nHeight
>= chainparams
.GetConsensus().BIP66Height
) {
1589 flags
|= SCRIPT_VERIFY_DERSIG
;
1592 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1593 if (pindex
->nHeight
>= chainparams
.GetConsensus().BIP65Height
) {
1594 flags
|= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
;
1597 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1598 int nLockTimeFlags
= 0;
1599 if (VersionBitsState(pindex
->pprev
, chainparams
.GetConsensus(), Consensus::DEPLOYMENT_CSV
, versionbitscache
) == THRESHOLD_ACTIVE
) {
1600 flags
|= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
;
1601 nLockTimeFlags
|= LOCKTIME_VERIFY_SEQUENCE
;
1604 // Start enforcing WITNESS rules using versionbits logic.
1605 if (IsWitnessEnabled(pindex
->pprev
, chainparams
.GetConsensus())) {
1606 flags
|= SCRIPT_VERIFY_WITNESS
;
1607 flags
|= SCRIPT_VERIFY_NULLDUMMY
;
1610 int64_t nTime2
= GetTimeMicros(); nTimeForks
+= nTime2
- nTime1
;
1611 LogPrint(BCLog::BENCH
, " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2
- nTime1
), nTimeForks
* 0.000001);
1613 CBlockUndo blockundo
;
1615 CCheckQueueControl
<CScriptCheck
> control(fScriptChecks
&& nScriptCheckThreads
? &scriptcheckqueue
: NULL
);
1617 std::vector
<int> prevheights
;
1620 int64_t nSigOpsCost
= 0;
1621 CDiskTxPos
pos(pindex
->GetBlockPos(), GetSizeOfCompactSize(block
.vtx
.size()));
1622 std::vector
<std::pair
<uint256
, CDiskTxPos
> > vPos
;
1623 vPos
.reserve(block
.vtx
.size());
1624 blockundo
.vtxundo
.reserve(block
.vtx
.size() - 1);
1625 std::vector
<PrecomputedTransactionData
> txdata
;
1626 txdata
.reserve(block
.vtx
.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1627 for (unsigned int i
= 0; i
< block
.vtx
.size(); i
++)
1629 const CTransaction
&tx
= *(block
.vtx
[i
]);
1631 nInputs
+= tx
.vin
.size();
1633 if (!tx
.IsCoinBase())
1635 if (!view
.HaveInputs(tx
))
1636 return state
.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1637 REJECT_INVALID
, "bad-txns-inputs-missingorspent");
1639 // Check that transaction is BIP68 final
1640 // BIP68 lock checks (as opposed to nLockTime checks) must
1641 // be in ConnectBlock because they require the UTXO set
1642 prevheights
.resize(tx
.vin
.size());
1643 for (size_t j
= 0; j
< tx
.vin
.size(); j
++) {
1644 prevheights
[j
] = view
.AccessCoin(tx
.vin
[j
].prevout
).nHeight
;
1647 if (!SequenceLocks(tx
, nLockTimeFlags
, &prevheights
, *pindex
)) {
1648 return state
.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__
),
1649 REJECT_INVALID
, "bad-txns-nonfinal");
1653 // GetTransactionSigOpCost counts 3 types of sigops:
1654 // * legacy (always)
1655 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1656 // * witness (when witness enabled in flags and excludes coinbase)
1657 nSigOpsCost
+= GetTransactionSigOpCost(tx
, view
, flags
);
1658 if (nSigOpsCost
> MAX_BLOCK_SIGOPS_COST
)
1659 return state
.DoS(100, error("ConnectBlock(): too many sigops"),
1660 REJECT_INVALID
, "bad-blk-sigops");
1662 txdata
.emplace_back(tx
);
1663 if (!tx
.IsCoinBase())
1665 nFees
+= view
.GetValueIn(tx
)-tx
.GetValueOut();
1667 std::vector
<CScriptCheck
> vChecks
;
1668 bool fCacheResults
= fJustCheck
; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1669 if (!CheckInputs(tx
, state
, view
, fScriptChecks
, flags
, fCacheResults
, txdata
[i
], nScriptCheckThreads
? &vChecks
: NULL
))
1670 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1671 tx
.GetHash().ToString(), FormatStateMessage(state
));
1672 control
.Add(vChecks
);
1677 blockundo
.vtxundo
.push_back(CTxUndo());
1679 UpdateCoins(tx
, view
, i
== 0 ? undoDummy
: blockundo
.vtxundo
.back(), pindex
->nHeight
);
1681 vPos
.push_back(std::make_pair(tx
.GetHash(), pos
));
1682 pos
.nTxOffset
+= ::GetSerializeSize(tx
, SER_DISK
, CLIENT_VERSION
);
1684 int64_t nTime3
= GetTimeMicros(); nTimeConnect
+= nTime3
- nTime2
;
1685 LogPrint(BCLog::BENCH
, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block
.vtx
.size(), 0.001 * (nTime3
- nTime2
), 0.001 * (nTime3
- nTime2
) / block
.vtx
.size(), nInputs
<= 1 ? 0 : 0.001 * (nTime3
- nTime2
) / (nInputs
-1), nTimeConnect
* 0.000001);
1687 CAmount blockReward
= nFees
+ GetBlockSubsidy(pindex
->nHeight
, chainparams
.GetConsensus());
1688 if (block
.vtx
[0]->GetValueOut() > blockReward
)
1689 return state
.DoS(100,
1690 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1691 block
.vtx
[0]->GetValueOut(), blockReward
),
1692 REJECT_INVALID
, "bad-cb-amount");
1694 if (!control
.Wait())
1695 return state
.DoS(100, error("%s: CheckQueue failed", __func__
), REJECT_INVALID
, "block-validation-failed");
1696 int64_t nTime4
= GetTimeMicros(); nTimeVerify
+= nTime4
- nTime2
;
1697 LogPrint(BCLog::BENCH
, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs
- 1, 0.001 * (nTime4
- nTime2
), nInputs
<= 1 ? 0 : 0.001 * (nTime4
- nTime2
) / (nInputs
-1), nTimeVerify
* 0.000001);
1702 // Write undo information to disk
1703 if (pindex
->GetUndoPos().IsNull() || !pindex
->IsValid(BLOCK_VALID_SCRIPTS
))
1705 if (pindex
->GetUndoPos().IsNull()) {
1707 if (!FindUndoPos(state
, pindex
->nFile
, _pos
, ::GetSerializeSize(blockundo
, SER_DISK
, CLIENT_VERSION
) + 40))
1708 return error("ConnectBlock(): FindUndoPos failed");
1709 if (!UndoWriteToDisk(blockundo
, _pos
, pindex
->pprev
->GetBlockHash(), chainparams
.MessageStart()))
1710 return AbortNode(state
, "Failed to write undo data");
1712 // update nUndoPos in block index
1713 pindex
->nUndoPos
= _pos
.nPos
;
1714 pindex
->nStatus
|= BLOCK_HAVE_UNDO
;
1717 pindex
->RaiseValidity(BLOCK_VALID_SCRIPTS
);
1718 setDirtyBlockIndex
.insert(pindex
);
1722 if (!pblocktree
->WriteTxIndex(vPos
))
1723 return AbortNode(state
, "Failed to write transaction index");
1725 // add this block to the view's block chain
1726 view
.SetBestBlock(pindex
->GetBlockHash());
1728 int64_t nTime5
= GetTimeMicros(); nTimeIndex
+= nTime5
- nTime4
;
1729 LogPrint(BCLog::BENCH
, " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5
- nTime4
), nTimeIndex
* 0.000001);
1731 int64_t nTime6
= GetTimeMicros(); nTimeCallbacks
+= nTime6
- nTime5
;
1732 LogPrint(BCLog::BENCH
, " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6
- nTime5
), nTimeCallbacks
* 0.000001);
1738 * Update the on-disk chain state.
1739 * The caches and indexes are flushed depending on the mode we're called with
1740 * if they're too large, if it's been a while since the last write,
1741 * or always and in all cases if we're in prune mode and are deleting files.
1743 bool static FlushStateToDisk(const CChainParams
& chainparams
, CValidationState
&state
, FlushStateMode mode
, int nManualPruneHeight
) {
1744 int64_t nMempoolUsage
= mempool
.DynamicMemoryUsage();
1745 LOCK2(cs_main
, cs_LastBlockFile
);
1746 static int64_t nLastWrite
= 0;
1747 static int64_t nLastFlush
= 0;
1748 static int64_t nLastSetChain
= 0;
1749 std::set
<int> setFilesToPrune
;
1750 bool fFlushForPrune
= false;
1752 if (fPruneMode
&& (fCheckForPruning
|| nManualPruneHeight
> 0) && !fReindex
) {
1753 if (nManualPruneHeight
> 0) {
1754 FindFilesToPruneManual(setFilesToPrune
, nManualPruneHeight
);
1756 FindFilesToPrune(setFilesToPrune
, chainparams
.PruneAfterHeight());
1757 fCheckForPruning
= false;
1759 if (!setFilesToPrune
.empty()) {
1760 fFlushForPrune
= true;
1762 pblocktree
->WriteFlag("prunedblockfiles", true);
1767 int64_t nNow
= GetTimeMicros();
1768 // Avoid writing/flushing immediately after startup.
1769 if (nLastWrite
== 0) {
1772 if (nLastFlush
== 0) {
1775 if (nLastSetChain
== 0) {
1776 nLastSetChain
= nNow
;
1778 int64_t nMempoolSizeMax
= GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000;
1779 int64_t cacheSize
= pcoinsTip
->DynamicMemoryUsage() * DB_PEAK_USAGE_FACTOR
;
1780 int64_t nTotalSpace
= nCoinCacheUsage
+ std::max
<int64_t>(nMempoolSizeMax
- nMempoolUsage
, 0);
1781 // 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).
1782 bool fCacheLarge
= mode
== FLUSH_STATE_PERIODIC
&& cacheSize
> std::max((9 * nTotalSpace
) / 10, nTotalSpace
- MAX_BLOCK_COINSDB_USAGE
* 1024 * 1024);
1783 // The cache is over the limit, we have to write now.
1784 bool fCacheCritical
= mode
== FLUSH_STATE_IF_NEEDED
&& cacheSize
> nTotalSpace
;
1785 // 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.
1786 bool fPeriodicWrite
= mode
== FLUSH_STATE_PERIODIC
&& nNow
> nLastWrite
+ (int64_t)DATABASE_WRITE_INTERVAL
* 1000000;
1787 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1788 bool fPeriodicFlush
= mode
== FLUSH_STATE_PERIODIC
&& nNow
> nLastFlush
+ (int64_t)DATABASE_FLUSH_INTERVAL
* 1000000;
1789 // Combine all conditions that result in a full cache flush.
1790 bool fDoFullFlush
= (mode
== FLUSH_STATE_ALWAYS
) || fCacheLarge
|| fCacheCritical
|| fPeriodicFlush
|| fFlushForPrune
;
1791 // Write blocks and block index to disk.
1792 if (fDoFullFlush
|| fPeriodicWrite
) {
1793 // Depend on nMinDiskSpace to ensure we can write block index
1794 if (!CheckDiskSpace(0))
1795 return state
.Error("out of disk space");
1796 // First make sure all block and undo data is flushed to disk.
1798 // Then update all block file information (which may refer to block and undo files).
1800 std::vector
<std::pair
<int, const CBlockFileInfo
*> > vFiles
;
1801 vFiles
.reserve(setDirtyFileInfo
.size());
1802 for (std::set
<int>::iterator it
= setDirtyFileInfo
.begin(); it
!= setDirtyFileInfo
.end(); ) {
1803 vFiles
.push_back(std::make_pair(*it
, &vinfoBlockFile
[*it
]));
1804 setDirtyFileInfo
.erase(it
++);
1806 std::vector
<const CBlockIndex
*> vBlocks
;
1807 vBlocks
.reserve(setDirtyBlockIndex
.size());
1808 for (std::set
<CBlockIndex
*>::iterator it
= setDirtyBlockIndex
.begin(); it
!= setDirtyBlockIndex
.end(); ) {
1809 vBlocks
.push_back(*it
);
1810 setDirtyBlockIndex
.erase(it
++);
1812 if (!pblocktree
->WriteBatchSync(vFiles
, nLastBlockFile
, vBlocks
)) {
1813 return AbortNode(state
, "Failed to write to block index database");
1816 // Finally remove any pruned files
1818 UnlinkPrunedFiles(setFilesToPrune
);
1821 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1823 // Typical Coin structures on disk are around 48 bytes in size.
1824 // Pushing a new one to the database can cause it to be written
1825 // twice (once in the log, and once in the tables). This is already
1826 // an overestimation, as most will delete an existing entry or
1827 // overwrite one. Still, use a conservative safety factor of 2.
1828 if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip
->GetCacheSize()))
1829 return state
.Error("out of disk space");
1830 // Flush the chainstate (which may refer to block index entries).
1831 if (!pcoinsTip
->Flush())
1832 return AbortNode(state
, "Failed to write to coin database");
1835 if (fDoFullFlush
|| ((mode
== FLUSH_STATE_ALWAYS
|| mode
== FLUSH_STATE_PERIODIC
) && nNow
> nLastSetChain
+ (int64_t)DATABASE_WRITE_INTERVAL
* 1000000)) {
1836 // Update best block in wallet (so we can detect restored wallets).
1837 GetMainSignals().SetBestChain(chainActive
.GetLocator());
1838 nLastSetChain
= nNow
;
1840 } catch (const std::runtime_error
& e
) {
1841 return AbortNode(state
, std::string("System error while flushing: ") + e
.what());
1846 void FlushStateToDisk() {
1847 CValidationState state
;
1848 const CChainParams
& chainparams
= Params();
1849 FlushStateToDisk(chainparams
, state
, FLUSH_STATE_ALWAYS
);
1852 void PruneAndFlush() {
1853 CValidationState state
;
1854 fCheckForPruning
= true;
1855 const CChainParams
& chainparams
= Params();
1856 FlushStateToDisk(chainparams
, state
, FLUSH_STATE_NONE
);
1859 static void DoWarning(const std::string
& strWarning
)
1861 static bool fWarned
= false;
1862 SetMiscWarning(strWarning
);
1864 AlertNotify(strWarning
);
1869 /** Update chainActive and related internal data structures. */
1870 void static UpdateTip(CBlockIndex
*pindexNew
, const CChainParams
& chainParams
) {
1871 chainActive
.SetTip(pindexNew
);
1874 mempool
.AddTransactionsUpdated(1);
1876 cvBlockChange
.notify_all();
1878 std::vector
<std::string
> warningMessages
;
1879 if (!IsInitialBlockDownload())
1882 const CBlockIndex
* pindex
= chainActive
.Tip();
1883 for (int bit
= 0; bit
< VERSIONBITS_NUM_BITS
; bit
++) {
1884 WarningBitsConditionChecker
checker(bit
);
1885 ThresholdState state
= checker
.GetStateFor(pindex
, chainParams
.GetConsensus(), warningcache
[bit
]);
1886 if (state
== THRESHOLD_ACTIVE
|| state
== THRESHOLD_LOCKED_IN
) {
1887 const std::string strWarning
= strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit
);
1888 if (state
== THRESHOLD_ACTIVE
) {
1889 DoWarning(strWarning
);
1891 warningMessages
.push_back(strWarning
);
1895 // Check the version of the last 100 blocks to see if we need to upgrade:
1896 for (int i
= 0; i
< 100 && pindex
!= NULL
; i
++)
1898 int32_t nExpectedVersion
= ComputeBlockVersion(pindex
->pprev
, chainParams
.GetConsensus());
1899 if (pindex
->nVersion
> VERSIONBITS_LAST_OLD_BLOCK_VERSION
&& (pindex
->nVersion
& ~nExpectedVersion
) != 0)
1901 pindex
= pindex
->pprev
;
1904 warningMessages
.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded
));
1905 if (nUpgraded
> 100/2)
1907 std::string strWarning
= _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
1908 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1909 DoWarning(strWarning
);
1912 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__
,
1913 chainActive
.Tip()->GetBlockHash().ToString(), chainActive
.Height(), chainActive
.Tip()->nVersion
,
1914 log(chainActive
.Tip()->nChainWork
.getdouble())/log(2.0), (unsigned long)chainActive
.Tip()->nChainTx
,
1915 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive
.Tip()->GetBlockTime()),
1916 GuessVerificationProgress(chainParams
.TxData(), chainActive
.Tip()), pcoinsTip
->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip
->GetCacheSize());
1917 if (!warningMessages
.empty())
1918 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages
, ", "));
1923 /** Disconnect chainActive's tip.
1924 * After calling, the mempool will be in an inconsistent state, with
1925 * transactions from disconnected blocks being added to disconnectpool. You
1926 * should make the mempool consistent again by calling UpdateMempoolForReorg.
1927 * with cs_main held.
1929 * If disconnectpool is NULL, then no disconnected transactions are added to
1930 * disconnectpool (note that the caller is responsible for mempool consistency
1933 bool static DisconnectTip(CValidationState
& state
, const CChainParams
& chainparams
, DisconnectedBlockTransactions
*disconnectpool
)
1935 CBlockIndex
*pindexDelete
= chainActive
.Tip();
1936 assert(pindexDelete
);
1937 // Read block from disk.
1938 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
1939 CBlock
& block
= *pblock
;
1940 if (!ReadBlockFromDisk(block
, pindexDelete
, chainparams
.GetConsensus()))
1941 return AbortNode(state
, "Failed to read block");
1942 // Apply the block atomically to the chain state.
1943 int64_t nStart
= GetTimeMicros();
1945 CCoinsViewCache
view(pcoinsTip
);
1946 if (DisconnectBlock(block
, pindexDelete
, view
) != DISCONNECT_OK
)
1947 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete
->GetBlockHash().ToString());
1948 bool flushed
= view
.Flush();
1951 LogPrint(BCLog::BENCH
, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart
) * 0.001);
1952 // Write the chain state to disk, if necessary.
1953 if (!FlushStateToDisk(chainparams
, state
, FLUSH_STATE_IF_NEEDED
))
1956 if (disconnectpool
) {
1957 // Save transactions to re-add to mempool at end of reorg
1958 for (auto it
= block
.vtx
.rbegin(); it
!= block
.vtx
.rend(); ++it
) {
1959 disconnectpool
->addTransaction(*it
);
1961 while (disconnectpool
->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE
* 1000) {
1962 // Drop the earliest entry, and remove its children from the mempool.
1963 auto it
= disconnectpool
->queuedTx
.get
<insertion_order
>().begin();
1964 mempool
.removeRecursive(**it
, MemPoolRemovalReason::REORG
);
1965 disconnectpool
->removeEntry(it
);
1969 // Update chainActive and related variables.
1970 UpdateTip(pindexDelete
->pprev
, chainparams
);
1971 // Let wallets know transactions went from 1-confirmed to
1972 // 0-confirmed or conflicted:
1973 GetMainSignals().BlockDisconnected(pblock
);
1977 static int64_t nTimeReadFromDisk
= 0;
1978 static int64_t nTimeConnectTotal
= 0;
1979 static int64_t nTimeFlush
= 0;
1980 static int64_t nTimeChainState
= 0;
1981 static int64_t nTimePostConnect
= 0;
1983 struct PerBlockConnectTrace
{
1984 CBlockIndex
* pindex
= NULL
;
1985 std::shared_ptr
<const CBlock
> pblock
;
1986 std::shared_ptr
<std::vector
<CTransactionRef
>> conflictedTxs
;
1987 PerBlockConnectTrace() : conflictedTxs(std::make_shared
<std::vector
<CTransactionRef
>>()) {}
1990 * Used to track blocks whose transactions were applied to the UTXO state as a
1991 * part of a single ActivateBestChainStep call.
1993 * This class also tracks transactions that are removed from the mempool as
1994 * conflicts (per block) and can be used to pass all those transactions
1995 * through SyncTransaction.
1997 * This class assumes (and asserts) that the conflicted transactions for a given
1998 * block are added via mempool callbacks prior to the BlockConnected() associated
1999 * with those transactions. If any transactions are marked conflicted, it is
2000 * assumed that an associated block will always be added.
2002 * This class is single-use, once you call GetBlocksConnected() you have to throw
2003 * it away and make a new one.
2005 class ConnectTrace
{
2007 std::vector
<PerBlockConnectTrace
> blocksConnected
;
2011 ConnectTrace(CTxMemPool
&_pool
) : blocksConnected(1), pool(_pool
) {
2012 pool
.NotifyEntryRemoved
.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved
, this, _1
, _2
));
2016 pool
.NotifyEntryRemoved
.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved
, this, _1
, _2
));
2019 void BlockConnected(CBlockIndex
* pindex
, std::shared_ptr
<const CBlock
> pblock
) {
2020 assert(!blocksConnected
.back().pindex
);
2023 blocksConnected
.back().pindex
= pindex
;
2024 blocksConnected
.back().pblock
= std::move(pblock
);
2025 blocksConnected
.emplace_back();
2028 std::vector
<PerBlockConnectTrace
>& GetBlocksConnected() {
2029 // We always keep one extra block at the end of our list because
2030 // blocks are added after all the conflicted transactions have
2031 // been filled in. Thus, the last entry should always be an empty
2032 // one waiting for the transactions from the next block. We pop
2033 // the last entry here to make sure the list we return is sane.
2034 assert(!blocksConnected
.back().pindex
);
2035 assert(blocksConnected
.back().conflictedTxs
->empty());
2036 blocksConnected
.pop_back();
2037 return blocksConnected
;
2040 void NotifyEntryRemoved(CTransactionRef txRemoved
, MemPoolRemovalReason reason
) {
2041 assert(!blocksConnected
.back().pindex
);
2042 if (reason
== MemPoolRemovalReason::CONFLICT
) {
2043 blocksConnected
.back().conflictedTxs
->emplace_back(std::move(txRemoved
));
2049 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2050 * corresponding to pindexNew, to bypass loading it again from disk.
2052 * The block is added to connectTrace if connection succeeds.
2054 bool static ConnectTip(CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
* pindexNew
, const std::shared_ptr
<const CBlock
>& pblock
, ConnectTrace
& connectTrace
, DisconnectedBlockTransactions
&disconnectpool
)
2056 assert(pindexNew
->pprev
== chainActive
.Tip());
2057 // Read block from disk.
2058 int64_t nTime1
= GetTimeMicros();
2059 std::shared_ptr
<const CBlock
> pthisBlock
;
2061 std::shared_ptr
<CBlock
> pblockNew
= std::make_shared
<CBlock
>();
2062 if (!ReadBlockFromDisk(*pblockNew
, pindexNew
, chainparams
.GetConsensus()))
2063 return AbortNode(state
, "Failed to read block");
2064 pthisBlock
= pblockNew
;
2066 pthisBlock
= pblock
;
2068 const CBlock
& blockConnecting
= *pthisBlock
;
2069 // Apply the block atomically to the chain state.
2070 int64_t nTime2
= GetTimeMicros(); nTimeReadFromDisk
+= nTime2
- nTime1
;
2072 LogPrint(BCLog::BENCH
, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2
- nTime1
) * 0.001, nTimeReadFromDisk
* 0.000001);
2074 CCoinsViewCache
view(pcoinsTip
);
2075 bool rv
= ConnectBlock(blockConnecting
, state
, pindexNew
, view
, chainparams
);
2076 GetMainSignals().BlockChecked(blockConnecting
, state
);
2078 if (state
.IsInvalid())
2079 InvalidBlockFound(pindexNew
, state
);
2080 return error("ConnectTip(): ConnectBlock %s failed", pindexNew
->GetBlockHash().ToString());
2082 nTime3
= GetTimeMicros(); nTimeConnectTotal
+= nTime3
- nTime2
;
2083 LogPrint(BCLog::BENCH
, " - Connect total: %.2fms [%.2fs]\n", (nTime3
- nTime2
) * 0.001, nTimeConnectTotal
* 0.000001);
2084 bool flushed
= view
.Flush();
2087 int64_t nTime4
= GetTimeMicros(); nTimeFlush
+= nTime4
- nTime3
;
2088 LogPrint(BCLog::BENCH
, " - Flush: %.2fms [%.2fs]\n", (nTime4
- nTime3
) * 0.001, nTimeFlush
* 0.000001);
2089 // Write the chain state to disk, if necessary.
2090 if (!FlushStateToDisk(chainparams
, state
, FLUSH_STATE_IF_NEEDED
))
2092 int64_t nTime5
= GetTimeMicros(); nTimeChainState
+= nTime5
- nTime4
;
2093 LogPrint(BCLog::BENCH
, " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5
- nTime4
) * 0.001, nTimeChainState
* 0.000001);
2094 // Remove conflicting transactions from the mempool.;
2095 mempool
.removeForBlock(blockConnecting
.vtx
, pindexNew
->nHeight
);
2096 disconnectpool
.removeForBlock(blockConnecting
.vtx
);
2097 // Update chainActive & related variables.
2098 UpdateTip(pindexNew
, chainparams
);
2100 int64_t nTime6
= GetTimeMicros(); nTimePostConnect
+= nTime6
- nTime5
; nTimeTotal
+= nTime6
- nTime1
;
2101 LogPrint(BCLog::BENCH
, " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6
- nTime5
) * 0.001, nTimePostConnect
* 0.000001);
2102 LogPrint(BCLog::BENCH
, "- Connect block: %.2fms [%.2fs]\n", (nTime6
- nTime1
) * 0.001, nTimeTotal
* 0.000001);
2104 connectTrace
.BlockConnected(pindexNew
, std::move(pthisBlock
));
2109 * Return the tip of the chain with the most work in it, that isn't
2110 * known to be invalid (it's however far from certain to be valid).
2112 static CBlockIndex
* FindMostWorkChain() {
2114 CBlockIndex
*pindexNew
= NULL
;
2116 // Find the best candidate header.
2118 std::set
<CBlockIndex
*, CBlockIndexWorkComparator
>::reverse_iterator it
= setBlockIndexCandidates
.rbegin();
2119 if (it
== setBlockIndexCandidates
.rend())
2124 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2125 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2126 CBlockIndex
*pindexTest
= pindexNew
;
2127 bool fInvalidAncestor
= false;
2128 while (pindexTest
&& !chainActive
.Contains(pindexTest
)) {
2129 assert(pindexTest
->nChainTx
|| pindexTest
->nHeight
== 0);
2131 // Pruned nodes may have entries in setBlockIndexCandidates for
2132 // which block files have been deleted. Remove those as candidates
2133 // for the most work chain if we come across them; we can't switch
2134 // to a chain unless we have all the non-active-chain parent blocks.
2135 bool fFailedChain
= pindexTest
->nStatus
& BLOCK_FAILED_MASK
;
2136 bool fMissingData
= !(pindexTest
->nStatus
& BLOCK_HAVE_DATA
);
2137 if (fFailedChain
|| fMissingData
) {
2138 // Candidate chain is not usable (either invalid or missing data)
2139 if (fFailedChain
&& (pindexBestInvalid
== NULL
|| pindexNew
->nChainWork
> pindexBestInvalid
->nChainWork
))
2140 pindexBestInvalid
= pindexNew
;
2141 CBlockIndex
*pindexFailed
= pindexNew
;
2142 // Remove the entire chain from the set.
2143 while (pindexTest
!= pindexFailed
) {
2145 pindexFailed
->nStatus
|= BLOCK_FAILED_CHILD
;
2146 } else if (fMissingData
) {
2147 // If we're missing data, then add back to mapBlocksUnlinked,
2148 // so that if the block arrives in the future we can try adding
2149 // to setBlockIndexCandidates again.
2150 mapBlocksUnlinked
.insert(std::make_pair(pindexFailed
->pprev
, pindexFailed
));
2152 setBlockIndexCandidates
.erase(pindexFailed
);
2153 pindexFailed
= pindexFailed
->pprev
;
2155 setBlockIndexCandidates
.erase(pindexTest
);
2156 fInvalidAncestor
= true;
2159 pindexTest
= pindexTest
->pprev
;
2161 if (!fInvalidAncestor
)
2166 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2167 static void PruneBlockIndexCandidates() {
2168 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2169 // reorganization to a better block fails.
2170 std::set
<CBlockIndex
*, CBlockIndexWorkComparator
>::iterator it
= setBlockIndexCandidates
.begin();
2171 while (it
!= setBlockIndexCandidates
.end() && setBlockIndexCandidates
.value_comp()(*it
, chainActive
.Tip())) {
2172 setBlockIndexCandidates
.erase(it
++);
2174 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2175 assert(!setBlockIndexCandidates
.empty());
2179 * Try to make some progress towards making pindexMostWork the active block.
2180 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2182 static bool ActivateBestChainStep(CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
* pindexMostWork
, const std::shared_ptr
<const CBlock
>& pblock
, bool& fInvalidFound
, ConnectTrace
& connectTrace
)
2184 AssertLockHeld(cs_main
);
2185 const CBlockIndex
*pindexOldTip
= chainActive
.Tip();
2186 const CBlockIndex
*pindexFork
= chainActive
.FindFork(pindexMostWork
);
2188 // Disconnect active blocks which are no longer in the best chain.
2189 bool fBlocksDisconnected
= false;
2190 DisconnectedBlockTransactions disconnectpool
;
2191 while (chainActive
.Tip() && chainActive
.Tip() != pindexFork
) {
2192 if (!DisconnectTip(state
, chainparams
, &disconnectpool
)) {
2193 // This is likely a fatal error, but keep the mempool consistent,
2194 // just in case. Only remove from the mempool in this case.
2195 UpdateMempoolForReorg(disconnectpool
, false);
2198 fBlocksDisconnected
= true;
2201 // Build list of new blocks to connect.
2202 std::vector
<CBlockIndex
*> vpindexToConnect
;
2203 bool fContinue
= true;
2204 int nHeight
= pindexFork
? pindexFork
->nHeight
: -1;
2205 while (fContinue
&& nHeight
!= pindexMostWork
->nHeight
) {
2206 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2207 // a few blocks along the way.
2208 int nTargetHeight
= std::min(nHeight
+ 32, pindexMostWork
->nHeight
);
2209 vpindexToConnect
.clear();
2210 vpindexToConnect
.reserve(nTargetHeight
- nHeight
);
2211 CBlockIndex
*pindexIter
= pindexMostWork
->GetAncestor(nTargetHeight
);
2212 while (pindexIter
&& pindexIter
->nHeight
!= nHeight
) {
2213 vpindexToConnect
.push_back(pindexIter
);
2214 pindexIter
= pindexIter
->pprev
;
2216 nHeight
= nTargetHeight
;
2218 // Connect new blocks.
2219 BOOST_REVERSE_FOREACH(CBlockIndex
*pindexConnect
, vpindexToConnect
) {
2220 if (!ConnectTip(state
, chainparams
, pindexConnect
, pindexConnect
== pindexMostWork
? pblock
: std::shared_ptr
<const CBlock
>(), connectTrace
, disconnectpool
)) {
2221 if (state
.IsInvalid()) {
2222 // The block violates a consensus rule.
2223 if (!state
.CorruptionPossible())
2224 InvalidChainFound(vpindexToConnect
.back());
2225 state
= CValidationState();
2226 fInvalidFound
= true;
2230 // A system error occurred (disk space, database error, ...).
2231 // Make the mempool consistent with the current tip, just in case
2232 // any observers try to use it before shutdown.
2233 UpdateMempoolForReorg(disconnectpool
, false);
2237 PruneBlockIndexCandidates();
2238 if (!pindexOldTip
|| chainActive
.Tip()->nChainWork
> pindexOldTip
->nChainWork
) {
2239 // We're in a better position than we were. Return temporarily to release the lock.
2247 if (fBlocksDisconnected
) {
2248 // If any blocks were disconnected, disconnectpool may be non empty. Add
2249 // any disconnected transactions back to the mempool.
2250 UpdateMempoolForReorg(disconnectpool
, true);
2252 mempool
.check(pcoinsTip
);
2254 // Callbacks/notifications for a new best chain.
2256 CheckForkWarningConditionsOnNewFork(vpindexToConnect
.back());
2258 CheckForkWarningConditions();
2263 static void NotifyHeaderTip() {
2264 bool fNotify
= false;
2265 bool fInitialBlockDownload
= false;
2266 static CBlockIndex
* pindexHeaderOld
= NULL
;
2267 CBlockIndex
* pindexHeader
= NULL
;
2270 pindexHeader
= pindexBestHeader
;
2272 if (pindexHeader
!= pindexHeaderOld
) {
2274 fInitialBlockDownload
= IsInitialBlockDownload();
2275 pindexHeaderOld
= pindexHeader
;
2278 // Send block tip changed notifications without cs_main
2280 uiInterface
.NotifyHeaderTip(fInitialBlockDownload
, pindexHeader
);
2285 * Make the best chain active, in multiple steps. The result is either failure
2286 * or an activated best chain. pblock is either NULL or a pointer to a block
2287 * that is already loaded (to avoid loading it again from disk).
2289 bool ActivateBestChain(CValidationState
&state
, const CChainParams
& chainparams
, std::shared_ptr
<const CBlock
> pblock
) {
2290 // Note that while we're often called here from ProcessNewBlock, this is
2291 // far from a guarantee. Things in the P2P/RPC will often end up calling
2292 // us in the middle of ProcessNewBlock - do not assume pblock is set
2293 // sanely for performance or correctness!
2295 CBlockIndex
*pindexMostWork
= NULL
;
2296 CBlockIndex
*pindexNewTip
= NULL
;
2297 int nStopAtHeight
= GetArg("-stopatheight", DEFAULT_STOPATHEIGHT
);
2299 boost::this_thread::interruption_point();
2300 if (ShutdownRequested())
2303 const CBlockIndex
*pindexFork
;
2304 bool fInitialDownload
;
2307 ConnectTrace
connectTrace(mempool
); // Destructed before cs_main is unlocked
2309 CBlockIndex
*pindexOldTip
= chainActive
.Tip();
2310 if (pindexMostWork
== NULL
) {
2311 pindexMostWork
= FindMostWorkChain();
2314 // Whether we have anything to do at all.
2315 if (pindexMostWork
== NULL
|| pindexMostWork
== chainActive
.Tip())
2318 bool fInvalidFound
= false;
2319 std::shared_ptr
<const CBlock
> nullBlockPtr
;
2320 if (!ActivateBestChainStep(state
, chainparams
, pindexMostWork
, pblock
&& pblock
->GetHash() == pindexMostWork
->GetBlockHash() ? pblock
: nullBlockPtr
, fInvalidFound
, connectTrace
))
2323 if (fInvalidFound
) {
2324 // Wipe cache, we may need another branch now.
2325 pindexMostWork
= NULL
;
2327 pindexNewTip
= chainActive
.Tip();
2328 pindexFork
= chainActive
.FindFork(pindexOldTip
);
2329 fInitialDownload
= IsInitialBlockDownload();
2331 for (const PerBlockConnectTrace
& trace
: connectTrace
.GetBlocksConnected()) {
2332 assert(trace
.pblock
&& trace
.pindex
);
2333 GetMainSignals().BlockConnected(trace
.pblock
, trace
.pindex
, *trace
.conflictedTxs
);
2336 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2338 // Notifications/callbacks that can run without cs_main
2340 // Notify external listeners about the new tip.
2341 GetMainSignals().UpdatedBlockTip(pindexNewTip
, pindexFork
, fInitialDownload
);
2343 // Always notify the UI if a new block tip was connected
2344 if (pindexFork
!= pindexNewTip
) {
2345 uiInterface
.NotifyBlockTip(fInitialDownload
, pindexNewTip
);
2348 if (nStopAtHeight
&& pindexNewTip
&& pindexNewTip
->nHeight
>= nStopAtHeight
) StartShutdown();
2349 } while (pindexNewTip
!= pindexMostWork
);
2350 CheckBlockIndex(chainparams
.GetConsensus());
2352 // Write changes periodically to disk, after relay.
2353 if (!FlushStateToDisk(chainparams
, state
, FLUSH_STATE_PERIODIC
)) {
2361 bool PreciousBlock(CValidationState
& state
, const CChainParams
& params
, CBlockIndex
*pindex
)
2365 if (pindex
->nChainWork
< chainActive
.Tip()->nChainWork
) {
2366 // Nothing to do, this block is not at the tip.
2369 if (chainActive
.Tip()->nChainWork
> nLastPreciousChainwork
) {
2370 // The chain has been extended since the last call, reset the counter.
2371 nBlockReverseSequenceId
= -1;
2373 nLastPreciousChainwork
= chainActive
.Tip()->nChainWork
;
2374 setBlockIndexCandidates
.erase(pindex
);
2375 pindex
->nSequenceId
= nBlockReverseSequenceId
;
2376 if (nBlockReverseSequenceId
> std::numeric_limits
<int32_t>::min()) {
2377 // We can't keep reducing the counter if somebody really wants to
2378 // call preciousblock 2**31-1 times on the same set of tips...
2379 nBlockReverseSequenceId
--;
2381 if (pindex
->IsValid(BLOCK_VALID_TRANSACTIONS
) && pindex
->nChainTx
) {
2382 setBlockIndexCandidates
.insert(pindex
);
2383 PruneBlockIndexCandidates();
2387 return ActivateBestChain(state
, params
);
2390 bool InvalidateBlock(CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
*pindex
)
2392 AssertLockHeld(cs_main
);
2394 // Mark the block itself as invalid.
2395 pindex
->nStatus
|= BLOCK_FAILED_VALID
;
2396 setDirtyBlockIndex
.insert(pindex
);
2397 setBlockIndexCandidates
.erase(pindex
);
2399 DisconnectedBlockTransactions disconnectpool
;
2400 while (chainActive
.Contains(pindex
)) {
2401 CBlockIndex
*pindexWalk
= chainActive
.Tip();
2402 pindexWalk
->nStatus
|= BLOCK_FAILED_CHILD
;
2403 setDirtyBlockIndex
.insert(pindexWalk
);
2404 setBlockIndexCandidates
.erase(pindexWalk
);
2405 // ActivateBestChain considers blocks already in chainActive
2406 // unconditionally valid already, so force disconnect away from it.
2407 if (!DisconnectTip(state
, chainparams
, &disconnectpool
)) {
2408 // It's probably hopeless to try to make the mempool consistent
2409 // here if DisconnectTip failed, but we can try.
2410 UpdateMempoolForReorg(disconnectpool
, false);
2415 // DisconnectTip will add transactions to disconnectpool; try to add these
2416 // back to the mempool.
2417 UpdateMempoolForReorg(disconnectpool
, true);
2419 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2421 BlockMap::iterator it
= mapBlockIndex
.begin();
2422 while (it
!= mapBlockIndex
.end()) {
2423 if (it
->second
->IsValid(BLOCK_VALID_TRANSACTIONS
) && it
->second
->nChainTx
&& !setBlockIndexCandidates
.value_comp()(it
->second
, chainActive
.Tip())) {
2424 setBlockIndexCandidates
.insert(it
->second
);
2429 InvalidChainFound(pindex
);
2430 uiInterface
.NotifyBlockTip(IsInitialBlockDownload(), pindex
->pprev
);
2434 bool ResetBlockFailureFlags(CBlockIndex
*pindex
) {
2435 AssertLockHeld(cs_main
);
2437 int nHeight
= pindex
->nHeight
;
2439 // Remove the invalidity flag from this block and all its descendants.
2440 BlockMap::iterator it
= mapBlockIndex
.begin();
2441 while (it
!= mapBlockIndex
.end()) {
2442 if (!it
->second
->IsValid() && it
->second
->GetAncestor(nHeight
) == pindex
) {
2443 it
->second
->nStatus
&= ~BLOCK_FAILED_MASK
;
2444 setDirtyBlockIndex
.insert(it
->second
);
2445 if (it
->second
->IsValid(BLOCK_VALID_TRANSACTIONS
) && it
->second
->nChainTx
&& setBlockIndexCandidates
.value_comp()(chainActive
.Tip(), it
->second
)) {
2446 setBlockIndexCandidates
.insert(it
->second
);
2448 if (it
->second
== pindexBestInvalid
) {
2449 // Reset invalid block marker if it was pointing to one of those.
2450 pindexBestInvalid
= NULL
;
2456 // Remove the invalidity flag from all ancestors too.
2457 while (pindex
!= NULL
) {
2458 if (pindex
->nStatus
& BLOCK_FAILED_MASK
) {
2459 pindex
->nStatus
&= ~BLOCK_FAILED_MASK
;
2460 setDirtyBlockIndex
.insert(pindex
);
2462 pindex
= pindex
->pprev
;
2467 static CBlockIndex
* AddToBlockIndex(const CBlockHeader
& block
)
2469 // Check for duplicate
2470 uint256 hash
= block
.GetHash();
2471 BlockMap::iterator it
= mapBlockIndex
.find(hash
);
2472 if (it
!= mapBlockIndex
.end())
2475 // Construct new block index object
2476 CBlockIndex
* pindexNew
= new CBlockIndex(block
);
2478 // We assign the sequence id to blocks only when the full data is available,
2479 // to avoid miners withholding blocks but broadcasting headers, to get a
2480 // competitive advantage.
2481 pindexNew
->nSequenceId
= 0;
2482 BlockMap::iterator mi
= mapBlockIndex
.insert(std::make_pair(hash
, pindexNew
)).first
;
2483 pindexNew
->phashBlock
= &((*mi
).first
);
2484 BlockMap::iterator miPrev
= mapBlockIndex
.find(block
.hashPrevBlock
);
2485 if (miPrev
!= mapBlockIndex
.end())
2487 pindexNew
->pprev
= (*miPrev
).second
;
2488 pindexNew
->nHeight
= pindexNew
->pprev
->nHeight
+ 1;
2489 pindexNew
->BuildSkip();
2491 pindexNew
->nTimeMax
= (pindexNew
->pprev
? std::max(pindexNew
->pprev
->nTimeMax
, pindexNew
->nTime
) : pindexNew
->nTime
);
2492 pindexNew
->nChainWork
= (pindexNew
->pprev
? pindexNew
->pprev
->nChainWork
: 0) + GetBlockProof(*pindexNew
);
2493 pindexNew
->RaiseValidity(BLOCK_VALID_TREE
);
2494 if (pindexBestHeader
== NULL
|| pindexBestHeader
->nChainWork
< pindexNew
->nChainWork
)
2495 pindexBestHeader
= pindexNew
;
2497 setDirtyBlockIndex
.insert(pindexNew
);
2502 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2503 static bool ReceivedBlockTransactions(const CBlock
&block
, CValidationState
& state
, CBlockIndex
*pindexNew
, const CDiskBlockPos
& pos
, const Consensus::Params
& consensusParams
)
2505 pindexNew
->nTx
= block
.vtx
.size();
2506 pindexNew
->nChainTx
= 0;
2507 pindexNew
->nFile
= pos
.nFile
;
2508 pindexNew
->nDataPos
= pos
.nPos
;
2509 pindexNew
->nUndoPos
= 0;
2510 pindexNew
->nStatus
|= BLOCK_HAVE_DATA
;
2511 if (IsWitnessEnabled(pindexNew
->pprev
, consensusParams
)) {
2512 pindexNew
->nStatus
|= BLOCK_OPT_WITNESS
;
2514 pindexNew
->RaiseValidity(BLOCK_VALID_TRANSACTIONS
);
2515 setDirtyBlockIndex
.insert(pindexNew
);
2517 if (pindexNew
->pprev
== NULL
|| pindexNew
->pprev
->nChainTx
) {
2518 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2519 std::deque
<CBlockIndex
*> queue
;
2520 queue
.push_back(pindexNew
);
2522 // Recursively process any descendant blocks that now may be eligible to be connected.
2523 while (!queue
.empty()) {
2524 CBlockIndex
*pindex
= queue
.front();
2526 pindex
->nChainTx
= (pindex
->pprev
? pindex
->pprev
->nChainTx
: 0) + pindex
->nTx
;
2528 LOCK(cs_nBlockSequenceId
);
2529 pindex
->nSequenceId
= nBlockSequenceId
++;
2531 if (chainActive
.Tip() == NULL
|| !setBlockIndexCandidates
.value_comp()(pindex
, chainActive
.Tip())) {
2532 setBlockIndexCandidates
.insert(pindex
);
2534 std::pair
<std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
, std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
> range
= mapBlocksUnlinked
.equal_range(pindex
);
2535 while (range
.first
!= range
.second
) {
2536 std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator it
= range
.first
;
2537 queue
.push_back(it
->second
);
2539 mapBlocksUnlinked
.erase(it
);
2543 if (pindexNew
->pprev
&& pindexNew
->pprev
->IsValid(BLOCK_VALID_TREE
)) {
2544 mapBlocksUnlinked
.insert(std::make_pair(pindexNew
->pprev
, pindexNew
));
2551 static bool FindBlockPos(CValidationState
&state
, CDiskBlockPos
&pos
, unsigned int nAddSize
, unsigned int nHeight
, uint64_t nTime
, bool fKnown
= false)
2553 LOCK(cs_LastBlockFile
);
2555 unsigned int nFile
= fKnown
? pos
.nFile
: nLastBlockFile
;
2556 if (vinfoBlockFile
.size() <= nFile
) {
2557 vinfoBlockFile
.resize(nFile
+ 1);
2561 while (vinfoBlockFile
[nFile
].nSize
+ nAddSize
>= MAX_BLOCKFILE_SIZE
) {
2563 if (vinfoBlockFile
.size() <= nFile
) {
2564 vinfoBlockFile
.resize(nFile
+ 1);
2568 pos
.nPos
= vinfoBlockFile
[nFile
].nSize
;
2571 if ((int)nFile
!= nLastBlockFile
) {
2573 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile
, vinfoBlockFile
[nLastBlockFile
].ToString());
2575 FlushBlockFile(!fKnown
);
2576 nLastBlockFile
= nFile
;
2579 vinfoBlockFile
[nFile
].AddBlock(nHeight
, nTime
);
2581 vinfoBlockFile
[nFile
].nSize
= std::max(pos
.nPos
+ nAddSize
, vinfoBlockFile
[nFile
].nSize
);
2583 vinfoBlockFile
[nFile
].nSize
+= nAddSize
;
2586 unsigned int nOldChunks
= (pos
.nPos
+ BLOCKFILE_CHUNK_SIZE
- 1) / BLOCKFILE_CHUNK_SIZE
;
2587 unsigned int nNewChunks
= (vinfoBlockFile
[nFile
].nSize
+ BLOCKFILE_CHUNK_SIZE
- 1) / BLOCKFILE_CHUNK_SIZE
;
2588 if (nNewChunks
> nOldChunks
) {
2590 fCheckForPruning
= true;
2591 if (CheckDiskSpace(nNewChunks
* BLOCKFILE_CHUNK_SIZE
- pos
.nPos
)) {
2592 FILE *file
= OpenBlockFile(pos
);
2594 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks
* BLOCKFILE_CHUNK_SIZE
, pos
.nFile
);
2595 AllocateFileRange(file
, pos
.nPos
, nNewChunks
* BLOCKFILE_CHUNK_SIZE
- pos
.nPos
);
2600 return state
.Error("out of disk space");
2604 setDirtyFileInfo
.insert(nFile
);
2608 static bool FindUndoPos(CValidationState
&state
, int nFile
, CDiskBlockPos
&pos
, unsigned int nAddSize
)
2612 LOCK(cs_LastBlockFile
);
2614 unsigned int nNewSize
;
2615 pos
.nPos
= vinfoBlockFile
[nFile
].nUndoSize
;
2616 nNewSize
= vinfoBlockFile
[nFile
].nUndoSize
+= nAddSize
;
2617 setDirtyFileInfo
.insert(nFile
);
2619 unsigned int nOldChunks
= (pos
.nPos
+ UNDOFILE_CHUNK_SIZE
- 1) / UNDOFILE_CHUNK_SIZE
;
2620 unsigned int nNewChunks
= (nNewSize
+ UNDOFILE_CHUNK_SIZE
- 1) / UNDOFILE_CHUNK_SIZE
;
2621 if (nNewChunks
> nOldChunks
) {
2623 fCheckForPruning
= true;
2624 if (CheckDiskSpace(nNewChunks
* UNDOFILE_CHUNK_SIZE
- pos
.nPos
)) {
2625 FILE *file
= OpenUndoFile(pos
);
2627 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks
* UNDOFILE_CHUNK_SIZE
, pos
.nFile
);
2628 AllocateFileRange(file
, pos
.nPos
, nNewChunks
* UNDOFILE_CHUNK_SIZE
- pos
.nPos
);
2633 return state
.Error("out of disk space");
2639 static bool CheckBlockHeader(const CBlockHeader
& block
, CValidationState
& state
, const Consensus::Params
& consensusParams
, bool fCheckPOW
= true)
2641 // Check proof of work matches claimed amount
2642 if (fCheckPOW
&& !CheckProofOfWork(block
.GetHash(), block
.nBits
, consensusParams
))
2643 return state
.DoS(50, false, REJECT_INVALID
, "high-hash", false, "proof of work failed");
2648 bool CheckBlock(const CBlock
& block
, CValidationState
& state
, const Consensus::Params
& consensusParams
, bool fCheckPOW
, bool fCheckMerkleRoot
)
2650 // These are checks that are independent of context.
2655 // Check that the header is valid (particularly PoW). This is mostly
2656 // redundant with the call in AcceptBlockHeader.
2657 if (!CheckBlockHeader(block
, state
, consensusParams
, fCheckPOW
))
2660 // Check the merkle root.
2661 if (fCheckMerkleRoot
) {
2663 uint256 hashMerkleRoot2
= BlockMerkleRoot(block
, &mutated
);
2664 if (block
.hashMerkleRoot
!= hashMerkleRoot2
)
2665 return state
.DoS(100, false, REJECT_INVALID
, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2667 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2668 // of transactions in a block without affecting the merkle root of a block,
2669 // while still invalidating it.
2671 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-duplicate", true, "duplicate transaction");
2674 // All potential-corruption validation must be done before we do any
2675 // transaction validation, as otherwise we may mark the header as invalid
2676 // because we receive the wrong transactions for it.
2677 // Note that witness malleability is checked in ContextualCheckBlock, so no
2678 // checks that use witness data may be performed here.
2681 if (block
.vtx
.empty() || block
.vtx
.size() > MAX_BLOCK_BASE_SIZE
|| ::GetSerializeSize(block
, SER_NETWORK
, PROTOCOL_VERSION
| SERIALIZE_TRANSACTION_NO_WITNESS
) > MAX_BLOCK_BASE_SIZE
)
2682 return state
.DoS(100, false, REJECT_INVALID
, "bad-blk-length", false, "size limits failed");
2684 // First transaction must be coinbase, the rest must not be
2685 if (block
.vtx
.empty() || !block
.vtx
[0]->IsCoinBase())
2686 return state
.DoS(100, false, REJECT_INVALID
, "bad-cb-missing", false, "first tx is not coinbase");
2687 for (unsigned int i
= 1; i
< block
.vtx
.size(); i
++)
2688 if (block
.vtx
[i
]->IsCoinBase())
2689 return state
.DoS(100, false, REJECT_INVALID
, "bad-cb-multiple", false, "more than one coinbase");
2691 // Check transactions
2692 for (const auto& tx
: block
.vtx
)
2693 if (!CheckTransaction(*tx
, state
, false))
2694 return state
.Invalid(false, state
.GetRejectCode(), state
.GetRejectReason(),
2695 strprintf("Transaction check failed (tx hash %s) %s", tx
->GetHash().ToString(), state
.GetDebugMessage()));
2697 unsigned int nSigOps
= 0;
2698 for (const auto& tx
: block
.vtx
)
2700 nSigOps
+= GetLegacySigOpCount(*tx
);
2702 if (nSigOps
* WITNESS_SCALE_FACTOR
> MAX_BLOCK_SIGOPS_COST
)
2703 return state
.DoS(100, false, REJECT_INVALID
, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2705 if (fCheckPOW
&& fCheckMerkleRoot
)
2706 block
.fChecked
= true;
2711 static bool CheckIndexAgainstCheckpoint(const CBlockIndex
* pindexPrev
, CValidationState
& state
, const CChainParams
& chainparams
, const uint256
& hash
)
2713 if (*pindexPrev
->phashBlock
== chainparams
.GetConsensus().hashGenesisBlock
)
2716 int nHeight
= pindexPrev
->nHeight
+1;
2717 // Don't accept any forks from the main chain prior to last checkpoint.
2718 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
2720 CBlockIndex
* pcheckpoint
= Checkpoints::GetLastCheckpoint(chainparams
.Checkpoints());
2721 if (pcheckpoint
&& nHeight
< pcheckpoint
->nHeight
)
2722 return state
.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__
, nHeight
), REJECT_CHECKPOINT
, "bad-fork-prior-to-checkpoint");
2727 bool IsWitnessEnabled(const CBlockIndex
* pindexPrev
, const Consensus::Params
& params
)
2730 return (VersionBitsState(pindexPrev
, params
, Consensus::DEPLOYMENT_SEGWIT
, versionbitscache
) == THRESHOLD_ACTIVE
);
2733 // Compute at which vout of the block's coinbase transaction the witness
2734 // commitment occurs, or -1 if not found.
2735 static int GetWitnessCommitmentIndex(const CBlock
& block
)
2738 if (!block
.vtx
.empty()) {
2739 for (size_t o
= 0; o
< block
.vtx
[0]->vout
.size(); o
++) {
2740 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) {
2748 void UpdateUncommittedBlockStructures(CBlock
& block
, const CBlockIndex
* pindexPrev
, const Consensus::Params
& consensusParams
)
2750 int commitpos
= GetWitnessCommitmentIndex(block
);
2751 static const std::vector
<unsigned char> nonce(32, 0x00);
2752 if (commitpos
!= -1 && IsWitnessEnabled(pindexPrev
, consensusParams
) && !block
.vtx
[0]->HasWitness()) {
2753 CMutableTransaction
tx(*block
.vtx
[0]);
2754 tx
.vin
[0].scriptWitness
.stack
.resize(1);
2755 tx
.vin
[0].scriptWitness
.stack
[0] = nonce
;
2756 block
.vtx
[0] = MakeTransactionRef(std::move(tx
));
2760 std::vector
<unsigned char> GenerateCoinbaseCommitment(CBlock
& block
, const CBlockIndex
* pindexPrev
, const Consensus::Params
& consensusParams
)
2762 std::vector
<unsigned char> commitment
;
2763 int commitpos
= GetWitnessCommitmentIndex(block
);
2764 std::vector
<unsigned char> ret(32, 0x00);
2765 if (consensusParams
.vDeployments
[Consensus::DEPLOYMENT_SEGWIT
].nTimeout
!= 0) {
2766 if (commitpos
== -1) {
2767 uint256 witnessroot
= BlockWitnessMerkleRoot(block
, NULL
);
2768 CHash256().Write(witnessroot
.begin(), 32).Write(&ret
[0], 32).Finalize(witnessroot
.begin());
2771 out
.scriptPubKey
.resize(38);
2772 out
.scriptPubKey
[0] = OP_RETURN
;
2773 out
.scriptPubKey
[1] = 0x24;
2774 out
.scriptPubKey
[2] = 0xaa;
2775 out
.scriptPubKey
[3] = 0x21;
2776 out
.scriptPubKey
[4] = 0xa9;
2777 out
.scriptPubKey
[5] = 0xed;
2778 memcpy(&out
.scriptPubKey
[6], witnessroot
.begin(), 32);
2779 commitment
= std::vector
<unsigned char>(out
.scriptPubKey
.begin(), out
.scriptPubKey
.end());
2780 CMutableTransaction
tx(*block
.vtx
[0]);
2781 tx
.vout
.push_back(out
);
2782 block
.vtx
[0] = MakeTransactionRef(std::move(tx
));
2785 UpdateUncommittedBlockStructures(block
, pindexPrev
, consensusParams
);
2789 /** Context-dependent validity checks.
2790 * By "context", we mean only the previous block headers, but not the UTXO
2791 * set; UTXO-related validity checks are done in ConnectBlock(). */
2792 static bool ContextualCheckBlockHeader(const CBlockHeader
& block
, CValidationState
& state
, const Consensus::Params
& consensusParams
, const CBlockIndex
* pindexPrev
, int64_t nAdjustedTime
)
2794 assert(pindexPrev
!= NULL
);
2795 const int nHeight
= pindexPrev
->nHeight
+ 1;
2796 // Check proof of work
2797 if (block
.nBits
!= GetNextWorkRequired(pindexPrev
, &block
, consensusParams
))
2798 return state
.DoS(100, false, REJECT_INVALID
, "bad-diffbits", false, "incorrect proof of work");
2800 // Check timestamp against prev
2801 if (block
.GetBlockTime() <= pindexPrev
->GetMedianTimePast())
2802 return state
.Invalid(false, REJECT_INVALID
, "time-too-old", "block's timestamp is too early");
2805 if (block
.GetBlockTime() > nAdjustedTime
+ MAX_FUTURE_BLOCK_TIME
)
2806 return state
.Invalid(false, REJECT_INVALID
, "time-too-new", "block timestamp too far in the future");
2808 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2809 // check for version 2, 3 and 4 upgrades
2810 if((block
.nVersion
< 2 && nHeight
>= consensusParams
.BIP34Height
) ||
2811 (block
.nVersion
< 3 && nHeight
>= consensusParams
.BIP66Height
) ||
2812 (block
.nVersion
< 4 && nHeight
>= consensusParams
.BIP65Height
))
2813 return state
.Invalid(false, REJECT_OBSOLETE
, strprintf("bad-version(0x%08x)", block
.nVersion
),
2814 strprintf("rejected nVersion=0x%08x block", block
.nVersion
));
2819 static bool ContextualCheckBlock(const CBlock
& block
, CValidationState
& state
, const Consensus::Params
& consensusParams
, const CBlockIndex
* pindexPrev
)
2821 const int nHeight
= pindexPrev
== NULL
? 0 : pindexPrev
->nHeight
+ 1;
2823 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
2824 int nLockTimeFlags
= 0;
2825 if (VersionBitsState(pindexPrev
, consensusParams
, Consensus::DEPLOYMENT_CSV
, versionbitscache
) == THRESHOLD_ACTIVE
) {
2826 nLockTimeFlags
|= LOCKTIME_MEDIAN_TIME_PAST
;
2829 int64_t nLockTimeCutoff
= (nLockTimeFlags
& LOCKTIME_MEDIAN_TIME_PAST
)
2830 ? pindexPrev
->GetMedianTimePast()
2831 : block
.GetBlockTime();
2833 // Check that all transactions are finalized
2834 for (const auto& tx
: block
.vtx
) {
2835 if (!IsFinalTx(*tx
, nHeight
, nLockTimeCutoff
)) {
2836 return state
.DoS(10, false, REJECT_INVALID
, "bad-txns-nonfinal", false, "non-final transaction");
2840 // Enforce rule that the coinbase starts with serialized block height
2841 if (nHeight
>= consensusParams
.BIP34Height
)
2843 CScript expect
= CScript() << nHeight
;
2844 if (block
.vtx
[0]->vin
[0].scriptSig
.size() < expect
.size() ||
2845 !std::equal(expect
.begin(), expect
.end(), block
.vtx
[0]->vin
[0].scriptSig
.begin())) {
2846 return state
.DoS(100, false, REJECT_INVALID
, "bad-cb-height", false, "block height mismatch in coinbase");
2850 // Validation for witness commitments.
2851 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
2852 // coinbase (where 0x0000....0000 is used instead).
2853 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
2854 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
2855 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
2856 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
2857 // multiple, the last one is used.
2858 bool fHaveWitness
= false;
2859 if (VersionBitsState(pindexPrev
, consensusParams
, Consensus::DEPLOYMENT_SEGWIT
, versionbitscache
) == THRESHOLD_ACTIVE
) {
2860 int commitpos
= GetWitnessCommitmentIndex(block
);
2861 if (commitpos
!= -1) {
2862 bool malleated
= false;
2863 uint256 hashWitness
= BlockWitnessMerkleRoot(block
, &malleated
);
2864 // The malleation check is ignored; as the transaction tree itself
2865 // already does not permit it, it is impossible to trigger in the
2867 if (block
.vtx
[0]->vin
[0].scriptWitness
.stack
.size() != 1 || block
.vtx
[0]->vin
[0].scriptWitness
.stack
[0].size() != 32) {
2868 return state
.DoS(100, false, REJECT_INVALID
, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__
));
2870 CHash256().Write(hashWitness
.begin(), 32).Write(&block
.vtx
[0]->vin
[0].scriptWitness
.stack
[0][0], 32).Finalize(hashWitness
.begin());
2871 if (memcmp(hashWitness
.begin(), &block
.vtx
[0]->vout
[commitpos
].scriptPubKey
[6], 32)) {
2872 return state
.DoS(100, false, REJECT_INVALID
, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__
));
2874 fHaveWitness
= true;
2878 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
2879 if (!fHaveWitness
) {
2880 for (const auto& tx
: block
.vtx
) {
2881 if (tx
->HasWitness()) {
2882 return state
.DoS(100, false, REJECT_INVALID
, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__
));
2887 // After the coinbase witness nonce and commitment are verified,
2888 // we can check if the block weight passes (before we've checked the
2889 // coinbase witness, it would be possible for the weight to be too
2890 // large by filling up the coinbase witness, which doesn't change
2891 // the block hash, so we couldn't mark the block as permanently
2893 if (GetBlockWeight(block
) > MAX_BLOCK_WEIGHT
) {
2894 return state
.DoS(100, false, REJECT_INVALID
, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__
));
2900 static bool AcceptBlockHeader(const CBlockHeader
& block
, CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
** ppindex
)
2902 AssertLockHeld(cs_main
);
2903 // Check for duplicate
2904 uint256 hash
= block
.GetHash();
2905 BlockMap::iterator miSelf
= mapBlockIndex
.find(hash
);
2906 CBlockIndex
*pindex
= NULL
;
2907 if (hash
!= chainparams
.GetConsensus().hashGenesisBlock
) {
2909 if (miSelf
!= mapBlockIndex
.end()) {
2910 // Block header is already known.
2911 pindex
= miSelf
->second
;
2914 if (pindex
->nStatus
& BLOCK_FAILED_MASK
)
2915 return state
.Invalid(error("%s: block %s is marked invalid", __func__
, hash
.ToString()), 0, "duplicate");
2919 if (!CheckBlockHeader(block
, state
, chainparams
.GetConsensus()))
2920 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__
, hash
.ToString(), FormatStateMessage(state
));
2922 // Get prev block index
2923 CBlockIndex
* pindexPrev
= NULL
;
2924 BlockMap::iterator mi
= mapBlockIndex
.find(block
.hashPrevBlock
);
2925 if (mi
== mapBlockIndex
.end())
2926 return state
.DoS(10, error("%s: prev block not found", __func__
), 0, "prev-blk-not-found");
2927 pindexPrev
= (*mi
).second
;
2928 if (pindexPrev
->nStatus
& BLOCK_FAILED_MASK
)
2929 return state
.DoS(100, error("%s: prev block invalid", __func__
), REJECT_INVALID
, "bad-prevblk");
2932 if (fCheckpointsEnabled
&& !CheckIndexAgainstCheckpoint(pindexPrev
, state
, chainparams
, hash
))
2933 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__
, state
.GetRejectReason().c_str());
2935 if (!ContextualCheckBlockHeader(block
, state
, chainparams
.GetConsensus(), pindexPrev
, GetAdjustedTime()))
2936 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__
, hash
.ToString(), FormatStateMessage(state
));
2939 pindex
= AddToBlockIndex(block
);
2944 CheckBlockIndex(chainparams
.GetConsensus());
2949 // Exposed wrapper for AcceptBlockHeader
2950 bool ProcessNewBlockHeaders(const std::vector
<CBlockHeader
>& headers
, CValidationState
& state
, const CChainParams
& chainparams
, const CBlockIndex
** ppindex
)
2954 for (const CBlockHeader
& header
: headers
) {
2955 CBlockIndex
*pindex
= NULL
; // Use a temp pindex instead of ppindex to avoid a const_cast
2956 if (!AcceptBlockHeader(header
, state
, chainparams
, &pindex
)) {
2968 /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
2969 static bool AcceptBlock(const std::shared_ptr
<const CBlock
>& pblock
, CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
** ppindex
, bool fRequested
, const CDiskBlockPos
* dbp
, bool* fNewBlock
)
2971 const CBlock
& block
= *pblock
;
2973 if (fNewBlock
) *fNewBlock
= false;
2974 AssertLockHeld(cs_main
);
2976 CBlockIndex
*pindexDummy
= NULL
;
2977 CBlockIndex
*&pindex
= ppindex
? *ppindex
: pindexDummy
;
2979 if (!AcceptBlockHeader(block
, state
, chainparams
, &pindex
))
2982 // Try to process all requested blocks that we don't have, but only
2983 // process an unrequested block if it's new and has enough work to
2984 // advance our tip, and isn't too many blocks ahead.
2985 bool fAlreadyHave
= pindex
->nStatus
& BLOCK_HAVE_DATA
;
2986 bool fHasMoreWork
= (chainActive
.Tip() ? pindex
->nChainWork
> chainActive
.Tip()->nChainWork
: true);
2987 // Blocks that are too out-of-order needlessly limit the effectiveness of
2988 // pruning, because pruning will not delete block files that contain any
2989 // blocks which are too close in height to the tip. Apply this test
2990 // regardless of whether pruning is enabled; it should generally be safe to
2991 // not process unrequested blocks.
2992 bool fTooFarAhead
= (pindex
->nHeight
> int(chainActive
.Height() + MIN_BLOCKS_TO_KEEP
));
2994 // TODO: Decouple this function from the block download logic by removing fRequested
2995 // This requires some new chain data structure to efficiently look up if a
2996 // block is in a chain leading to a candidate for best tip, despite not
2997 // being such a candidate itself.
2999 // TODO: deal better with return value and error conditions for duplicate
3000 // and unrequested blocks.
3001 if (fAlreadyHave
) return true;
3002 if (!fRequested
) { // If we didn't ask for it:
3003 if (pindex
->nTx
!= 0) return true; // This is a previously-processed block that was pruned
3004 if (!fHasMoreWork
) return true; // Don't process less-work chains
3005 if (fTooFarAhead
) return true; // Block height is too high
3007 if (fNewBlock
) *fNewBlock
= true;
3009 if (!CheckBlock(block
, state
, chainparams
.GetConsensus()) ||
3010 !ContextualCheckBlock(block
, state
, chainparams
.GetConsensus(), pindex
->pprev
)) {
3011 if (state
.IsInvalid() && !state
.CorruptionPossible()) {
3012 pindex
->nStatus
|= BLOCK_FAILED_VALID
;
3013 setDirtyBlockIndex
.insert(pindex
);
3015 return error("%s: %s", __func__
, FormatStateMessage(state
));
3018 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3019 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3020 if (!IsInitialBlockDownload() && chainActive
.Tip() == pindex
->pprev
)
3021 GetMainSignals().NewPoWValidBlock(pindex
, pblock
);
3023 int nHeight
= pindex
->nHeight
;
3025 // Write block to history file
3027 unsigned int nBlockSize
= ::GetSerializeSize(block
, SER_DISK
, CLIENT_VERSION
);
3028 CDiskBlockPos blockPos
;
3031 if (!FindBlockPos(state
, blockPos
, nBlockSize
+8, nHeight
, block
.GetBlockTime(), dbp
!= NULL
))
3032 return error("AcceptBlock(): FindBlockPos failed");
3034 if (!WriteBlockToDisk(block
, blockPos
, chainparams
.MessageStart()))
3035 AbortNode(state
, "Failed to write block");
3036 if (!ReceivedBlockTransactions(block
, state
, pindex
, blockPos
, chainparams
.GetConsensus()))
3037 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3038 } catch (const std::runtime_error
& e
) {
3039 return AbortNode(state
, std::string("System error: ") + e
.what());
3042 if (fCheckForPruning
)
3043 FlushStateToDisk(chainparams
, state
, FLUSH_STATE_NONE
); // we just allocated more disk space for block files
3048 bool ProcessNewBlock(const CChainParams
& chainparams
, const std::shared_ptr
<const CBlock
> pblock
, bool fForceProcessing
, bool *fNewBlock
)
3051 CBlockIndex
*pindex
= NULL
;
3052 if (fNewBlock
) *fNewBlock
= false;
3053 CValidationState state
;
3054 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3055 // belt-and-suspenders.
3056 bool ret
= CheckBlock(*pblock
, state
, chainparams
.GetConsensus());
3062 ret
= AcceptBlock(pblock
, state
, chainparams
, &pindex
, fForceProcessing
, NULL
, fNewBlock
);
3064 CheckBlockIndex(chainparams
.GetConsensus());
3066 GetMainSignals().BlockChecked(*pblock
, state
);
3067 return error("%s: AcceptBlock FAILED", __func__
);
3073 CValidationState state
; // Only used to report errors, not invalidity - ignore it
3074 if (!ActivateBestChain(state
, chainparams
, pblock
))
3075 return error("%s: ActivateBestChain failed", __func__
);
3080 bool TestBlockValidity(CValidationState
& state
, const CChainParams
& chainparams
, const CBlock
& block
, CBlockIndex
* pindexPrev
, bool fCheckPOW
, bool fCheckMerkleRoot
)
3082 AssertLockHeld(cs_main
);
3083 assert(pindexPrev
&& pindexPrev
== chainActive
.Tip());
3084 if (fCheckpointsEnabled
&& !CheckIndexAgainstCheckpoint(pindexPrev
, state
, chainparams
, block
.GetHash()))
3085 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__
, state
.GetRejectReason().c_str());
3087 CCoinsViewCache
viewNew(pcoinsTip
);
3088 CBlockIndex
indexDummy(block
);
3089 indexDummy
.pprev
= pindexPrev
;
3090 indexDummy
.nHeight
= pindexPrev
->nHeight
+ 1;
3092 // NOTE: CheckBlockHeader is called by CheckBlock
3093 if (!ContextualCheckBlockHeader(block
, state
, chainparams
.GetConsensus(), pindexPrev
, GetAdjustedTime()))
3094 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__
, FormatStateMessage(state
));
3095 if (!CheckBlock(block
, state
, chainparams
.GetConsensus(), fCheckPOW
, fCheckMerkleRoot
))
3096 return error("%s: Consensus::CheckBlock: %s", __func__
, FormatStateMessage(state
));
3097 if (!ContextualCheckBlock(block
, state
, chainparams
.GetConsensus(), pindexPrev
))
3098 return error("%s: Consensus::ContextualCheckBlock: %s", __func__
, FormatStateMessage(state
));
3099 if (!ConnectBlock(block
, state
, &indexDummy
, viewNew
, chainparams
, true))
3101 assert(state
.IsValid());
3107 * BLOCK PRUNING CODE
3110 /* Calculate the amount of disk space the block & undo files currently use */
3111 static uint64_t CalculateCurrentUsage()
3113 uint64_t retval
= 0;
3114 for (const CBlockFileInfo
&file
: vinfoBlockFile
) {
3115 retval
+= file
.nSize
+ file
.nUndoSize
;
3120 /* Prune a block file (modify associated database entries)*/
3121 void PruneOneBlockFile(const int fileNumber
)
3123 for (BlockMap::iterator it
= mapBlockIndex
.begin(); it
!= mapBlockIndex
.end(); ++it
) {
3124 CBlockIndex
* pindex
= it
->second
;
3125 if (pindex
->nFile
== fileNumber
) {
3126 pindex
->nStatus
&= ~BLOCK_HAVE_DATA
;
3127 pindex
->nStatus
&= ~BLOCK_HAVE_UNDO
;
3129 pindex
->nDataPos
= 0;
3130 pindex
->nUndoPos
= 0;
3131 setDirtyBlockIndex
.insert(pindex
);
3133 // Prune from mapBlocksUnlinked -- any block we prune would have
3134 // to be downloaded again in order to consider its chain, at which
3135 // point it would be considered as a candidate for
3136 // mapBlocksUnlinked or setBlockIndexCandidates.
3137 std::pair
<std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
, std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
> range
= mapBlocksUnlinked
.equal_range(pindex
->pprev
);
3138 while (range
.first
!= range
.second
) {
3139 std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator _it
= range
.first
;
3141 if (_it
->second
== pindex
) {
3142 mapBlocksUnlinked
.erase(_it
);
3148 vinfoBlockFile
[fileNumber
].SetNull();
3149 setDirtyFileInfo
.insert(fileNumber
);
3153 void UnlinkPrunedFiles(const std::set
<int>& setFilesToPrune
)
3155 for (std::set
<int>::iterator it
= setFilesToPrune
.begin(); it
!= setFilesToPrune
.end(); ++it
) {
3156 CDiskBlockPos
pos(*it
, 0);
3157 fs::remove(GetBlockPosFilename(pos
, "blk"));
3158 fs::remove(GetBlockPosFilename(pos
, "rev"));
3159 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__
, *it
);
3163 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3164 static void FindFilesToPruneManual(std::set
<int>& setFilesToPrune
, int nManualPruneHeight
)
3166 assert(fPruneMode
&& nManualPruneHeight
> 0);
3168 LOCK2(cs_main
, cs_LastBlockFile
);
3169 if (chainActive
.Tip() == NULL
)
3172 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3173 unsigned int nLastBlockWeCanPrune
= std::min((unsigned)nManualPruneHeight
, chainActive
.Tip()->nHeight
- MIN_BLOCKS_TO_KEEP
);
3175 for (int fileNumber
= 0; fileNumber
< nLastBlockFile
; fileNumber
++) {
3176 if (vinfoBlockFile
[fileNumber
].nSize
== 0 || vinfoBlockFile
[fileNumber
].nHeightLast
> nLastBlockWeCanPrune
)
3178 PruneOneBlockFile(fileNumber
);
3179 setFilesToPrune
.insert(fileNumber
);
3182 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune
, count
);
3185 /* This function is called from the RPC code for pruneblockchain */
3186 void PruneBlockFilesManual(int nManualPruneHeight
)
3188 CValidationState state
;
3189 const CChainParams
& chainparams
= Params();
3190 FlushStateToDisk(chainparams
, state
, FLUSH_STATE_NONE
, nManualPruneHeight
);
3194 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
3195 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
3196 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
3197 * (which in this case means the blockchain must be re-downloaded.)
3199 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
3200 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
3201 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
3202 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
3203 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
3204 * A db flag records the fact that at least some block files have been pruned.
3206 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
3208 static void FindFilesToPrune(std::set
<int>& setFilesToPrune
, uint64_t nPruneAfterHeight
)
3210 LOCK2(cs_main
, cs_LastBlockFile
);
3211 if (chainActive
.Tip() == NULL
|| nPruneTarget
== 0) {
3214 if ((uint64_t)chainActive
.Tip()->nHeight
<= nPruneAfterHeight
) {
3218 unsigned int nLastBlockWeCanPrune
= chainActive
.Tip()->nHeight
- MIN_BLOCKS_TO_KEEP
;
3219 uint64_t nCurrentUsage
= CalculateCurrentUsage();
3220 // We don't check to prune until after we've allocated new space for files
3221 // So we should leave a buffer under our target to account for another allocation
3222 // before the next pruning.
3223 uint64_t nBuffer
= BLOCKFILE_CHUNK_SIZE
+ UNDOFILE_CHUNK_SIZE
;
3224 uint64_t nBytesToPrune
;
3227 if (nCurrentUsage
+ nBuffer
>= nPruneTarget
) {
3228 for (int fileNumber
= 0; fileNumber
< nLastBlockFile
; fileNumber
++) {
3229 nBytesToPrune
= vinfoBlockFile
[fileNumber
].nSize
+ vinfoBlockFile
[fileNumber
].nUndoSize
;
3231 if (vinfoBlockFile
[fileNumber
].nSize
== 0)
3234 if (nCurrentUsage
+ nBuffer
< nPruneTarget
) // are we below our target?
3237 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3238 if (vinfoBlockFile
[fileNumber
].nHeightLast
> nLastBlockWeCanPrune
)
3241 PruneOneBlockFile(fileNumber
);
3242 // Queue up the files for removal
3243 setFilesToPrune
.insert(fileNumber
);
3244 nCurrentUsage
-= nBytesToPrune
;
3249 LogPrint(BCLog::PRUNE
, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3250 nPruneTarget
/1024/1024, nCurrentUsage
/1024/1024,
3251 ((int64_t)nPruneTarget
- (int64_t)nCurrentUsage
)/1024/1024,
3252 nLastBlockWeCanPrune
, count
);
3255 bool CheckDiskSpace(uint64_t nAdditionalBytes
)
3257 uint64_t nFreeBytesAvailable
= fs::space(GetDataDir()).available
;
3259 // Check for nMinDiskSpace bytes (currently 50MB)
3260 if (nFreeBytesAvailable
< nMinDiskSpace
+ nAdditionalBytes
)
3261 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3266 static FILE* OpenDiskFile(const CDiskBlockPos
&pos
, const char *prefix
, bool fReadOnly
)
3270 fs::path path
= GetBlockPosFilename(pos
, prefix
);
3271 fs::create_directories(path
.parent_path());
3272 FILE* file
= fsbridge::fopen(path
, "rb+");
3273 if (!file
&& !fReadOnly
)
3274 file
= fsbridge::fopen(path
, "wb+");
3276 LogPrintf("Unable to open file %s\n", path
.string());
3280 if (fseek(file
, pos
.nPos
, SEEK_SET
)) {
3281 LogPrintf("Unable to seek to position %u of %s\n", pos
.nPos
, path
.string());
3289 FILE* OpenBlockFile(const CDiskBlockPos
&pos
, bool fReadOnly
) {
3290 return OpenDiskFile(pos
, "blk", fReadOnly
);
3293 /** Open an undo file (rev?????.dat) */
3294 static FILE* OpenUndoFile(const CDiskBlockPos
&pos
, bool fReadOnly
) {
3295 return OpenDiskFile(pos
, "rev", fReadOnly
);
3298 fs::path
GetBlockPosFilename(const CDiskBlockPos
&pos
, const char *prefix
)
3300 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix
, pos
.nFile
);
3303 CBlockIndex
* InsertBlockIndex(uint256 hash
)
3309 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
3310 if (mi
!= mapBlockIndex
.end())
3311 return (*mi
).second
;
3314 CBlockIndex
* pindexNew
= new CBlockIndex();
3316 throw std::runtime_error(std::string(__func__
) + ": new CBlockIndex failed");
3317 mi
= mapBlockIndex
.insert(std::make_pair(hash
, pindexNew
)).first
;
3318 pindexNew
->phashBlock
= &((*mi
).first
);
3323 bool static LoadBlockIndexDB(const CChainParams
& chainparams
)
3325 if (!pblocktree
->LoadBlockIndexGuts(InsertBlockIndex
))
3328 boost::this_thread::interruption_point();
3330 // Calculate nChainWork
3331 std::vector
<std::pair
<int, CBlockIndex
*> > vSortedByHeight
;
3332 vSortedByHeight
.reserve(mapBlockIndex
.size());
3333 for (const std::pair
<uint256
, CBlockIndex
*>& item
: mapBlockIndex
)
3335 CBlockIndex
* pindex
= item
.second
;
3336 vSortedByHeight
.push_back(std::make_pair(pindex
->nHeight
, pindex
));
3338 sort(vSortedByHeight
.begin(), vSortedByHeight
.end());
3339 for (const std::pair
<int, CBlockIndex
*>& item
: vSortedByHeight
)
3341 CBlockIndex
* pindex
= item
.second
;
3342 pindex
->nChainWork
= (pindex
->pprev
? pindex
->pprev
->nChainWork
: 0) + GetBlockProof(*pindex
);
3343 pindex
->nTimeMax
= (pindex
->pprev
? std::max(pindex
->pprev
->nTimeMax
, pindex
->nTime
) : pindex
->nTime
);
3344 // We can link the chain of blocks for which we've received transactions at some point.
3345 // Pruned nodes may have deleted the block.
3346 if (pindex
->nTx
> 0) {
3347 if (pindex
->pprev
) {
3348 if (pindex
->pprev
->nChainTx
) {
3349 pindex
->nChainTx
= pindex
->pprev
->nChainTx
+ pindex
->nTx
;
3351 pindex
->nChainTx
= 0;
3352 mapBlocksUnlinked
.insert(std::make_pair(pindex
->pprev
, pindex
));
3355 pindex
->nChainTx
= pindex
->nTx
;
3358 if (pindex
->IsValid(BLOCK_VALID_TRANSACTIONS
) && (pindex
->nChainTx
|| pindex
->pprev
== NULL
))
3359 setBlockIndexCandidates
.insert(pindex
);
3360 if (pindex
->nStatus
& BLOCK_FAILED_MASK
&& (!pindexBestInvalid
|| pindex
->nChainWork
> pindexBestInvalid
->nChainWork
))
3361 pindexBestInvalid
= pindex
;
3363 pindex
->BuildSkip();
3364 if (pindex
->IsValid(BLOCK_VALID_TREE
) && (pindexBestHeader
== NULL
|| CBlockIndexWorkComparator()(pindexBestHeader
, pindex
)))
3365 pindexBestHeader
= pindex
;
3368 // Load block file info
3369 pblocktree
->ReadLastBlockFile(nLastBlockFile
);
3370 vinfoBlockFile
.resize(nLastBlockFile
+ 1);
3371 LogPrintf("%s: last block file = %i\n", __func__
, nLastBlockFile
);
3372 for (int nFile
= 0; nFile
<= nLastBlockFile
; nFile
++) {
3373 pblocktree
->ReadBlockFileInfo(nFile
, vinfoBlockFile
[nFile
]);
3375 LogPrintf("%s: last block file info: %s\n", __func__
, vinfoBlockFile
[nLastBlockFile
].ToString());
3376 for (int nFile
= nLastBlockFile
+ 1; true; nFile
++) {
3377 CBlockFileInfo info
;
3378 if (pblocktree
->ReadBlockFileInfo(nFile
, info
)) {
3379 vinfoBlockFile
.push_back(info
);
3385 // Check presence of blk files
3386 LogPrintf("Checking all blk files are present...\n");
3387 std::set
<int> setBlkDataFiles
;
3388 for (const std::pair
<uint256
, CBlockIndex
*>& item
: mapBlockIndex
)
3390 CBlockIndex
* pindex
= item
.second
;
3391 if (pindex
->nStatus
& BLOCK_HAVE_DATA
) {
3392 setBlkDataFiles
.insert(pindex
->nFile
);
3395 for (std::set
<int>::iterator it
= setBlkDataFiles
.begin(); it
!= setBlkDataFiles
.end(); it
++)
3397 CDiskBlockPos
pos(*it
, 0);
3398 if (CAutoFile(OpenBlockFile(pos
, true), SER_DISK
, CLIENT_VERSION
).IsNull()) {
3403 // Check whether we have ever pruned block & undo files
3404 pblocktree
->ReadFlag("prunedblockfiles", fHavePruned
);
3406 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3408 // Check whether we need to continue reindexing
3409 bool fReindexing
= false;
3410 pblocktree
->ReadReindexing(fReindexing
);
3411 fReindex
|= fReindexing
;
3413 // Check whether we have a transaction index
3414 pblocktree
->ReadFlag("txindex", fTxIndex
);
3415 LogPrintf("%s: transaction index %s\n", __func__
, fTxIndex
? "enabled" : "disabled");
3417 // Load pointer to end of best chain
3418 BlockMap::iterator it
= mapBlockIndex
.find(pcoinsTip
->GetBestBlock());
3419 if (it
== mapBlockIndex
.end())
3421 chainActive
.SetTip(it
->second
);
3423 PruneBlockIndexCandidates();
3425 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__
,
3426 chainActive
.Tip()->GetBlockHash().ToString(), chainActive
.Height(),
3427 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive
.Tip()->GetBlockTime()),
3428 GuessVerificationProgress(chainparams
.TxData(), chainActive
.Tip()));
3433 CVerifyDB::CVerifyDB()
3435 uiInterface
.ShowProgress(_("Verifying blocks..."), 0);
3438 CVerifyDB::~CVerifyDB()
3440 uiInterface
.ShowProgress("", 100);
3443 bool CVerifyDB::VerifyDB(const CChainParams
& chainparams
, CCoinsView
*coinsview
, int nCheckLevel
, int nCheckDepth
)
3446 if (chainActive
.Tip() == NULL
|| chainActive
.Tip()->pprev
== NULL
)
3449 // Verify blocks in the best chain
3450 if (nCheckDepth
<= 0)
3451 nCheckDepth
= 1000000000; // suffices until the year 19000
3452 if (nCheckDepth
> chainActive
.Height())
3453 nCheckDepth
= chainActive
.Height();
3454 nCheckLevel
= std::max(0, std::min(4, nCheckLevel
));
3455 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth
, nCheckLevel
);
3456 CCoinsViewCache
coins(coinsview
);
3457 CBlockIndex
* pindexState
= chainActive
.Tip();
3458 CBlockIndex
* pindexFailure
= NULL
;
3459 int nGoodTransactions
= 0;
3460 CValidationState state
;
3462 LogPrintf("[0%%]...");
3463 for (CBlockIndex
* pindex
= chainActive
.Tip(); pindex
&& pindex
->pprev
; pindex
= pindex
->pprev
)
3465 boost::this_thread::interruption_point();
3466 int percentageDone
= std::max(1, std::min(99, (int)(((double)(chainActive
.Height() - pindex
->nHeight
)) / (double)nCheckDepth
* (nCheckLevel
>= 4 ? 50 : 100))));
3467 if (reportDone
< percentageDone
/10) {
3468 // report every 10% step
3469 LogPrintf("[%d%%]...", percentageDone
);
3470 reportDone
= percentageDone
/10;
3472 uiInterface
.ShowProgress(_("Verifying blocks..."), percentageDone
);
3473 if (pindex
->nHeight
< chainActive
.Height()-nCheckDepth
)
3475 if (fPruneMode
&& !(pindex
->nStatus
& BLOCK_HAVE_DATA
)) {
3476 // If pruning, only go back as far as we have data.
3477 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex
->nHeight
);
3481 // check level 0: read from disk
3482 if (!ReadBlockFromDisk(block
, pindex
, chainparams
.GetConsensus()))
3483 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
3484 // check level 1: verify block validity
3485 if (nCheckLevel
>= 1 && !CheckBlock(block
, state
, chainparams
.GetConsensus()))
3486 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__
,
3487 pindex
->nHeight
, pindex
->GetBlockHash().ToString(), FormatStateMessage(state
));
3488 // check level 2: verify undo validity
3489 if (nCheckLevel
>= 2 && pindex
) {
3491 CDiskBlockPos pos
= pindex
->GetUndoPos();
3492 if (!pos
.IsNull()) {
3493 if (!UndoReadFromDisk(undo
, pos
, pindex
->pprev
->GetBlockHash()))
3494 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
3497 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3498 if (nCheckLevel
>= 3 && pindex
== pindexState
&& (coins
.DynamicMemoryUsage() + pcoinsTip
->DynamicMemoryUsage()) <= nCoinCacheUsage
) {
3499 DisconnectResult res
= DisconnectBlock(block
, pindex
, coins
);
3500 if (res
== DISCONNECT_FAILED
) {
3501 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
3503 pindexState
= pindex
->pprev
;
3504 if (res
== DISCONNECT_UNCLEAN
) {
3505 nGoodTransactions
= 0;
3506 pindexFailure
= pindex
;
3508 nGoodTransactions
+= block
.vtx
.size();
3511 if (ShutdownRequested())
3515 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive
.Height() - pindexFailure
->nHeight
+ 1, nGoodTransactions
);
3517 // check level 4: try reconnecting blocks
3518 if (nCheckLevel
>= 4) {
3519 CBlockIndex
*pindex
= pindexState
;
3520 while (pindex
!= chainActive
.Tip()) {
3521 boost::this_thread::interruption_point();
3522 uiInterface
.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive
.Height() - pindex
->nHeight
)) / (double)nCheckDepth
* 50))));
3523 pindex
= chainActive
.Next(pindex
);
3525 if (!ReadBlockFromDisk(block
, pindex
, chainparams
.GetConsensus()))
3526 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
3527 if (!ConnectBlock(block
, state
, pindex
, coins
, chainparams
))
3528 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
3532 LogPrintf("[DONE].\n");
3533 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive
.Height() - pindexState
->nHeight
, nGoodTransactions
);
3538 bool RewindBlockIndex(const CChainParams
& params
)
3543 while (nHeight
<= chainActive
.Height()) {
3544 if (IsWitnessEnabled(chainActive
[nHeight
- 1], params
.GetConsensus()) && !(chainActive
[nHeight
]->nStatus
& BLOCK_OPT_WITNESS
)) {
3550 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3551 CValidationState state
;
3552 CBlockIndex
* pindex
= chainActive
.Tip();
3553 while (chainActive
.Height() >= nHeight
) {
3554 if (fPruneMode
&& !(chainActive
.Tip()->nStatus
& BLOCK_HAVE_DATA
)) {
3555 // If pruning, don't try rewinding past the HAVE_DATA point;
3556 // since older blocks can't be served anyway, there's
3557 // no need to walk further, and trying to DisconnectTip()
3558 // will fail (and require a needless reindex/redownload
3559 // of the blockchain).
3562 if (!DisconnectTip(state
, params
, NULL
)) {
3563 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex
->nHeight
);
3565 // Occasionally flush state to disk.
3566 if (!FlushStateToDisk(params
, state
, FLUSH_STATE_PERIODIC
))
3570 // Reduce validity flag and have-data flags.
3571 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3572 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3573 for (BlockMap::iterator it
= mapBlockIndex
.begin(); it
!= mapBlockIndex
.end(); it
++) {
3574 CBlockIndex
* pindexIter
= it
->second
;
3576 // Note: If we encounter an insufficiently validated block that
3577 // is on chainActive, it must be because we are a pruning node, and
3578 // this block or some successor doesn't HAVE_DATA, so we were unable to
3579 // rewind all the way. Blocks remaining on chainActive at this point
3580 // must not have their validity reduced.
3581 if (IsWitnessEnabled(pindexIter
->pprev
, params
.GetConsensus()) && !(pindexIter
->nStatus
& BLOCK_OPT_WITNESS
) && !chainActive
.Contains(pindexIter
)) {
3583 pindexIter
->nStatus
= std::min
<unsigned int>(pindexIter
->nStatus
& BLOCK_VALID_MASK
, BLOCK_VALID_TREE
) | (pindexIter
->nStatus
& ~BLOCK_VALID_MASK
);
3584 // Remove have-data flags.
3585 pindexIter
->nStatus
&= ~(BLOCK_HAVE_DATA
| BLOCK_HAVE_UNDO
);
3586 // Remove storage location.
3587 pindexIter
->nFile
= 0;
3588 pindexIter
->nDataPos
= 0;
3589 pindexIter
->nUndoPos
= 0;
3590 // Remove various other things
3591 pindexIter
->nTx
= 0;
3592 pindexIter
->nChainTx
= 0;
3593 pindexIter
->nSequenceId
= 0;
3594 // Make sure it gets written.
3595 setDirtyBlockIndex
.insert(pindexIter
);
3597 setBlockIndexCandidates
.erase(pindexIter
);
3598 std::pair
<std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
, std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
> ret
= mapBlocksUnlinked
.equal_range(pindexIter
->pprev
);
3599 while (ret
.first
!= ret
.second
) {
3600 if (ret
.first
->second
== pindexIter
) {
3601 mapBlocksUnlinked
.erase(ret
.first
++);
3606 } else if (pindexIter
->IsValid(BLOCK_VALID_TRANSACTIONS
) && pindexIter
->nChainTx
) {
3607 setBlockIndexCandidates
.insert(pindexIter
);
3611 PruneBlockIndexCandidates();
3613 CheckBlockIndex(params
.GetConsensus());
3615 if (!FlushStateToDisk(params
, state
, FLUSH_STATE_ALWAYS
)) {
3622 // May NOT be used after any connections are up as much
3623 // of the peer-processing logic assumes a consistent
3624 // block index state
3625 void UnloadBlockIndex()
3628 setBlockIndexCandidates
.clear();
3629 chainActive
.SetTip(NULL
);
3630 pindexBestInvalid
= NULL
;
3631 pindexBestHeader
= NULL
;
3633 mapBlocksUnlinked
.clear();
3634 vinfoBlockFile
.clear();
3636 nBlockSequenceId
= 1;
3637 setDirtyBlockIndex
.clear();
3638 setDirtyFileInfo
.clear();
3639 versionbitscache
.Clear();
3640 for (int b
= 0; b
< VERSIONBITS_NUM_BITS
; b
++) {
3641 warningcache
[b
].clear();
3644 for (BlockMap::value_type
& entry
: mapBlockIndex
) {
3645 delete entry
.second
;
3647 mapBlockIndex
.clear();
3648 fHavePruned
= false;
3651 bool LoadBlockIndex(const CChainParams
& chainparams
)
3653 // Load block index from databases
3654 if (!fReindex
&& !LoadBlockIndexDB(chainparams
))
3659 bool InitBlockIndex(const CChainParams
& chainparams
)
3663 // Check whether we're already initialized
3664 if (chainActive
.Genesis() != NULL
)
3667 // Use the provided setting for -txindex in the new database
3668 fTxIndex
= GetBoolArg("-txindex", DEFAULT_TXINDEX
);
3669 pblocktree
->WriteFlag("txindex", fTxIndex
);
3670 LogPrintf("Initializing databases...\n");
3672 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3675 CBlock
&block
= const_cast<CBlock
&>(chainparams
.GenesisBlock());
3676 // Start new block file
3677 unsigned int nBlockSize
= ::GetSerializeSize(block
, SER_DISK
, CLIENT_VERSION
);
3678 CDiskBlockPos blockPos
;
3679 CValidationState state
;
3680 if (!FindBlockPos(state
, blockPos
, nBlockSize
+8, 0, block
.GetBlockTime()))
3681 return error("LoadBlockIndex(): FindBlockPos failed");
3682 if (!WriteBlockToDisk(block
, blockPos
, chainparams
.MessageStart()))
3683 return error("LoadBlockIndex(): writing genesis block to disk failed");
3684 CBlockIndex
*pindex
= AddToBlockIndex(block
);
3685 if (!ReceivedBlockTransactions(block
, state
, pindex
, blockPos
, chainparams
.GetConsensus()))
3686 return error("LoadBlockIndex(): genesis block not accepted");
3687 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3688 return FlushStateToDisk(chainparams
, state
, FLUSH_STATE_ALWAYS
);
3689 } catch (const std::runtime_error
& e
) {
3690 return error("LoadBlockIndex(): failed to initialize block database: %s", e
.what());
3697 bool LoadExternalBlockFile(const CChainParams
& chainparams
, FILE* fileIn
, CDiskBlockPos
*dbp
)
3699 // Map of disk positions for blocks with unknown parent (only used for reindex)
3700 static std::multimap
<uint256
, CDiskBlockPos
> mapBlocksUnknownParent
;
3701 int64_t nStart
= GetTimeMillis();
3705 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3706 CBufferedFile
blkdat(fileIn
, 2*MAX_BLOCK_SERIALIZED_SIZE
, MAX_BLOCK_SERIALIZED_SIZE
+8, SER_DISK
, CLIENT_VERSION
);
3707 uint64_t nRewind
= blkdat
.GetPos();
3708 while (!blkdat
.eof()) {
3709 boost::this_thread::interruption_point();
3711 blkdat
.SetPos(nRewind
);
3712 nRewind
++; // start one byte further next time, in case of failure
3713 blkdat
.SetLimit(); // remove former limit
3714 unsigned int nSize
= 0;
3717 unsigned char buf
[CMessageHeader::MESSAGE_START_SIZE
];
3718 blkdat
.FindByte(chainparams
.MessageStart()[0]);
3719 nRewind
= blkdat
.GetPos()+1;
3720 blkdat
>> FLATDATA(buf
);
3721 if (memcmp(buf
, chainparams
.MessageStart(), CMessageHeader::MESSAGE_START_SIZE
))
3725 if (nSize
< 80 || nSize
> MAX_BLOCK_SERIALIZED_SIZE
)
3727 } catch (const std::exception
&) {
3728 // no valid block header found; don't complain
3733 uint64_t nBlockPos
= blkdat
.GetPos();
3735 dbp
->nPos
= nBlockPos
;
3736 blkdat
.SetLimit(nBlockPos
+ nSize
);
3737 blkdat
.SetPos(nBlockPos
);
3738 std::shared_ptr
<CBlock
> pblock
= std::make_shared
<CBlock
>();
3739 CBlock
& block
= *pblock
;
3741 nRewind
= blkdat
.GetPos();
3743 // detect out of order blocks, and store them for later
3744 uint256 hash
= block
.GetHash();
3745 if (hash
!= chainparams
.GetConsensus().hashGenesisBlock
&& mapBlockIndex
.find(block
.hashPrevBlock
) == mapBlockIndex
.end()) {
3746 LogPrint(BCLog::REINDEX
, "%s: Out of order block %s, parent %s not known\n", __func__
, hash
.ToString(),
3747 block
.hashPrevBlock
.ToString());
3749 mapBlocksUnknownParent
.insert(std::make_pair(block
.hashPrevBlock
, *dbp
));
3753 // process in case the block isn't known yet
3754 if (mapBlockIndex
.count(hash
) == 0 || (mapBlockIndex
[hash
]->nStatus
& BLOCK_HAVE_DATA
) == 0) {
3756 CValidationState state
;
3757 if (AcceptBlock(pblock
, state
, chainparams
, NULL
, true, dbp
, NULL
))
3759 if (state
.IsError())
3761 } else if (hash
!= chainparams
.GetConsensus().hashGenesisBlock
&& mapBlockIndex
[hash
]->nHeight
% 1000 == 0) {
3762 LogPrint(BCLog::REINDEX
, "Block Import: already had block %s at height %d\n", hash
.ToString(), mapBlockIndex
[hash
]->nHeight
);
3765 // Activate the genesis block so normal node progress can continue
3766 if (hash
== chainparams
.GetConsensus().hashGenesisBlock
) {
3767 CValidationState state
;
3768 if (!ActivateBestChain(state
, chainparams
)) {
3775 // Recursively process earlier encountered successors of this block
3776 std::deque
<uint256
> queue
;
3777 queue
.push_back(hash
);
3778 while (!queue
.empty()) {
3779 uint256 head
= queue
.front();
3781 std::pair
<std::multimap
<uint256
, CDiskBlockPos
>::iterator
, std::multimap
<uint256
, CDiskBlockPos
>::iterator
> range
= mapBlocksUnknownParent
.equal_range(head
);
3782 while (range
.first
!= range
.second
) {
3783 std::multimap
<uint256
, CDiskBlockPos
>::iterator it
= range
.first
;
3784 std::shared_ptr
<CBlock
> pblockrecursive
= std::make_shared
<CBlock
>();
3785 if (ReadBlockFromDisk(*pblockrecursive
, it
->second
, chainparams
.GetConsensus()))
3787 LogPrint(BCLog::REINDEX
, "%s: Processing out of order child %s of %s\n", __func__
, pblockrecursive
->GetHash().ToString(),
3790 CValidationState dummy
;
3791 if (AcceptBlock(pblockrecursive
, dummy
, chainparams
, NULL
, true, &it
->second
, NULL
))
3794 queue
.push_back(pblockrecursive
->GetHash());
3798 mapBlocksUnknownParent
.erase(it
);
3802 } catch (const std::exception
& e
) {
3803 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__
, e
.what());
3806 } catch (const std::runtime_error
& e
) {
3807 AbortNode(std::string("System error: ") + e
.what());
3810 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded
, GetTimeMillis() - nStart
);
3814 void static CheckBlockIndex(const Consensus::Params
& consensusParams
)
3816 if (!fCheckBlockIndex
) {
3822 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3823 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3824 // iterating the block tree require that chainActive has been initialized.)
3825 if (chainActive
.Height() < 0) {
3826 assert(mapBlockIndex
.size() <= 1);
3830 // Build forward-pointing map of the entire block tree.
3831 std::multimap
<CBlockIndex
*,CBlockIndex
*> forward
;
3832 for (BlockMap::iterator it
= mapBlockIndex
.begin(); it
!= mapBlockIndex
.end(); it
++) {
3833 forward
.insert(std::make_pair(it
->second
->pprev
, it
->second
));
3836 assert(forward
.size() == mapBlockIndex
.size());
3838 std::pair
<std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
,std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
> rangeGenesis
= forward
.equal_range(NULL
);
3839 CBlockIndex
*pindex
= rangeGenesis
.first
->second
;
3840 rangeGenesis
.first
++;
3841 assert(rangeGenesis
.first
== rangeGenesis
.second
); // There is only one index entry with parent NULL.
3843 // Iterate over the entire block tree, using depth-first search.
3844 // Along the way, remember whether there are blocks on the path from genesis
3845 // block being explored which are the first to have certain properties.
3848 CBlockIndex
* pindexFirstInvalid
= NULL
; // Oldest ancestor of pindex which is invalid.
3849 CBlockIndex
* pindexFirstMissing
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3850 CBlockIndex
* pindexFirstNeverProcessed
= NULL
; // Oldest ancestor of pindex for which nTx == 0.
3851 CBlockIndex
* pindexFirstNotTreeValid
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3852 CBlockIndex
* pindexFirstNotTransactionsValid
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3853 CBlockIndex
* pindexFirstNotChainValid
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3854 CBlockIndex
* pindexFirstNotScriptsValid
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3855 while (pindex
!= NULL
) {
3857 if (pindexFirstInvalid
== NULL
&& pindex
->nStatus
& BLOCK_FAILED_VALID
) pindexFirstInvalid
= pindex
;
3858 if (pindexFirstMissing
== NULL
&& !(pindex
->nStatus
& BLOCK_HAVE_DATA
)) pindexFirstMissing
= pindex
;
3859 if (pindexFirstNeverProcessed
== NULL
&& pindex
->nTx
== 0) pindexFirstNeverProcessed
= pindex
;
3860 if (pindex
->pprev
!= NULL
&& pindexFirstNotTreeValid
== NULL
&& (pindex
->nStatus
& BLOCK_VALID_MASK
) < BLOCK_VALID_TREE
) pindexFirstNotTreeValid
= pindex
;
3861 if (pindex
->pprev
!= NULL
&& pindexFirstNotTransactionsValid
== NULL
&& (pindex
->nStatus
& BLOCK_VALID_MASK
) < BLOCK_VALID_TRANSACTIONS
) pindexFirstNotTransactionsValid
= pindex
;
3862 if (pindex
->pprev
!= NULL
&& pindexFirstNotChainValid
== NULL
&& (pindex
->nStatus
& BLOCK_VALID_MASK
) < BLOCK_VALID_CHAIN
) pindexFirstNotChainValid
= pindex
;
3863 if (pindex
->pprev
!= NULL
&& pindexFirstNotScriptsValid
== NULL
&& (pindex
->nStatus
& BLOCK_VALID_MASK
) < BLOCK_VALID_SCRIPTS
) pindexFirstNotScriptsValid
= pindex
;
3865 // Begin: actual consistency checks.
3866 if (pindex
->pprev
== NULL
) {
3867 // Genesis block checks.
3868 assert(pindex
->GetBlockHash() == consensusParams
.hashGenesisBlock
); // Genesis block's hash must match.
3869 assert(pindex
== chainActive
.Genesis()); // The current active chain's genesis block must be this block.
3871 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)
3872 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3873 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3875 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3876 assert(!(pindex
->nStatus
& BLOCK_HAVE_DATA
) == (pindex
->nTx
== 0));
3877 assert(pindexFirstMissing
== pindexFirstNeverProcessed
);
3879 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3880 if (pindex
->nStatus
& BLOCK_HAVE_DATA
) assert(pindex
->nTx
> 0);
3882 if (pindex
->nStatus
& BLOCK_HAVE_UNDO
) assert(pindex
->nStatus
& BLOCK_HAVE_DATA
);
3883 assert(((pindex
->nStatus
& BLOCK_VALID_MASK
) >= BLOCK_VALID_TRANSACTIONS
) == (pindex
->nTx
> 0)); // This is pruning-independent.
3884 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3885 assert((pindexFirstNeverProcessed
!= NULL
) == (pindex
->nChainTx
== 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3886 assert((pindexFirstNotTransactionsValid
!= NULL
) == (pindex
->nChainTx
== 0));
3887 assert(pindex
->nHeight
== nHeight
); // nHeight must be consistent.
3888 assert(pindex
->pprev
== NULL
|| pindex
->nChainWork
>= pindex
->pprev
->nChainWork
); // For every block except the genesis block, the chainwork must be larger than the parent's.
3889 assert(nHeight
< 2 || (pindex
->pskip
&& (pindex
->pskip
->nHeight
< nHeight
))); // The pskip pointer must point back for all but the first 2 blocks.
3890 assert(pindexFirstNotTreeValid
== NULL
); // All mapBlockIndex entries must at least be TREE valid
3891 if ((pindex
->nStatus
& BLOCK_VALID_MASK
) >= BLOCK_VALID_TREE
) assert(pindexFirstNotTreeValid
== NULL
); // TREE valid implies all parents are TREE valid
3892 if ((pindex
->nStatus
& BLOCK_VALID_MASK
) >= BLOCK_VALID_CHAIN
) assert(pindexFirstNotChainValid
== NULL
); // CHAIN valid implies all parents are CHAIN valid
3893 if ((pindex
->nStatus
& BLOCK_VALID_MASK
) >= BLOCK_VALID_SCRIPTS
) assert(pindexFirstNotScriptsValid
== NULL
); // SCRIPTS valid implies all parents are SCRIPTS valid
3894 if (pindexFirstInvalid
== NULL
) {
3895 // Checks for not-invalid blocks.
3896 assert((pindex
->nStatus
& BLOCK_FAILED_MASK
) == 0); // The failed mask cannot be set for blocks without invalid parents.
3898 if (!CBlockIndexWorkComparator()(pindex
, chainActive
.Tip()) && pindexFirstNeverProcessed
== NULL
) {
3899 if (pindexFirstInvalid
== NULL
) {
3900 // If this block sorts at least as good as the current tip and
3901 // is valid and we have all data for its parents, it must be in
3902 // setBlockIndexCandidates. chainActive.Tip() must also be there
3903 // even if some data has been pruned.
3904 if (pindexFirstMissing
== NULL
|| pindex
== chainActive
.Tip()) {
3905 assert(setBlockIndexCandidates
.count(pindex
));
3907 // If some parent is missing, then it could be that this block was in
3908 // setBlockIndexCandidates but had to be removed because of the missing data.
3909 // In this case it must be in mapBlocksUnlinked -- see test below.
3911 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3912 assert(setBlockIndexCandidates
.count(pindex
) == 0);
3914 // Check whether this block is in mapBlocksUnlinked.
3915 std::pair
<std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
,std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
> rangeUnlinked
= mapBlocksUnlinked
.equal_range(pindex
->pprev
);
3916 bool foundInUnlinked
= false;
3917 while (rangeUnlinked
.first
!= rangeUnlinked
.second
) {
3918 assert(rangeUnlinked
.first
->first
== pindex
->pprev
);
3919 if (rangeUnlinked
.first
->second
== pindex
) {
3920 foundInUnlinked
= true;
3923 rangeUnlinked
.first
++;
3925 if (pindex
->pprev
&& (pindex
->nStatus
& BLOCK_HAVE_DATA
) && pindexFirstNeverProcessed
!= NULL
&& pindexFirstInvalid
== NULL
) {
3926 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3927 assert(foundInUnlinked
);
3929 if (!(pindex
->nStatus
& BLOCK_HAVE_DATA
)) assert(!foundInUnlinked
); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3930 if (pindexFirstMissing
== NULL
) assert(!foundInUnlinked
); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3931 if (pindex
->pprev
&& (pindex
->nStatus
& BLOCK_HAVE_DATA
) && pindexFirstNeverProcessed
== NULL
&& pindexFirstMissing
!= NULL
) {
3932 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3933 assert(fHavePruned
); // We must have pruned.
3934 // This block may have entered mapBlocksUnlinked if:
3935 // - it has a descendant that at some point had more work than the
3937 // - we tried switching to that descendant but were missing
3938 // data for some intermediate block between chainActive and the
3940 // So if this block is itself better than chainActive.Tip() and it wasn't in
3941 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3942 if (!CBlockIndexWorkComparator()(pindex
, chainActive
.Tip()) && setBlockIndexCandidates
.count(pindex
) == 0) {
3943 if (pindexFirstInvalid
== NULL
) {
3944 assert(foundInUnlinked
);
3948 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
3949 // End: actual consistency checks.
3951 // Try descending into the first subnode.
3952 std::pair
<std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
,std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
> range
= forward
.equal_range(pindex
);
3953 if (range
.first
!= range
.second
) {
3954 // A subnode was found.
3955 pindex
= range
.first
->second
;
3959 // This is a leaf node.
3960 // Move upwards until we reach a node of which we have not yet visited the last child.
3962 // We are going to either move to a parent or a sibling of pindex.
3963 // If pindex was the first with a certain property, unset the corresponding variable.
3964 if (pindex
== pindexFirstInvalid
) pindexFirstInvalid
= NULL
;
3965 if (pindex
== pindexFirstMissing
) pindexFirstMissing
= NULL
;
3966 if (pindex
== pindexFirstNeverProcessed
) pindexFirstNeverProcessed
= NULL
;
3967 if (pindex
== pindexFirstNotTreeValid
) pindexFirstNotTreeValid
= NULL
;
3968 if (pindex
== pindexFirstNotTransactionsValid
) pindexFirstNotTransactionsValid
= NULL
;
3969 if (pindex
== pindexFirstNotChainValid
) pindexFirstNotChainValid
= NULL
;
3970 if (pindex
== pindexFirstNotScriptsValid
) pindexFirstNotScriptsValid
= NULL
;
3972 CBlockIndex
* pindexPar
= pindex
->pprev
;
3973 // Find which child we just visited.
3974 std::pair
<std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
,std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
> rangePar
= forward
.equal_range(pindexPar
);
3975 while (rangePar
.first
->second
!= pindex
) {
3976 assert(rangePar
.first
!= rangePar
.second
); // Our parent must have at least the node we're coming from as child.
3979 // Proceed to the next one.
3981 if (rangePar
.first
!= rangePar
.second
) {
3982 // Move to the sibling.
3983 pindex
= rangePar
.first
->second
;
3994 // Check that we actually traversed the entire map.
3995 assert(nNodes
== forward
.size());
3998 std::string
CBlockFileInfo::ToString() const
4000 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
));
4003 CBlockFileInfo
* GetBlockFileInfo(size_t n
)
4005 return &vinfoBlockFile
.at(n
);
4008 ThresholdState
VersionBitsTipState(const Consensus::Params
& params
, Consensus::DeploymentPos pos
)
4011 return VersionBitsState(chainActive
.Tip(), params
, pos
, versionbitscache
);
4014 BIP9Stats
VersionBitsTipStatistics(const Consensus::Params
& params
, Consensus::DeploymentPos pos
)
4017 return VersionBitsStatistics(chainActive
.Tip(), params
, pos
);
4020 int VersionBitsTipStateSinceHeight(const Consensus::Params
& params
, Consensus::DeploymentPos pos
)
4023 return VersionBitsStateSinceHeight(chainActive
.Tip(), params
, pos
, versionbitscache
);
4026 static const uint64_t MEMPOOL_DUMP_VERSION
= 1;
4028 bool LoadMempool(void)
4030 const CChainParams
& chainparams
= Params();
4031 int64_t nExpiryTimeout
= GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY
) * 60 * 60;
4032 FILE* filestr
= fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4033 CAutoFile
file(filestr
, SER_DISK
, CLIENT_VERSION
);
4034 if (file
.IsNull()) {
4035 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4040 int64_t skipped
= 0;
4042 int64_t nNow
= GetTime();
4047 if (version
!= MEMPOOL_DUMP_VERSION
) {
4060 CAmount amountdelta
= nFeeDelta
;
4062 mempool
.PrioritiseTransaction(tx
->GetHash(), amountdelta
);
4064 CValidationState state
;
4065 if (nTime
+ nExpiryTimeout
> nNow
) {
4067 AcceptToMemoryPoolWithTime(chainparams
, mempool
, state
, tx
, true, NULL
, nTime
, NULL
, false, 0);
4068 if (state
.IsValid()) {
4076 if (ShutdownRequested())
4079 std::map
<uint256
, CAmount
> mapDeltas
;
4082 for (const auto& i
: mapDeltas
) {
4083 mempool
.PrioritiseTransaction(i
.first
, i
.second
);
4085 } catch (const std::exception
& e
) {
4086 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e
.what());
4090 LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count
, failed
, skipped
);
4094 void DumpMempool(void)
4096 int64_t start
= GetTimeMicros();
4098 std::map
<uint256
, CAmount
> mapDeltas
;
4099 std::vector
<TxMempoolInfo
> vinfo
;
4103 for (const auto &i
: mempool
.mapDeltas
) {
4104 mapDeltas
[i
.first
] = i
.second
;
4106 vinfo
= mempool
.infoAll();
4109 int64_t mid
= GetTimeMicros();
4112 FILE* filestr
= fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4117 CAutoFile
file(filestr
, SER_DISK
, CLIENT_VERSION
);
4119 uint64_t version
= MEMPOOL_DUMP_VERSION
;
4122 file
<< (uint64_t)vinfo
.size();
4123 for (const auto& i
: vinfo
) {
4125 file
<< (int64_t)i
.nTime
;
4126 file
<< (int64_t)i
.nFeeDelta
;
4127 mapDeltas
.erase(i
.tx
->GetHash());
4131 FileCommit(file
.Get());
4133 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4134 int64_t last
= GetTimeMicros();
4135 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid
-start
)*0.000001, (last
-mid
)*0.000001);
4136 } catch (const std::exception
& e
) {
4137 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e
.what());
4141 //! Guess how far we are in the verification process at the given block index
4142 double GuessVerificationProgress(const ChainTxData
& data
, CBlockIndex
*pindex
) {
4146 int64_t nNow
= time(NULL
);
4150 if (pindex
->nChainTx
<= data
.nTxCount
) {
4151 fTxTotal
= data
.nTxCount
+ (nNow
- data
.nTime
) * data
.dTxRate
;
4153 fTxTotal
= pindex
->nChainTx
+ (nNow
- pindex
->GetBlockTime()) * data
.dTxRate
;
4156 return pindex
->nChainTx
/ fTxTotal
;
4165 BlockMap::iterator it1
= mapBlockIndex
.begin();
4166 for (; it1
!= mapBlockIndex
.end(); it1
++)
4167 delete (*it1
).second
;
4168 mapBlockIndex
.clear();
4170 } instance_of_cmaincleanup
;