1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "validation.h"
8 #include "arith_uint256.h"
9 #include "chainparams.h"
10 #include "checkpoints.h"
11 #include "checkqueue.h"
12 #include "consensus/consensus.h"
13 #include "consensus/merkle.h"
14 #include "consensus/validation.h"
17 #include "policy/fees.h"
18 #include "policy/policy.h"
20 #include "primitives/block.h"
21 #include "primitives/transaction.h"
23 #include "script/script.h"
24 #include "script/sigcache.h"
25 #include "script/standard.h"
27 #include "tinyformat.h"
29 #include "txmempool.h"
30 #include "ui_interface.h"
33 #include "utilmoneystr.h"
34 #include "utilstrencodings.h"
35 #include "validationinterface.h"
36 #include "versionbits.h"
41 #include <boost/algorithm/string/replace.hpp>
42 #include <boost/algorithm/string/join.hpp>
43 #include <boost/filesystem.hpp>
44 #include <boost/filesystem/fstream.hpp>
45 #include <boost/math/distributions/poisson.hpp>
46 #include <boost/thread.hpp>
51 # error "Bitcoin cannot be compiled without assertions."
58 CCriticalSection cs_main
;
60 BlockMap mapBlockIndex
;
62 CBlockIndex
*pindexBestHeader
= NULL
;
63 CWaitableCriticalSection csBestBlock
;
64 CConditionVariable cvBlockChange
;
65 int nScriptCheckThreads
= 0;
66 std::atomic_bool
fImporting(false);
67 bool fReindex
= false;
68 bool fTxIndex
= false;
69 bool fHavePruned
= false;
70 bool fPruneMode
= false;
71 bool fIsBareMultisigStd
= DEFAULT_PERMIT_BAREMULTISIG
;
72 bool fRequireStandard
= true;
73 bool fCheckBlockIndex
= false;
74 bool fCheckpointsEnabled
= DEFAULT_CHECKPOINTS_ENABLED
;
75 size_t nCoinCacheUsage
= 5000 * 300;
76 uint64_t nPruneTarget
= 0;
77 int64_t nMaxTipAge
= DEFAULT_MAX_TIP_AGE
;
78 bool fEnableReplacement
= DEFAULT_ENABLE_REPLACEMENT
;
81 CFeeRate minRelayTxFee
= CFeeRate(DEFAULT_MIN_RELAY_TX_FEE
);
82 CAmount maxTxFee
= DEFAULT_TRANSACTION_MAXFEE
;
84 CTxMemPool
mempool(::minRelayTxFee
);
86 static void CheckBlockIndex(const Consensus::Params
& consensusParams
);
88 /** Constant stuff for coinbase transactions we create: */
89 CScript COINBASE_FLAGS
;
91 const string strMessageMagic
= "Bitcoin Signed Message:\n";
96 struct CBlockIndexWorkComparator
98 bool operator()(CBlockIndex
*pa
, CBlockIndex
*pb
) const {
99 // First sort by most total work, ...
100 if (pa
->nChainWork
> pb
->nChainWork
) return false;
101 if (pa
->nChainWork
< pb
->nChainWork
) return true;
103 // ... then by earliest time received, ...
104 if (pa
->nSequenceId
< pb
->nSequenceId
) return false;
105 if (pa
->nSequenceId
> pb
->nSequenceId
) return true;
107 // Use pointer address as tie breaker (should only happen with blocks
108 // loaded from disk, as those all have id 0).
109 if (pa
< pb
) return false;
110 if (pa
> pb
) return true;
117 CBlockIndex
*pindexBestInvalid
;
120 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
121 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
122 * missing the data for the block.
124 set
<CBlockIndex
*, CBlockIndexWorkComparator
> setBlockIndexCandidates
;
125 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
126 * Pruned nodes may have entries where B is missing data.
128 multimap
<CBlockIndex
*, CBlockIndex
*> mapBlocksUnlinked
;
130 CCriticalSection cs_LastBlockFile
;
131 std::vector
<CBlockFileInfo
> vinfoBlockFile
;
132 int nLastBlockFile
= 0;
133 /** Global flag to indicate we should check to see if there are
134 * block/undo files that should be deleted. Set on startup
135 * or if we allocate more file space when we're in prune mode
137 bool fCheckForPruning
= false;
140 * Every received block is assigned a unique and increasing identifier, so we
141 * know which one to give priority in case of a fork.
143 CCriticalSection cs_nBlockSequenceId
;
144 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
145 int32_t nBlockSequenceId
= 1;
146 /** Decreasing counter (used by subsequent preciousblock calls). */
147 int32_t nBlockReverseSequenceId
= -1;
148 /** chainwork for the last block that preciousblock has been applied to. */
149 arith_uint256 nLastPreciousChainwork
= 0;
151 /** Dirty block index entries. */
152 set
<CBlockIndex
*> setDirtyBlockIndex
;
154 /** Dirty block file entries. */
155 set
<int> setDirtyFileInfo
;
158 CBlockIndex
* FindForkInGlobalIndex(const CChain
& chain
, const CBlockLocator
& locator
)
160 // Find the first block the caller has in the main chain
161 BOOST_FOREACH(const uint256
& hash
, locator
.vHave
) {
162 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
163 if (mi
!= mapBlockIndex
.end())
165 CBlockIndex
* pindex
= (*mi
).second
;
166 if (chain
.Contains(pindex
))
168 if (pindex
->GetAncestor(chain
.Height()) == chain
.Tip()) {
173 return chain
.Genesis();
176 CCoinsViewCache
*pcoinsTip
= NULL
;
177 CBlockTreeDB
*pblocktree
= NULL
;
179 enum FlushStateMode
{
181 FLUSH_STATE_IF_NEEDED
,
182 FLUSH_STATE_PERIODIC
,
186 // See definition for documentation
187 bool static FlushStateToDisk(CValidationState
&state
, FlushStateMode mode
);
189 bool IsFinalTx(const CTransaction
&tx
, int nBlockHeight
, int64_t nBlockTime
)
191 if (tx
.nLockTime
== 0)
193 if ((int64_t)tx
.nLockTime
< ((int64_t)tx
.nLockTime
< LOCKTIME_THRESHOLD
? (int64_t)nBlockHeight
: nBlockTime
))
195 for (const auto& txin
: tx
.vin
) {
196 if (!(txin
.nSequence
== CTxIn::SEQUENCE_FINAL
))
202 bool CheckFinalTx(const CTransaction
&tx
, int flags
)
204 AssertLockHeld(cs_main
);
206 // By convention a negative value for flags indicates that the
207 // current network-enforced consensus rules should be used. In
208 // a future soft-fork scenario that would mean checking which
209 // rules would be enforced for the next block and setting the
210 // appropriate flags. At the present time no soft-forks are
211 // scheduled, so no flags are set.
212 flags
= std::max(flags
, 0);
214 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
215 // nLockTime because when IsFinalTx() is called within
216 // CBlock::AcceptBlock(), the height of the block *being*
217 // evaluated is what is used. Thus if we want to know if a
218 // transaction can be part of the *next* block, we need to call
219 // IsFinalTx() with one more than chainActive.Height().
220 const int nBlockHeight
= chainActive
.Height() + 1;
222 // BIP113 will require that time-locked transactions have nLockTime set to
223 // less than the median time of the previous block they're contained in.
224 // When the next block is created its previous block will be the current
225 // chain tip, so we use that to calculate the median time passed to
226 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
227 const int64_t nBlockTime
= (flags
& LOCKTIME_MEDIAN_TIME_PAST
)
228 ? chainActive
.Tip()->GetMedianTimePast()
231 return IsFinalTx(tx
, nBlockHeight
, nBlockTime
);
235 * Calculates the block height and previous block's median time past at
236 * which the transaction will be considered final in the context of BIP 68.
237 * Also removes from the vector of input heights any entries which did not
238 * correspond to sequence locked inputs as they do not affect the calculation.
240 static std::pair
<int, int64_t> CalculateSequenceLocks(const CTransaction
&tx
, int flags
, std::vector
<int>* prevHeights
, const CBlockIndex
& block
)
242 assert(prevHeights
->size() == tx
.vin
.size());
244 // Will be set to the equivalent height- and time-based nLockTime
245 // values that would be necessary to satisfy all relative lock-
246 // time constraints given our view of block chain history.
247 // The semantics of nLockTime are the last invalid height/time, so
248 // use -1 to have the effect of any height or time being valid.
250 int64_t nMinTime
= -1;
252 // tx.nVersion is signed integer so requires cast to unsigned otherwise
253 // we would be doing a signed comparison and half the range of nVersion
254 // wouldn't support BIP 68.
255 bool fEnforceBIP68
= static_cast<uint32_t>(tx
.nVersion
) >= 2
256 && flags
& LOCKTIME_VERIFY_SEQUENCE
;
258 // Do not enforce sequence numbers as a relative lock time
259 // unless we have been instructed to
260 if (!fEnforceBIP68
) {
261 return std::make_pair(nMinHeight
, nMinTime
);
264 for (size_t txinIndex
= 0; txinIndex
< tx
.vin
.size(); txinIndex
++) {
265 const CTxIn
& txin
= tx
.vin
[txinIndex
];
267 // Sequence numbers with the most significant bit set are not
268 // treated as relative lock-times, nor are they given any
269 // consensus-enforced meaning at this point.
270 if (txin
.nSequence
& CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG
) {
271 // The height of this input is not relevant for sequence locks
272 (*prevHeights
)[txinIndex
] = 0;
276 int nCoinHeight
= (*prevHeights
)[txinIndex
];
278 if (txin
.nSequence
& CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG
) {
279 int64_t nCoinTime
= block
.GetAncestor(std::max(nCoinHeight
-1, 0))->GetMedianTimePast();
280 // NOTE: Subtract 1 to maintain nLockTime semantics
281 // BIP 68 relative lock times have the semantics of calculating
282 // the first block or time at which the transaction would be
283 // valid. When calculating the effective block time or height
284 // for the entire transaction, we switch to using the
285 // semantics of nLockTime which is the last invalid block
286 // time or height. Thus we subtract 1 from the calculated
289 // Time-based relative lock-times are measured from the
290 // smallest allowed timestamp of the block containing the
291 // txout being spent, which is the median time past of the
293 nMinTime
= std::max(nMinTime
, nCoinTime
+ (int64_t)((txin
.nSequence
& CTxIn::SEQUENCE_LOCKTIME_MASK
) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY
) - 1);
295 nMinHeight
= std::max(nMinHeight
, nCoinHeight
+ (int)(txin
.nSequence
& CTxIn::SEQUENCE_LOCKTIME_MASK
) - 1);
299 return std::make_pair(nMinHeight
, nMinTime
);
302 static bool EvaluateSequenceLocks(const CBlockIndex
& block
, std::pair
<int, int64_t> lockPair
)
305 int64_t nBlockTime
= block
.pprev
->GetMedianTimePast();
306 if (lockPair
.first
>= block
.nHeight
|| lockPair
.second
>= nBlockTime
)
312 bool SequenceLocks(const CTransaction
&tx
, int flags
, std::vector
<int>* prevHeights
, const CBlockIndex
& block
)
314 return EvaluateSequenceLocks(block
, CalculateSequenceLocks(tx
, flags
, prevHeights
, block
));
317 bool TestLockPointValidity(const LockPoints
* lp
)
319 AssertLockHeld(cs_main
);
321 // If there are relative lock times then the maxInputBlock will be set
322 // If there are no relative lock times, the LockPoints don't depend on the chain
323 if (lp
->maxInputBlock
) {
324 // Check whether chainActive is an extension of the block at which the LockPoints
325 // calculation was valid. If not LockPoints are no longer valid
326 if (!chainActive
.Contains(lp
->maxInputBlock
)) {
331 // LockPoints still valid
335 bool CheckSequenceLocks(const CTransaction
&tx
, int flags
, LockPoints
* lp
, bool useExistingLockPoints
)
337 AssertLockHeld(cs_main
);
338 AssertLockHeld(mempool
.cs
);
340 CBlockIndex
* tip
= chainActive
.Tip();
343 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
344 // height based locks because when SequenceLocks() is called within
345 // ConnectBlock(), the height of the block *being*
346 // evaluated is what is used.
347 // Thus if we want to know if a transaction can be part of the
348 // *next* block, we need to use one more than chainActive.Height()
349 index
.nHeight
= tip
->nHeight
+ 1;
351 std::pair
<int, int64_t> lockPair
;
352 if (useExistingLockPoints
) {
354 lockPair
.first
= lp
->height
;
355 lockPair
.second
= lp
->time
;
358 // pcoinsTip contains the UTXO set for chainActive.Tip()
359 CCoinsViewMemPool
viewMemPool(pcoinsTip
, mempool
);
360 std::vector
<int> prevheights
;
361 prevheights
.resize(tx
.vin
.size());
362 for (size_t txinIndex
= 0; txinIndex
< tx
.vin
.size(); txinIndex
++) {
363 const CTxIn
& txin
= tx
.vin
[txinIndex
];
365 if (!viewMemPool
.GetCoins(txin
.prevout
.hash
, coins
)) {
366 return error("%s: Missing input", __func__
);
368 if (coins
.nHeight
== MEMPOOL_HEIGHT
) {
369 // Assume all mempool transaction confirm in the next block
370 prevheights
[txinIndex
] = tip
->nHeight
+ 1;
372 prevheights
[txinIndex
] = coins
.nHeight
;
375 lockPair
= CalculateSequenceLocks(tx
, flags
, &prevheights
, index
);
377 lp
->height
= lockPair
.first
;
378 lp
->time
= lockPair
.second
;
379 // Also store the hash of the block with the highest height of
380 // all the blocks which have sequence locked prevouts.
381 // This hash needs to still be on the chain
382 // for these LockPoint calculations to be valid
383 // Note: It is impossible to correctly calculate a maxInputBlock
384 // if any of the sequence locked inputs depend on unconfirmed txs,
385 // except in the special case where the relative lock time/height
386 // is 0, which is equivalent to no sequence lock. Since we assume
387 // input height of tip+1 for mempool txs and test the resulting
388 // lockPair from CalculateSequenceLocks against tip+1. We know
389 // EvaluateSequenceLocks will fail if there was a non-zero sequence
390 // lock on a mempool input, so we can use the return value of
391 // CheckSequenceLocks to indicate the LockPoints validity
392 int maxInputHeight
= 0;
393 BOOST_FOREACH(int height
, prevheights
) {
394 // Can ignore mempool inputs since we'll fail if they had non-zero locks
395 if (height
!= tip
->nHeight
+1) {
396 maxInputHeight
= std::max(maxInputHeight
, height
);
399 lp
->maxInputBlock
= tip
->GetAncestor(maxInputHeight
);
402 return EvaluateSequenceLocks(index
, lockPair
);
406 unsigned int GetLegacySigOpCount(const CTransaction
& tx
)
408 unsigned int nSigOps
= 0;
409 for (const auto& txin
: tx
.vin
)
411 nSigOps
+= txin
.scriptSig
.GetSigOpCount(false);
413 for (const auto& txout
: tx
.vout
)
415 nSigOps
+= txout
.scriptPubKey
.GetSigOpCount(false);
420 unsigned int GetP2SHSigOpCount(const CTransaction
& tx
, const CCoinsViewCache
& inputs
)
425 unsigned int nSigOps
= 0;
426 for (unsigned int i
= 0; i
< tx
.vin
.size(); i
++)
428 const CTxOut
&prevout
= inputs
.GetOutputFor(tx
.vin
[i
]);
429 if (prevout
.scriptPubKey
.IsPayToScriptHash())
430 nSigOps
+= prevout
.scriptPubKey
.GetSigOpCount(tx
.vin
[i
].scriptSig
);
435 int64_t GetTransactionSigOpCost(const CTransaction
& tx
, const CCoinsViewCache
& inputs
, int flags
)
437 int64_t nSigOps
= GetLegacySigOpCount(tx
) * WITNESS_SCALE_FACTOR
;
442 if (flags
& SCRIPT_VERIFY_P2SH
) {
443 nSigOps
+= GetP2SHSigOpCount(tx
, inputs
) * WITNESS_SCALE_FACTOR
;
446 for (unsigned int i
= 0; i
< tx
.vin
.size(); i
++)
448 const CTxOut
&prevout
= inputs
.GetOutputFor(tx
.vin
[i
]);
449 nSigOps
+= CountWitnessSigOps(tx
.vin
[i
].scriptSig
, prevout
.scriptPubKey
, i
< tx
.wit
.vtxinwit
.size() ? &tx
.wit
.vtxinwit
[i
].scriptWitness
: NULL
, flags
);
458 bool CheckTransaction(const CTransaction
& tx
, CValidationState
&state
, bool fCheckDuplicateInputs
)
460 // Basic checks that don't depend on any context
462 return state
.DoS(10, false, REJECT_INVALID
, "bad-txns-vin-empty");
464 return state
.DoS(10, false, REJECT_INVALID
, "bad-txns-vout-empty");
465 // Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability)
466 if (::GetSerializeSize(tx
, SER_NETWORK
, PROTOCOL_VERSION
| SERIALIZE_TRANSACTION_NO_WITNESS
) > MAX_BLOCK_BASE_SIZE
)
467 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-oversize");
469 // Check for negative or overflow output values
470 CAmount nValueOut
= 0;
471 for (const auto& txout
: tx
.vout
)
473 if (txout
.nValue
< 0)
474 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-vout-negative");
475 if (txout
.nValue
> MAX_MONEY
)
476 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-vout-toolarge");
477 nValueOut
+= txout
.nValue
;
478 if (!MoneyRange(nValueOut
))
479 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-txouttotal-toolarge");
482 // Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock
483 if (fCheckDuplicateInputs
) {
484 set
<COutPoint
> vInOutPoints
;
485 for (const auto& txin
: tx
.vin
)
487 if (!vInOutPoints
.insert(txin
.prevout
).second
)
488 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-inputs-duplicate");
494 if (tx
.vin
[0].scriptSig
.size() < 2 || tx
.vin
[0].scriptSig
.size() > 100)
495 return state
.DoS(100, false, REJECT_INVALID
, "bad-cb-length");
499 for (const auto& txin
: tx
.vin
)
500 if (txin
.prevout
.IsNull())
501 return state
.DoS(10, false, REJECT_INVALID
, "bad-txns-prevout-null");
507 void LimitMempoolSize(CTxMemPool
& pool
, size_t limit
, unsigned long age
) {
508 int expired
= pool
.Expire(GetTime() - age
);
510 LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired
);
512 std::vector
<uint256
> vNoSpendsRemaining
;
513 pool
.TrimToSize(limit
, &vNoSpendsRemaining
);
514 BOOST_FOREACH(const uint256
& removed
, vNoSpendsRemaining
)
515 pcoinsTip
->Uncache(removed
);
518 /** Convert CValidationState to a human-readable message for logging */
519 std::string
FormatStateMessage(const CValidationState
&state
)
521 return strprintf("%s%s (code %i)",
522 state
.GetRejectReason(),
523 state
.GetDebugMessage().empty() ? "" : ", "+state
.GetDebugMessage(),
524 state
.GetRejectCode());
527 bool AcceptToMemoryPoolWorker(CTxMemPool
& pool
, CValidationState
& state
, const CTransaction
& tx
, bool fLimitFree
,
528 bool* pfMissingInputs
, int64_t nAcceptTime
, bool fOverrideMempoolLimit
, const CAmount
& nAbsurdFee
,
529 std::vector
<uint256
>& vHashTxnToUncache
)
531 const uint256 hash
= tx
.GetHash();
532 AssertLockHeld(cs_main
);
534 *pfMissingInputs
= false;
536 if (!CheckTransaction(tx
, state
))
537 return false; // state filled in by CheckTransaction
539 // Coinbase is only valid in a block, not as a loose transaction
541 return state
.DoS(100, false, REJECT_INVALID
, "coinbase");
543 // Don't relay version 2 transactions until CSV is active, and we can be
544 // sure that such transactions will be mined (unless we're on
545 // -testnet/-regtest).
546 const CChainParams
& chainparams
= Params();
547 if (fRequireStandard
&& tx
.nVersion
>= 2 && VersionBitsTipState(chainparams
.GetConsensus(), Consensus::DEPLOYMENT_CSV
) != THRESHOLD_ACTIVE
) {
548 return state
.DoS(0, false, REJECT_NONSTANDARD
, "premature-version2-tx");
551 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
552 bool witnessEnabled
= IsWitnessEnabled(chainActive
.Tip(), Params().GetConsensus());
553 if (!GetBoolArg("-prematurewitness",false) && !tx
.wit
.IsNull() && !witnessEnabled
) {
554 return state
.DoS(0, false, REJECT_NONSTANDARD
, "no-witness-yet", true);
557 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
559 if (fRequireStandard
&& !IsStandardTx(tx
, reason
, witnessEnabled
))
560 return state
.DoS(0, false, REJECT_NONSTANDARD
, reason
);
562 // Only accept nLockTime-using transactions that can be mined in the next
563 // block; we don't want our mempool filled up with transactions that can't
565 if (!CheckFinalTx(tx
, STANDARD_LOCKTIME_VERIFY_FLAGS
))
566 return state
.DoS(0, false, REJECT_NONSTANDARD
, "non-final");
568 // is it already in the memory pool?
569 if (pool
.exists(hash
))
570 return state
.Invalid(false, REJECT_ALREADY_KNOWN
, "txn-already-in-mempool");
572 // Check for conflicts with in-memory transactions
573 set
<uint256
> setConflicts
;
575 LOCK(pool
.cs
); // protect pool.mapNextTx
576 BOOST_FOREACH(const CTxIn
&txin
, tx
.vin
)
578 auto itConflicting
= pool
.mapNextTx
.find(txin
.prevout
);
579 if (itConflicting
!= pool
.mapNextTx
.end())
581 const CTransaction
*ptxConflicting
= itConflicting
->second
;
582 if (!setConflicts
.count(ptxConflicting
->GetHash()))
584 // Allow opt-out of transaction replacement by setting
585 // nSequence >= maxint-1 on all inputs.
587 // maxint-1 is picked to still allow use of nLockTime by
588 // non-replaceable transactions. All inputs rather than just one
589 // is for the sake of multi-party protocols, where we don't
590 // want a single party to be able to disable replacement.
592 // The opt-out ignores descendants as anyone relying on
593 // first-seen mempool behavior should be checking all
594 // unconfirmed ancestors anyway; doing otherwise is hopelessly
596 bool fReplacementOptOut
= true;
597 if (fEnableReplacement
)
599 BOOST_FOREACH(const CTxIn
&_txin
, ptxConflicting
->vin
)
601 if (_txin
.nSequence
< std::numeric_limits
<unsigned int>::max()-1)
603 fReplacementOptOut
= false;
608 if (fReplacementOptOut
)
609 return state
.Invalid(false, REJECT_CONFLICT
, "txn-mempool-conflict");
611 setConflicts
.insert(ptxConflicting
->GetHash());
619 CCoinsViewCache
view(&dummy
);
621 CAmount nValueIn
= 0;
625 CCoinsViewMemPool
viewMemPool(pcoinsTip
, pool
);
626 view
.SetBackend(viewMemPool
);
628 // do we already have it?
629 bool fHadTxInCache
= pcoinsTip
->HaveCoinsInCache(hash
);
630 if (view
.HaveCoins(hash
)) {
632 vHashTxnToUncache
.push_back(hash
);
633 return state
.Invalid(false, REJECT_ALREADY_KNOWN
, "txn-already-known");
636 // do all inputs exist?
637 // Note that this does not check for the presence of actual outputs (see the next check for that),
638 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
639 BOOST_FOREACH(const CTxIn txin
, tx
.vin
) {
640 if (!pcoinsTip
->HaveCoinsInCache(txin
.prevout
.hash
))
641 vHashTxnToUncache
.push_back(txin
.prevout
.hash
);
642 if (!view
.HaveCoins(txin
.prevout
.hash
)) {
644 *pfMissingInputs
= true;
645 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
649 // are the actual inputs available?
650 if (!view
.HaveInputs(tx
))
651 return state
.Invalid(false, REJECT_DUPLICATE
, "bad-txns-inputs-spent");
653 // Bring the best block into scope
656 nValueIn
= view
.GetValueIn(tx
);
658 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
659 view
.SetBackend(dummy
);
661 // Only accept BIP68 sequence locked transactions that can be mined in the next
662 // block; we don't want our mempool filled up with transactions that can't
664 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
665 // CoinsViewCache instead of create its own
666 if (!CheckSequenceLocks(tx
, STANDARD_LOCKTIME_VERIFY_FLAGS
, &lp
))
667 return state
.DoS(0, false, REJECT_NONSTANDARD
, "non-BIP68-final");
670 // Check for non-standard pay-to-script-hash in inputs
671 if (fRequireStandard
&& !AreInputsStandard(tx
, view
))
672 return state
.Invalid(false, REJECT_NONSTANDARD
, "bad-txns-nonstandard-inputs");
674 // Check for non-standard witness in P2WSH
675 if (!tx
.wit
.IsNull() && fRequireStandard
&& !IsWitnessStandard(tx
, view
))
676 return state
.DoS(0, false, REJECT_NONSTANDARD
, "bad-witness-nonstandard", true);
678 int64_t nSigOpsCost
= GetTransactionSigOpCost(tx
, view
, STANDARD_SCRIPT_VERIFY_FLAGS
);
680 CAmount nValueOut
= tx
.GetValueOut();
681 CAmount nFees
= nValueIn
-nValueOut
;
682 // nModifiedFees includes any fee deltas from PrioritiseTransaction
683 CAmount nModifiedFees
= nFees
;
684 double nPriorityDummy
= 0;
685 pool
.ApplyDeltas(hash
, nPriorityDummy
, nModifiedFees
);
687 CAmount inChainInputValue
;
688 double dPriority
= view
.GetPriority(tx
, chainActive
.Height(), inChainInputValue
);
690 // Keep track of transactions that spend a coinbase, which we re-scan
691 // during reorgs to ensure COINBASE_MATURITY is still met.
692 bool fSpendsCoinbase
= false;
693 BOOST_FOREACH(const CTxIn
&txin
, tx
.vin
) {
694 const CCoins
*coins
= view
.AccessCoins(txin
.prevout
.hash
);
695 if (coins
->IsCoinBase()) {
696 fSpendsCoinbase
= true;
701 CTxMemPoolEntry
entry(tx
, nFees
, nAcceptTime
, dPriority
, chainActive
.Height(), pool
.HasNoInputsOf(tx
), inChainInputValue
, fSpendsCoinbase
, nSigOpsCost
, lp
);
702 unsigned int nSize
= entry
.GetTxSize();
704 // Check that the transaction doesn't have an excessive number of
705 // sigops, making it impossible to mine. Since the coinbase transaction
706 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
707 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
708 // merely non-standard transaction.
709 if (nSigOpsCost
> MAX_STANDARD_TX_SIGOPS_COST
)
710 return state
.DoS(0, false, REJECT_NONSTANDARD
, "bad-txns-too-many-sigops", false,
711 strprintf("%d", nSigOpsCost
));
713 CAmount mempoolRejectFee
= pool
.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000).GetFee(nSize
);
714 if (mempoolRejectFee
> 0 && nModifiedFees
< mempoolRejectFee
) {
715 return state
.DoS(0, false, REJECT_INSUFFICIENTFEE
, "mempool min fee not met", false, strprintf("%d < %d", nFees
, mempoolRejectFee
));
716 } else if (GetBoolArg("-relaypriority", DEFAULT_RELAYPRIORITY
) && nModifiedFees
< ::minRelayTxFee
.GetFee(nSize
) && !AllowFree(entry
.GetPriority(chainActive
.Height() + 1))) {
717 // Require that free transactions have sufficient priority to be mined in the next block.
718 return state
.DoS(0, false, REJECT_INSUFFICIENTFEE
, "insufficient priority");
721 // Continuously rate-limit free (really, very-low-fee) transactions
722 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
723 // be annoying or make others' transactions take longer to confirm.
724 if (fLimitFree
&& nModifiedFees
< ::minRelayTxFee
.GetFee(nSize
))
726 static CCriticalSection csFreeLimiter
;
727 static double dFreeCount
;
728 static int64_t nLastTime
;
729 int64_t nNow
= GetTime();
733 // Use an exponentially decaying ~10-minute window:
734 dFreeCount
*= pow(1.0 - 1.0/600.0, (double)(nNow
- nLastTime
));
736 // -limitfreerelay unit is thousand-bytes-per-minute
737 // At default rate it would take over a month to fill 1GB
738 if (dFreeCount
+ nSize
>= GetArg("-limitfreerelay", DEFAULT_LIMITFREERELAY
) * 10 * 1000)
739 return state
.DoS(0, false, REJECT_INSUFFICIENTFEE
, "rate limited free transaction");
740 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount
, dFreeCount
+nSize
);
744 if (nAbsurdFee
&& nFees
> nAbsurdFee
)
745 return state
.Invalid(false,
746 REJECT_HIGHFEE
, "absurdly-high-fee",
747 strprintf("%d > %d", nFees
, nAbsurdFee
));
749 // Calculate in-mempool ancestors, up to a limit.
750 CTxMemPool::setEntries setAncestors
;
751 size_t nLimitAncestors
= GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT
);
752 size_t nLimitAncestorSize
= GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT
)*1000;
753 size_t nLimitDescendants
= GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT
);
754 size_t nLimitDescendantSize
= GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT
)*1000;
755 std::string errString
;
756 if (!pool
.CalculateMemPoolAncestors(entry
, setAncestors
, nLimitAncestors
, nLimitAncestorSize
, nLimitDescendants
, nLimitDescendantSize
, errString
)) {
757 return state
.DoS(0, false, REJECT_NONSTANDARD
, "too-long-mempool-chain", false, errString
);
760 // A transaction that spends outputs that would be replaced by it is invalid. Now
761 // that we have the set of all ancestors we can detect this
762 // pathological case by making sure setConflicts and setAncestors don't
764 BOOST_FOREACH(CTxMemPool::txiter ancestorIt
, setAncestors
)
766 const uint256
&hashAncestor
= ancestorIt
->GetTx().GetHash();
767 if (setConflicts
.count(hashAncestor
))
769 return state
.DoS(10, false,
770 REJECT_INVALID
, "bad-txns-spends-conflicting-tx", false,
771 strprintf("%s spends conflicting transaction %s",
773 hashAncestor
.ToString()));
777 // Check if it's economically rational to mine this transaction rather
778 // than the ones it replaces.
779 CAmount nConflictingFees
= 0;
780 size_t nConflictingSize
= 0;
781 uint64_t nConflictingCount
= 0;
782 CTxMemPool::setEntries allConflicting
;
784 // If we don't hold the lock allConflicting might be incomplete; the
785 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
786 // mempool consistency for us.
788 if (setConflicts
.size())
790 CFeeRate
newFeeRate(nModifiedFees
, nSize
);
791 set
<uint256
> setConflictsParents
;
792 const int maxDescendantsToVisit
= 100;
793 CTxMemPool::setEntries setIterConflicting
;
794 BOOST_FOREACH(const uint256
&hashConflicting
, setConflicts
)
796 CTxMemPool::txiter mi
= pool
.mapTx
.find(hashConflicting
);
797 if (mi
== pool
.mapTx
.end())
800 // Save these to avoid repeated lookups
801 setIterConflicting
.insert(mi
);
803 // Don't allow the replacement to reduce the feerate of the
806 // We usually don't want to accept replacements with lower
807 // feerates than what they replaced as that would lower the
808 // feerate of the next block. Requiring that the feerate always
809 // be increased is also an easy-to-reason about way to prevent
810 // DoS attacks via replacements.
812 // The mining code doesn't (currently) take children into
813 // account (CPFP) so we only consider the feerates of
814 // transactions being directly replaced, not their indirect
815 // descendants. While that does mean high feerate children are
816 // ignored when deciding whether or not to replace, we do
817 // require the replacement to pay more overall fees too,
818 // mitigating most cases.
819 CFeeRate
oldFeeRate(mi
->GetModifiedFee(), mi
->GetTxSize());
820 if (newFeeRate
<= oldFeeRate
)
822 return state
.DoS(0, false,
823 REJECT_INSUFFICIENTFEE
, "insufficient fee", false,
824 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
826 newFeeRate
.ToString(),
827 oldFeeRate
.ToString()));
830 BOOST_FOREACH(const CTxIn
&txin
, mi
->GetTx().vin
)
832 setConflictsParents
.insert(txin
.prevout
.hash
);
835 nConflictingCount
+= mi
->GetCountWithDescendants();
837 // This potentially overestimates the number of actual descendants
838 // but we just want to be conservative to avoid doing too much
840 if (nConflictingCount
<= maxDescendantsToVisit
) {
841 // If not too many to replace, then calculate the set of
842 // transactions that would have to be evicted
843 BOOST_FOREACH(CTxMemPool::txiter it
, setIterConflicting
) {
844 pool
.CalculateDescendants(it
, allConflicting
);
846 BOOST_FOREACH(CTxMemPool::txiter it
, allConflicting
) {
847 nConflictingFees
+= it
->GetModifiedFee();
848 nConflictingSize
+= it
->GetTxSize();
851 return state
.DoS(0, false,
852 REJECT_NONSTANDARD
, "too many potential replacements", false,
853 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
856 maxDescendantsToVisit
));
859 for (unsigned int j
= 0; j
< tx
.vin
.size(); j
++)
861 // We don't want to accept replacements that require low
862 // feerate junk to be mined first. Ideally we'd keep track of
863 // the ancestor feerates and make the decision based on that,
864 // but for now requiring all new inputs to be confirmed works.
865 if (!setConflictsParents
.count(tx
.vin
[j
].prevout
.hash
))
867 // Rather than check the UTXO set - potentially expensive -
868 // it's cheaper to just check if the new input refers to a
869 // tx that's in the mempool.
870 if (pool
.mapTx
.find(tx
.vin
[j
].prevout
.hash
) != pool
.mapTx
.end())
871 return state
.DoS(0, false,
872 REJECT_NONSTANDARD
, "replacement-adds-unconfirmed", false,
873 strprintf("replacement %s adds unconfirmed input, idx %d",
874 hash
.ToString(), j
));
878 // The replacement must pay greater fees than the transactions it
879 // replaces - if we did the bandwidth used by those conflicting
880 // transactions would not be paid for.
881 if (nModifiedFees
< nConflictingFees
)
883 return state
.DoS(0, false,
884 REJECT_INSUFFICIENTFEE
, "insufficient fee", false,
885 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
886 hash
.ToString(), FormatMoney(nModifiedFees
), FormatMoney(nConflictingFees
)));
889 // Finally in addition to paying more fees than the conflicts the
890 // new transaction must pay for its own bandwidth.
891 CAmount nDeltaFees
= nModifiedFees
- nConflictingFees
;
892 if (nDeltaFees
< ::minRelayTxFee
.GetFee(nSize
))
894 return state
.DoS(0, false,
895 REJECT_INSUFFICIENTFEE
, "insufficient fee", false,
896 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
898 FormatMoney(nDeltaFees
),
899 FormatMoney(::minRelayTxFee
.GetFee(nSize
))));
903 unsigned int scriptVerifyFlags
= STANDARD_SCRIPT_VERIFY_FLAGS
;
904 if (!Params().RequireStandard()) {
905 scriptVerifyFlags
= GetArg("-promiscuousmempoolflags", scriptVerifyFlags
);
908 // Check against previous transactions
909 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
910 PrecomputedTransactionData
txdata(tx
);
911 if (!CheckInputs(tx
, state
, view
, true, scriptVerifyFlags
, true, txdata
)) {
912 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
913 // need to turn both off, and compare against just turning off CLEANSTACK
914 // to see if the failure is specifically due to witness validation.
915 if (tx
.wit
.IsNull() && CheckInputs(tx
, state
, view
, true, scriptVerifyFlags
& ~(SCRIPT_VERIFY_WITNESS
| SCRIPT_VERIFY_CLEANSTACK
), true, txdata
) &&
916 !CheckInputs(tx
, state
, view
, true, scriptVerifyFlags
& ~SCRIPT_VERIFY_CLEANSTACK
, true, txdata
)) {
917 // Only the witness is missing, so the transaction itself may be fine.
918 state
.SetCorruptionPossible();
923 // Check again against just the consensus-critical mandatory script
924 // verification flags, in case of bugs in the standard flags that cause
925 // transactions to pass as valid when they're actually invalid. For
926 // instance the STRICTENC flag was incorrectly allowing certain
927 // CHECKSIG NOT scripts to pass, even though they were invalid.
929 // There is a similar check in CreateNewBlock() to prevent creating
930 // invalid blocks, however allowing such transactions into the mempool
931 // can be exploited as a DoS attack.
932 if (!CheckInputs(tx
, state
, view
, true, MANDATORY_SCRIPT_VERIFY_FLAGS
, true, txdata
))
934 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
935 __func__
, hash
.ToString(), FormatStateMessage(state
));
938 // Remove conflicting transactions from the mempool
939 BOOST_FOREACH(const CTxMemPool::txiter it
, allConflicting
)
941 LogPrint("mempool", "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
942 it
->GetTx().GetHash().ToString(),
944 FormatMoney(nModifiedFees
- nConflictingFees
),
945 (int)nSize
- (int)nConflictingSize
);
947 pool
.RemoveStaged(allConflicting
, false);
949 // Store transaction in memory
950 pool
.addUnchecked(hash
, entry
, setAncestors
, !IsInitialBlockDownload());
952 // trim mempool and check if tx was trimmed
953 if (!fOverrideMempoolLimit
) {
954 LimitMempoolSize(pool
, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY
) * 60 * 60);
955 if (!pool
.exists(hash
))
956 return state
.DoS(0, false, REJECT_INSUFFICIENTFEE
, "mempool full");
960 GetMainSignals().SyncTransaction(tx
, NULL
, CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK
);
965 bool AcceptToMemoryPoolWithTime(CTxMemPool
& pool
, CValidationState
&state
, const CTransaction
&tx
, bool fLimitFree
,
966 bool* pfMissingInputs
, int64_t nAcceptTime
, bool fOverrideMempoolLimit
, const CAmount nAbsurdFee
)
968 std::vector
<uint256
> vHashTxToUncache
;
969 bool res
= AcceptToMemoryPoolWorker(pool
, state
, tx
, fLimitFree
, pfMissingInputs
, nAcceptTime
, fOverrideMempoolLimit
, nAbsurdFee
, vHashTxToUncache
);
971 BOOST_FOREACH(const uint256
& hashTx
, vHashTxToUncache
)
972 pcoinsTip
->Uncache(hashTx
);
974 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
975 CValidationState stateDummy
;
976 FlushStateToDisk(stateDummy
, FLUSH_STATE_PERIODIC
);
980 bool AcceptToMemoryPool(CTxMemPool
& pool
, CValidationState
&state
, const CTransaction
&tx
, bool fLimitFree
,
981 bool* pfMissingInputs
, bool fOverrideMempoolLimit
, const CAmount nAbsurdFee
)
983 return AcceptToMemoryPoolWithTime(pool
, state
, tx
, fLimitFree
, pfMissingInputs
, GetTime(), fOverrideMempoolLimit
, nAbsurdFee
);
986 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
987 bool GetTransaction(const uint256
&hash
, CTransactionRef
&txOut
, const Consensus::Params
& consensusParams
, uint256
&hashBlock
, bool fAllowSlow
)
989 CBlockIndex
*pindexSlow
= NULL
;
993 CTransactionRef ptx
= mempool
.get(hash
);
1002 if (pblocktree
->ReadTxIndex(hash
, postx
)) {
1003 CAutoFile
file(OpenBlockFile(postx
, true), SER_DISK
, CLIENT_VERSION
);
1005 return error("%s: OpenBlockFile failed", __func__
);
1006 CBlockHeader header
;
1009 fseek(file
.Get(), postx
.nTxOffset
, SEEK_CUR
);
1011 } catch (const std::exception
& e
) {
1012 return error("%s: Deserialize or I/O error - %s", __func__
, e
.what());
1014 hashBlock
= header
.GetHash();
1015 if (txOut
->GetHash() != hash
)
1016 return error("%s: txid mismatch", __func__
);
1021 if (fAllowSlow
) { // use coin database to locate block that contains transaction, and scan it
1024 const CCoinsViewCache
& view
= *pcoinsTip
;
1025 const CCoins
* coins
= view
.AccessCoins(hash
);
1027 nHeight
= coins
->nHeight
;
1030 pindexSlow
= chainActive
[nHeight
];
1035 if (ReadBlockFromDisk(block
, pindexSlow
, consensusParams
)) {
1036 for (const auto& tx
: block
.vtx
) {
1037 if (tx
->GetHash() == hash
) {
1039 hashBlock
= pindexSlow
->GetBlockHash();
1054 //////////////////////////////////////////////////////////////////////////////
1056 // CBlock and CBlockIndex
1059 bool WriteBlockToDisk(const CBlock
& block
, CDiskBlockPos
& pos
, const CMessageHeader::MessageStartChars
& messageStart
)
1061 // Open history file to append
1062 CAutoFile
fileout(OpenBlockFile(pos
), SER_DISK
, CLIENT_VERSION
);
1063 if (fileout
.IsNull())
1064 return error("WriteBlockToDisk: OpenBlockFile failed");
1066 // Write index header
1067 unsigned int nSize
= GetSerializeSize(fileout
, block
);
1068 fileout
<< FLATDATA(messageStart
) << nSize
;
1071 long fileOutPos
= ftell(fileout
.Get());
1073 return error("WriteBlockToDisk: ftell failed");
1074 pos
.nPos
= (unsigned int)fileOutPos
;
1080 bool ReadBlockFromDisk(CBlock
& block
, const CDiskBlockPos
& pos
, const Consensus::Params
& consensusParams
)
1084 // Open history file to read
1085 CAutoFile
filein(OpenBlockFile(pos
, true), SER_DISK
, CLIENT_VERSION
);
1086 if (filein
.IsNull())
1087 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos
.ToString());
1093 catch (const std::exception
& e
) {
1094 return error("%s: Deserialize or I/O error - %s at %s", __func__
, e
.what(), pos
.ToString());
1098 if (!CheckProofOfWork(block
.GetHash(), block
.nBits
, consensusParams
))
1099 return error("ReadBlockFromDisk: Errors in block header at %s", pos
.ToString());
1104 bool ReadBlockFromDisk(CBlock
& block
, const CBlockIndex
* pindex
, const Consensus::Params
& consensusParams
)
1106 if (!ReadBlockFromDisk(block
, pindex
->GetBlockPos(), consensusParams
))
1108 if (block
.GetHash() != pindex
->GetBlockHash())
1109 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1110 pindex
->ToString(), pindex
->GetBlockPos().ToString());
1114 CAmount
GetBlockSubsidy(int nHeight
, const Consensus::Params
& consensusParams
)
1116 int halvings
= nHeight
/ consensusParams
.nSubsidyHalvingInterval
;
1117 // Force block reward to zero when right shift is undefined.
1121 CAmount nSubsidy
= 50 * COIN
;
1122 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1123 nSubsidy
>>= halvings
;
1127 bool IsInitialBlockDownload()
1129 const CChainParams
& chainParams
= Params();
1131 // Once this function has returned false, it must remain false.
1132 static std::atomic
<bool> latchToFalse
{false};
1133 // Optimization: pre-test latch before taking the lock.
1134 if (latchToFalse
.load(std::memory_order_relaxed
))
1138 if (latchToFalse
.load(std::memory_order_relaxed
))
1140 if (fImporting
|| fReindex
)
1142 if (chainActive
.Tip() == NULL
)
1144 if (chainActive
.Tip()->nChainWork
< UintToArith256(chainParams
.GetConsensus().nMinimumChainWork
))
1146 if (chainActive
.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge
))
1148 latchToFalse
.store(true, std::memory_order_relaxed
);
1152 bool fLargeWorkForkFound
= false;
1153 bool fLargeWorkInvalidChainFound
= false;
1154 CBlockIndex
*pindexBestForkTip
= NULL
, *pindexBestForkBase
= NULL
;
1156 static void AlertNotify(const std::string
& strMessage
)
1158 uiInterface
.NotifyAlertChanged();
1159 std::string strCmd
= GetArg("-alertnotify", "");
1160 if (strCmd
.empty()) return;
1162 // Alert text should be plain ascii coming from a trusted source, but to
1163 // be safe we first strip anything not in safeChars, then add single quotes around
1164 // the whole string before passing it to the shell:
1165 std::string
singleQuote("'");
1166 std::string safeStatus
= SanitizeString(strMessage
);
1167 safeStatus
= singleQuote
+safeStatus
+singleQuote
;
1168 boost::replace_all(strCmd
, "%s", safeStatus
);
1170 boost::thread
t(runCommand
, strCmd
); // thread runs free
1173 void CheckForkWarningConditions()
1175 AssertLockHeld(cs_main
);
1176 // Before we get past initial download, we cannot reliably alert about forks
1177 // (we assume we don't get stuck on a fork before finishing our initial sync)
1178 if (IsInitialBlockDownload())
1181 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1182 // of our head, drop it
1183 if (pindexBestForkTip
&& chainActive
.Height() - pindexBestForkTip
->nHeight
>= 72)
1184 pindexBestForkTip
= NULL
;
1186 if (pindexBestForkTip
|| (pindexBestInvalid
&& pindexBestInvalid
->nChainWork
> chainActive
.Tip()->nChainWork
+ (GetBlockProof(*chainActive
.Tip()) * 6)))
1188 if (!fLargeWorkForkFound
&& pindexBestForkBase
)
1190 std::string warning
= std::string("'Warning: Large-work fork detected, forking after block ") +
1191 pindexBestForkBase
->phashBlock
->ToString() + std::string("'");
1192 AlertNotify(warning
);
1194 if (pindexBestForkTip
&& pindexBestForkBase
)
1196 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__
,
1197 pindexBestForkBase
->nHeight
, pindexBestForkBase
->phashBlock
->ToString(),
1198 pindexBestForkTip
->nHeight
, pindexBestForkTip
->phashBlock
->ToString());
1199 fLargeWorkForkFound
= true;
1203 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__
);
1204 fLargeWorkInvalidChainFound
= true;
1209 fLargeWorkForkFound
= false;
1210 fLargeWorkInvalidChainFound
= false;
1214 void CheckForkWarningConditionsOnNewFork(CBlockIndex
* pindexNewForkTip
)
1216 AssertLockHeld(cs_main
);
1217 // If we are on a fork that is sufficiently large, set a warning flag
1218 CBlockIndex
* pfork
= pindexNewForkTip
;
1219 CBlockIndex
* plonger
= chainActive
.Tip();
1220 while (pfork
&& pfork
!= plonger
)
1222 while (plonger
&& plonger
->nHeight
> pfork
->nHeight
)
1223 plonger
= plonger
->pprev
;
1224 if (pfork
== plonger
)
1226 pfork
= pfork
->pprev
;
1229 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1230 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1231 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1232 // hash rate operating on the fork.
1233 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1234 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1235 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1236 if (pfork
&& (!pindexBestForkTip
|| (pindexBestForkTip
&& pindexNewForkTip
->nHeight
> pindexBestForkTip
->nHeight
)) &&
1237 pindexNewForkTip
->nChainWork
- pfork
->nChainWork
> (GetBlockProof(*pfork
) * 7) &&
1238 chainActive
.Height() - pindexNewForkTip
->nHeight
< 72)
1240 pindexBestForkTip
= pindexNewForkTip
;
1241 pindexBestForkBase
= pfork
;
1244 CheckForkWarningConditions();
1247 void static InvalidChainFound(CBlockIndex
* pindexNew
)
1249 if (!pindexBestInvalid
|| pindexNew
->nChainWork
> pindexBestInvalid
->nChainWork
)
1250 pindexBestInvalid
= pindexNew
;
1252 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__
,
1253 pindexNew
->GetBlockHash().ToString(), pindexNew
->nHeight
,
1254 log(pindexNew
->nChainWork
.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1255 pindexNew
->GetBlockTime()));
1256 CBlockIndex
*tip
= chainActive
.Tip();
1258 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__
,
1259 tip
->GetBlockHash().ToString(), chainActive
.Height(), log(tip
->nChainWork
.getdouble())/log(2.0),
1260 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip
->GetBlockTime()));
1261 CheckForkWarningConditions();
1264 void static InvalidBlockFound(CBlockIndex
*pindex
, const CValidationState
&state
) {
1265 if (!state
.CorruptionPossible()) {
1266 pindex
->nStatus
|= BLOCK_FAILED_VALID
;
1267 setDirtyBlockIndex
.insert(pindex
);
1268 setBlockIndexCandidates
.erase(pindex
);
1269 InvalidChainFound(pindex
);
1273 void UpdateCoins(const CTransaction
& tx
, CCoinsViewCache
& inputs
, CTxUndo
&txundo
, int nHeight
)
1275 // mark inputs spent
1276 if (!tx
.IsCoinBase()) {
1277 txundo
.vprevout
.reserve(tx
.vin
.size());
1278 BOOST_FOREACH(const CTxIn
&txin
, tx
.vin
) {
1279 CCoinsModifier coins
= inputs
.ModifyCoins(txin
.prevout
.hash
);
1280 unsigned nPos
= txin
.prevout
.n
;
1282 if (nPos
>= coins
->vout
.size() || coins
->vout
[nPos
].IsNull())
1284 // mark an outpoint spent, and construct undo information
1285 txundo
.vprevout
.push_back(CTxInUndo(coins
->vout
[nPos
]));
1287 if (coins
->vout
.size() == 0) {
1288 CTxInUndo
& undo
= txundo
.vprevout
.back();
1289 undo
.nHeight
= coins
->nHeight
;
1290 undo
.fCoinBase
= coins
->fCoinBase
;
1291 undo
.nVersion
= coins
->nVersion
;
1296 inputs
.ModifyNewCoins(tx
.GetHash(), tx
.IsCoinBase())->FromTx(tx
, nHeight
);
1299 void UpdateCoins(const CTransaction
& tx
, CCoinsViewCache
& inputs
, int nHeight
)
1302 UpdateCoins(tx
, inputs
, txundo
, nHeight
);
1305 bool CScriptCheck::operator()() {
1306 const CScript
&scriptSig
= ptxTo
->vin
[nIn
].scriptSig
;
1307 const CScriptWitness
*witness
= (nIn
< ptxTo
->wit
.vtxinwit
.size()) ? &ptxTo
->wit
.vtxinwit
[nIn
].scriptWitness
: NULL
;
1308 if (!VerifyScript(scriptSig
, scriptPubKey
, witness
, nFlags
, CachingTransactionSignatureChecker(ptxTo
, nIn
, amount
, cacheStore
, *txdata
), &error
)) {
1314 int GetSpendHeight(const CCoinsViewCache
& inputs
)
1317 CBlockIndex
* pindexPrev
= mapBlockIndex
.find(inputs
.GetBestBlock())->second
;
1318 return pindexPrev
->nHeight
+ 1;
1321 namespace Consensus
{
1322 bool CheckTxInputs(const CTransaction
& tx
, CValidationState
& state
, const CCoinsViewCache
& inputs
, int nSpendHeight
)
1324 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1325 // for an attacker to attempt to split the network.
1326 if (!inputs
.HaveInputs(tx
))
1327 return state
.Invalid(false, 0, "", "Inputs unavailable");
1329 CAmount nValueIn
= 0;
1331 for (unsigned int i
= 0; i
< tx
.vin
.size(); i
++)
1333 const COutPoint
&prevout
= tx
.vin
[i
].prevout
;
1334 const CCoins
*coins
= inputs
.AccessCoins(prevout
.hash
);
1337 // If prev is coinbase, check that it's matured
1338 if (coins
->IsCoinBase()) {
1339 if (nSpendHeight
- coins
->nHeight
< COINBASE_MATURITY
)
1340 return state
.Invalid(false,
1341 REJECT_INVALID
, "bad-txns-premature-spend-of-coinbase",
1342 strprintf("tried to spend coinbase at depth %d", nSpendHeight
- coins
->nHeight
));
1345 // Check for negative or overflow input values
1346 nValueIn
+= coins
->vout
[prevout
.n
].nValue
;
1347 if (!MoneyRange(coins
->vout
[prevout
.n
].nValue
) || !MoneyRange(nValueIn
))
1348 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-inputvalues-outofrange");
1352 if (nValueIn
< tx
.GetValueOut())
1353 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-in-belowout", false,
1354 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn
), FormatMoney(tx
.GetValueOut())));
1356 // Tally transaction fees
1357 CAmount nTxFee
= nValueIn
- tx
.GetValueOut();
1359 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-fee-negative");
1361 if (!MoneyRange(nFees
))
1362 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-fee-outofrange");
1365 }// namespace Consensus
1367 bool CheckInputs(const CTransaction
& tx
, CValidationState
&state
, const CCoinsViewCache
&inputs
, bool fScriptChecks
, unsigned int flags
, bool cacheStore
, PrecomputedTransactionData
& txdata
, std::vector
<CScriptCheck
> *pvChecks
)
1369 if (!tx
.IsCoinBase())
1371 if (!Consensus::CheckTxInputs(tx
, state
, inputs
, GetSpendHeight(inputs
)))
1375 pvChecks
->reserve(tx
.vin
.size());
1377 // The first loop above does all the inexpensive checks.
1378 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1379 // Helps prevent CPU exhaustion attacks.
1381 // Skip ECDSA signature verification when connecting blocks before the
1382 // last block chain checkpoint. Assuming the checkpoints are valid this
1383 // is safe because block merkle hashes are still computed and checked,
1384 // and any change will be caught at the next checkpoint. Of course, if
1385 // the checkpoint is for a chain that's invalid due to false scriptSigs
1386 // this optimization would allow an invalid chain to be accepted.
1387 if (fScriptChecks
) {
1388 for (unsigned int i
= 0; i
< tx
.vin
.size(); i
++) {
1389 const COutPoint
&prevout
= tx
.vin
[i
].prevout
;
1390 const CCoins
* coins
= inputs
.AccessCoins(prevout
.hash
);
1394 CScriptCheck
check(*coins
, tx
, i
, flags
, cacheStore
, &txdata
);
1396 pvChecks
->push_back(CScriptCheck());
1397 check
.swap(pvChecks
->back());
1398 } else if (!check()) {
1399 if (flags
& STANDARD_NOT_MANDATORY_VERIFY_FLAGS
) {
1400 // Check whether the failure was caused by a
1401 // non-mandatory script verification check, such as
1402 // non-standard DER encodings or non-null dummy
1403 // arguments; if so, don't trigger DoS protection to
1404 // avoid splitting the network between upgraded and
1405 // non-upgraded nodes.
1406 CScriptCheck
check2(*coins
, tx
, i
,
1407 flags
& ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS
, cacheStore
, &txdata
);
1409 return state
.Invalid(false, REJECT_NONSTANDARD
, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check
.GetScriptError())));
1411 // Failures of other flags indicate a transaction that is
1412 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1413 // such nodes as they are not following the protocol. That
1414 // said during an upgrade careful thought should be taken
1415 // as to the correct behavior - we may want to continue
1416 // peering with non-upgraded nodes even after soft-fork
1417 // super-majority signaling has occurred.
1418 return state
.DoS(100,false, REJECT_INVALID
, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check
.GetScriptError())));
1429 bool UndoWriteToDisk(const CBlockUndo
& blockundo
, CDiskBlockPos
& pos
, const uint256
& hashBlock
, const CMessageHeader::MessageStartChars
& messageStart
)
1431 // Open history file to append
1432 CAutoFile
fileout(OpenUndoFile(pos
), SER_DISK
, CLIENT_VERSION
);
1433 if (fileout
.IsNull())
1434 return error("%s: OpenUndoFile failed", __func__
);
1436 // Write index header
1437 unsigned int nSize
= GetSerializeSize(fileout
, blockundo
);
1438 fileout
<< FLATDATA(messageStart
) << nSize
;
1441 long fileOutPos
= ftell(fileout
.Get());
1443 return error("%s: ftell failed", __func__
);
1444 pos
.nPos
= (unsigned int)fileOutPos
;
1445 fileout
<< blockundo
;
1447 // calculate & write checksum
1448 CHashWriter
hasher(SER_GETHASH
, PROTOCOL_VERSION
);
1449 hasher
<< hashBlock
;
1450 hasher
<< blockundo
;
1451 fileout
<< hasher
.GetHash();
1456 bool UndoReadFromDisk(CBlockUndo
& blockundo
, const CDiskBlockPos
& pos
, const uint256
& hashBlock
)
1458 // Open history file to read
1459 CAutoFile
filein(OpenUndoFile(pos
, true), SER_DISK
, CLIENT_VERSION
);
1460 if (filein
.IsNull())
1461 return error("%s: OpenUndoFile failed", __func__
);
1464 uint256 hashChecksum
;
1466 filein
>> blockundo
;
1467 filein
>> hashChecksum
;
1469 catch (const std::exception
& e
) {
1470 return error("%s: Deserialize or I/O error - %s", __func__
, e
.what());
1474 CHashWriter
hasher(SER_GETHASH
, PROTOCOL_VERSION
);
1475 hasher
<< hashBlock
;
1476 hasher
<< blockundo
;
1477 if (hashChecksum
!= hasher
.GetHash())
1478 return error("%s: Checksum mismatch", __func__
);
1483 /** Abort with a message */
1484 bool AbortNode(const std::string
& strMessage
, const std::string
& userMessage
="")
1486 strMiscWarning
= strMessage
;
1487 LogPrintf("*** %s\n", strMessage
);
1488 uiInterface
.ThreadSafeMessageBox(
1489 userMessage
.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage
,
1490 "", CClientUIInterface::MSG_ERROR
);
1495 bool AbortNode(CValidationState
& state
, const std::string
& strMessage
, const std::string
& userMessage
="")
1497 AbortNode(strMessage
, userMessage
);
1498 return state
.Error(strMessage
);
1504 * Apply the undo operation of a CTxInUndo to the given chain state.
1505 * @param undo The undo object.
1506 * @param view The coins view to which to apply the changes.
1507 * @param out The out point that corresponds to the tx input.
1508 * @return True on success.
1510 static bool ApplyTxInUndo(const CTxInUndo
& undo
, CCoinsViewCache
& view
, const COutPoint
& out
)
1514 CCoinsModifier coins
= view
.ModifyCoins(out
.hash
);
1515 if (undo
.nHeight
!= 0) {
1516 // undo data contains height: this is the last output of the prevout tx being spent
1517 if (!coins
->IsPruned())
1518 fClean
= fClean
&& error("%s: undo data overwriting existing transaction", __func__
);
1520 coins
->fCoinBase
= undo
.fCoinBase
;
1521 coins
->nHeight
= undo
.nHeight
;
1522 coins
->nVersion
= undo
.nVersion
;
1524 if (coins
->IsPruned())
1525 fClean
= fClean
&& error("%s: undo data adding output to missing transaction", __func__
);
1527 if (coins
->IsAvailable(out
.n
))
1528 fClean
= fClean
&& error("%s: undo data overwriting existing output", __func__
);
1529 if (coins
->vout
.size() < out
.n
+1)
1530 coins
->vout
.resize(out
.n
+1);
1531 coins
->vout
[out
.n
] = undo
.txout
;
1536 bool DisconnectBlock(const CBlock
& block
, CValidationState
& state
, const CBlockIndex
* pindex
, CCoinsViewCache
& view
, bool* pfClean
)
1538 assert(pindex
->GetBlockHash() == view
.GetBestBlock());
1545 CBlockUndo blockUndo
;
1546 CDiskBlockPos pos
= pindex
->GetUndoPos();
1548 return error("DisconnectBlock(): no undo data available");
1549 if (!UndoReadFromDisk(blockUndo
, pos
, pindex
->pprev
->GetBlockHash()))
1550 return error("DisconnectBlock(): failure reading undo data");
1552 if (blockUndo
.vtxundo
.size() + 1 != block
.vtx
.size())
1553 return error("DisconnectBlock(): block and undo data inconsistent");
1555 // undo transactions in reverse order
1556 for (int i
= block
.vtx
.size() - 1; i
>= 0; i
--) {
1557 const CTransaction
&tx
= *(block
.vtx
[i
]);
1558 uint256 hash
= tx
.GetHash();
1560 // Check that all outputs are available and match the outputs in the block itself
1563 CCoinsModifier outs
= view
.ModifyCoins(hash
);
1564 outs
->ClearUnspendable();
1566 CCoins
outsBlock(tx
, pindex
->nHeight
);
1567 // The CCoins serialization does not serialize negative numbers.
1568 // No network rules currently depend on the version here, so an inconsistency is harmless
1569 // but it must be corrected before txout nversion ever influences a network rule.
1570 if (outsBlock
.nVersion
< 0)
1571 outs
->nVersion
= outsBlock
.nVersion
;
1572 if (*outs
!= outsBlock
)
1573 fClean
= fClean
&& error("DisconnectBlock(): added transaction mismatch? database corrupted");
1580 if (i
> 0) { // not coinbases
1581 const CTxUndo
&txundo
= blockUndo
.vtxundo
[i
-1];
1582 if (txundo
.vprevout
.size() != tx
.vin
.size())
1583 return error("DisconnectBlock(): transaction and undo data inconsistent");
1584 for (unsigned int j
= tx
.vin
.size(); j
-- > 0;) {
1585 const COutPoint
&out
= tx
.vin
[j
].prevout
;
1586 const CTxInUndo
&undo
= txundo
.vprevout
[j
];
1587 if (!ApplyTxInUndo(undo
, view
, out
))
1593 // move best block pointer to prevout block
1594 view
.SetBestBlock(pindex
->pprev
->GetBlockHash());
1604 void static FlushBlockFile(bool fFinalize
= false)
1606 LOCK(cs_LastBlockFile
);
1608 CDiskBlockPos
posOld(nLastBlockFile
, 0);
1610 FILE *fileOld
= OpenBlockFile(posOld
);
1613 TruncateFile(fileOld
, vinfoBlockFile
[nLastBlockFile
].nSize
);
1614 FileCommit(fileOld
);
1618 fileOld
= OpenUndoFile(posOld
);
1621 TruncateFile(fileOld
, vinfoBlockFile
[nLastBlockFile
].nUndoSize
);
1622 FileCommit(fileOld
);
1627 bool FindUndoPos(CValidationState
&state
, int nFile
, CDiskBlockPos
&pos
, unsigned int nAddSize
);
1629 static CCheckQueue
<CScriptCheck
> scriptcheckqueue(128);
1631 void ThreadScriptCheck() {
1632 RenameThread("bitcoin-scriptch");
1633 scriptcheckqueue
.Thread();
1636 // Protected by cs_main
1637 VersionBitsCache versionbitscache
;
1639 int32_t ComputeBlockVersion(const CBlockIndex
* pindexPrev
, const Consensus::Params
& params
)
1642 int32_t nVersion
= VERSIONBITS_TOP_BITS
;
1644 for (int i
= 0; i
< (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS
; i
++) {
1645 ThresholdState state
= VersionBitsState(pindexPrev
, params
, (Consensus::DeploymentPos
)i
, versionbitscache
);
1646 if (state
== THRESHOLD_LOCKED_IN
|| state
== THRESHOLD_STARTED
) {
1647 nVersion
|= VersionBitsMask(params
, (Consensus::DeploymentPos
)i
);
1655 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1657 class WarningBitsConditionChecker
: public AbstractThresholdConditionChecker
1663 WarningBitsConditionChecker(int bitIn
) : bit(bitIn
) {}
1665 int64_t BeginTime(const Consensus::Params
& params
) const { return 0; }
1666 int64_t EndTime(const Consensus::Params
& params
) const { return std::numeric_limits
<int64_t>::max(); }
1667 int Period(const Consensus::Params
& params
) const { return params
.nMinerConfirmationWindow
; }
1668 int Threshold(const Consensus::Params
& params
) const { return params
.nRuleChangeActivationThreshold
; }
1670 bool Condition(const CBlockIndex
* pindex
, const Consensus::Params
& params
) const
1672 return ((pindex
->nVersion
& VERSIONBITS_TOP_MASK
) == VERSIONBITS_TOP_BITS
) &&
1673 ((pindex
->nVersion
>> bit
) & 1) != 0 &&
1674 ((ComputeBlockVersion(pindex
->pprev
, params
) >> bit
) & 1) == 0;
1678 // Protected by cs_main
1679 static ThresholdConditionCache warningcache
[VERSIONBITS_NUM_BITS
];
1681 static int64_t nTimeCheck
= 0;
1682 static int64_t nTimeForks
= 0;
1683 static int64_t nTimeVerify
= 0;
1684 static int64_t nTimeConnect
= 0;
1685 static int64_t nTimeIndex
= 0;
1686 static int64_t nTimeCallbacks
= 0;
1687 static int64_t nTimeTotal
= 0;
1689 bool ConnectBlock(const CBlock
& block
, CValidationState
& state
, CBlockIndex
* pindex
,
1690 CCoinsViewCache
& view
, const CChainParams
& chainparams
, bool fJustCheck
)
1692 AssertLockHeld(cs_main
);
1694 int64_t nTimeStart
= GetTimeMicros();
1696 // Check it again in case a previous version let a bad block in
1697 if (!CheckBlock(block
, state
, chainparams
.GetConsensus(), !fJustCheck
, !fJustCheck
))
1698 return error("%s: Consensus::CheckBlock: %s", __func__
, FormatStateMessage(state
));
1700 // verify that the view's current state corresponds to the previous block
1701 uint256 hashPrevBlock
= pindex
->pprev
== NULL
? uint256() : pindex
->pprev
->GetBlockHash();
1702 assert(hashPrevBlock
== view
.GetBestBlock());
1704 // Special case for the genesis block, skipping connection of its transactions
1705 // (its coinbase is unspendable)
1706 if (block
.GetHash() == chainparams
.GetConsensus().hashGenesisBlock
) {
1708 view
.SetBestBlock(pindex
->GetBlockHash());
1712 bool fScriptChecks
= true;
1713 if (fCheckpointsEnabled
) {
1714 CBlockIndex
*pindexLastCheckpoint
= Checkpoints::GetLastCheckpoint(chainparams
.Checkpoints());
1715 if (pindexLastCheckpoint
&& pindexLastCheckpoint
->GetAncestor(pindex
->nHeight
) == pindex
) {
1716 // This block is an ancestor of a checkpoint: disable script checks
1717 fScriptChecks
= false;
1721 int64_t nTime1
= GetTimeMicros(); nTimeCheck
+= nTime1
- nTimeStart
;
1722 LogPrint("bench", " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1
- nTimeStart
), nTimeCheck
* 0.000001);
1724 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1725 // unless those are already completely spent.
1726 // If such overwrites are allowed, coinbases and transactions depending upon those
1727 // can be duplicated to remove the ability to spend the first instance -- even after
1728 // being sent to another address.
1729 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1730 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1731 // already refuses previously-known transaction ids entirely.
1732 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1733 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1734 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1735 // initial block download.
1736 bool fEnforceBIP30
= (!pindex
->phashBlock
) || // Enforce on CreateNewBlock invocations which don't have a hash.
1737 !((pindex
->nHeight
==91842 && pindex
->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1738 (pindex
->nHeight
==91880 && pindex
->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1740 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1741 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1742 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1743 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1744 // duplicate transactions descending from the known pairs either.
1745 // 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.
1746 CBlockIndex
*pindexBIP34height
= pindex
->pprev
->GetAncestor(chainparams
.GetConsensus().BIP34Height
);
1747 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1748 fEnforceBIP30
= fEnforceBIP30
&& (!pindexBIP34height
|| !(pindexBIP34height
->GetBlockHash() == chainparams
.GetConsensus().BIP34Hash
));
1750 if (fEnforceBIP30
) {
1751 for (const auto& tx
: block
.vtx
) {
1752 const CCoins
* coins
= view
.AccessCoins(tx
->GetHash());
1753 if (coins
&& !coins
->IsPruned())
1754 return state
.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1755 REJECT_INVALID
, "bad-txns-BIP30");
1759 // BIP16 didn't become active until Apr 1 2012
1760 int64_t nBIP16SwitchTime
= 1333238400;
1761 bool fStrictPayToScriptHash
= (pindex
->GetBlockTime() >= nBIP16SwitchTime
);
1763 unsigned int flags
= fStrictPayToScriptHash
? SCRIPT_VERIFY_P2SH
: SCRIPT_VERIFY_NONE
;
1765 // Start enforcing the DERSIG (BIP66) rule
1766 if (pindex
->nHeight
>= chainparams
.GetConsensus().BIP66Height
) {
1767 flags
|= SCRIPT_VERIFY_DERSIG
;
1770 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1771 if (pindex
->nHeight
>= chainparams
.GetConsensus().BIP65Height
) {
1772 flags
|= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
;
1775 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1776 int nLockTimeFlags
= 0;
1777 if (VersionBitsState(pindex
->pprev
, chainparams
.GetConsensus(), Consensus::DEPLOYMENT_CSV
, versionbitscache
) == THRESHOLD_ACTIVE
) {
1778 flags
|= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
;
1779 nLockTimeFlags
|= LOCKTIME_VERIFY_SEQUENCE
;
1782 // Start enforcing WITNESS rules using versionbits logic.
1783 if (IsWitnessEnabled(pindex
->pprev
, chainparams
.GetConsensus())) {
1784 flags
|= SCRIPT_VERIFY_WITNESS
;
1785 flags
|= SCRIPT_VERIFY_NULLDUMMY
;
1788 int64_t nTime2
= GetTimeMicros(); nTimeForks
+= nTime2
- nTime1
;
1789 LogPrint("bench", " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2
- nTime1
), nTimeForks
* 0.000001);
1791 CBlockUndo blockundo
;
1793 CCheckQueueControl
<CScriptCheck
> control(fScriptChecks
&& nScriptCheckThreads
? &scriptcheckqueue
: NULL
);
1795 std::vector
<int> prevheights
;
1798 int64_t nSigOpsCost
= 0;
1799 CDiskTxPos
pos(pindex
->GetBlockPos(), GetSizeOfCompactSize(block
.vtx
.size()));
1800 std::vector
<std::pair
<uint256
, CDiskTxPos
> > vPos
;
1801 vPos
.reserve(block
.vtx
.size());
1802 blockundo
.vtxundo
.reserve(block
.vtx
.size() - 1);
1803 std::vector
<PrecomputedTransactionData
> txdata
;
1804 txdata
.reserve(block
.vtx
.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1805 for (unsigned int i
= 0; i
< block
.vtx
.size(); i
++)
1807 const CTransaction
&tx
= *(block
.vtx
[i
]);
1809 nInputs
+= tx
.vin
.size();
1811 if (!tx
.IsCoinBase())
1813 if (!view
.HaveInputs(tx
))
1814 return state
.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1815 REJECT_INVALID
, "bad-txns-inputs-missingorspent");
1817 // Check that transaction is BIP68 final
1818 // BIP68 lock checks (as opposed to nLockTime checks) must
1819 // be in ConnectBlock because they require the UTXO set
1820 prevheights
.resize(tx
.vin
.size());
1821 for (size_t j
= 0; j
< tx
.vin
.size(); j
++) {
1822 prevheights
[j
] = view
.AccessCoins(tx
.vin
[j
].prevout
.hash
)->nHeight
;
1825 if (!SequenceLocks(tx
, nLockTimeFlags
, &prevheights
, *pindex
)) {
1826 return state
.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__
),
1827 REJECT_INVALID
, "bad-txns-nonfinal");
1831 // GetTransactionSigOpCost counts 3 types of sigops:
1832 // * legacy (always)
1833 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1834 // * witness (when witness enabled in flags and excludes coinbase)
1835 nSigOpsCost
+= GetTransactionSigOpCost(tx
, view
, flags
);
1836 if (nSigOpsCost
> MAX_BLOCK_SIGOPS_COST
)
1837 return state
.DoS(100, error("ConnectBlock(): too many sigops"),
1838 REJECT_INVALID
, "bad-blk-sigops");
1840 txdata
.emplace_back(tx
);
1841 if (!tx
.IsCoinBase())
1843 nFees
+= view
.GetValueIn(tx
)-tx
.GetValueOut();
1845 std::vector
<CScriptCheck
> vChecks
;
1846 bool fCacheResults
= fJustCheck
; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1847 if (!CheckInputs(tx
, state
, view
, fScriptChecks
, flags
, fCacheResults
, txdata
[i
], nScriptCheckThreads
? &vChecks
: NULL
))
1848 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1849 tx
.GetHash().ToString(), FormatStateMessage(state
));
1850 control
.Add(vChecks
);
1855 blockundo
.vtxundo
.push_back(CTxUndo());
1857 UpdateCoins(tx
, view
, i
== 0 ? undoDummy
: blockundo
.vtxundo
.back(), pindex
->nHeight
);
1859 vPos
.push_back(std::make_pair(tx
.GetHash(), pos
));
1860 pos
.nTxOffset
+= ::GetSerializeSize(tx
, SER_DISK
, CLIENT_VERSION
);
1862 int64_t nTime3
= GetTimeMicros(); nTimeConnect
+= nTime3
- nTime2
;
1863 LogPrint("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);
1865 CAmount blockReward
= nFees
+ GetBlockSubsidy(pindex
->nHeight
, chainparams
.GetConsensus());
1866 if (block
.vtx
[0]->GetValueOut() > blockReward
)
1867 return state
.DoS(100,
1868 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1869 block
.vtx
[0]->GetValueOut(), blockReward
),
1870 REJECT_INVALID
, "bad-cb-amount");
1872 if (!control
.Wait())
1873 return state
.DoS(100, false);
1874 int64_t nTime4
= GetTimeMicros(); nTimeVerify
+= nTime4
- nTime2
;
1875 LogPrint("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);
1880 // Write undo information to disk
1881 if (pindex
->GetUndoPos().IsNull() || !pindex
->IsValid(BLOCK_VALID_SCRIPTS
))
1883 if (pindex
->GetUndoPos().IsNull()) {
1885 if (!FindUndoPos(state
, pindex
->nFile
, _pos
, ::GetSerializeSize(blockundo
, SER_DISK
, CLIENT_VERSION
) + 40))
1886 return error("ConnectBlock(): FindUndoPos failed");
1887 if (!UndoWriteToDisk(blockundo
, _pos
, pindex
->pprev
->GetBlockHash(), chainparams
.MessageStart()))
1888 return AbortNode(state
, "Failed to write undo data");
1890 // update nUndoPos in block index
1891 pindex
->nUndoPos
= _pos
.nPos
;
1892 pindex
->nStatus
|= BLOCK_HAVE_UNDO
;
1895 pindex
->RaiseValidity(BLOCK_VALID_SCRIPTS
);
1896 setDirtyBlockIndex
.insert(pindex
);
1900 if (!pblocktree
->WriteTxIndex(vPos
))
1901 return AbortNode(state
, "Failed to write transaction index");
1903 // add this block to the view's block chain
1904 view
.SetBestBlock(pindex
->GetBlockHash());
1906 int64_t nTime5
= GetTimeMicros(); nTimeIndex
+= nTime5
- nTime4
;
1907 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5
- nTime4
), nTimeIndex
* 0.000001);
1909 // Watch for changes to the previous coinbase transaction.
1910 static uint256 hashPrevBestCoinBase
;
1911 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase
);
1912 hashPrevBestCoinBase
= block
.vtx
[0]->GetHash();
1915 int64_t nTime6
= GetTimeMicros(); nTimeCallbacks
+= nTime6
- nTime5
;
1916 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6
- nTime5
), nTimeCallbacks
* 0.000001);
1922 * Update the on-disk chain state.
1923 * The caches and indexes are flushed depending on the mode we're called with
1924 * if they're too large, if it's been a while since the last write,
1925 * or always and in all cases if we're in prune mode and are deleting files.
1927 bool static FlushStateToDisk(CValidationState
&state
, FlushStateMode mode
) {
1928 const CChainParams
& chainparams
= Params();
1929 LOCK2(cs_main
, cs_LastBlockFile
);
1930 static int64_t nLastWrite
= 0;
1931 static int64_t nLastFlush
= 0;
1932 static int64_t nLastSetChain
= 0;
1933 std::set
<int> setFilesToPrune
;
1934 bool fFlushForPrune
= false;
1936 if (fPruneMode
&& fCheckForPruning
&& !fReindex
) {
1937 FindFilesToPrune(setFilesToPrune
, chainparams
.PruneAfterHeight());
1938 fCheckForPruning
= false;
1939 if (!setFilesToPrune
.empty()) {
1940 fFlushForPrune
= true;
1942 pblocktree
->WriteFlag("prunedblockfiles", true);
1947 int64_t nNow
= GetTimeMicros();
1948 // Avoid writing/flushing immediately after startup.
1949 if (nLastWrite
== 0) {
1952 if (nLastFlush
== 0) {
1955 if (nLastSetChain
== 0) {
1956 nLastSetChain
= nNow
;
1958 size_t cacheSize
= pcoinsTip
->DynamicMemoryUsage();
1959 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
1960 bool fCacheLarge
= mode
== FLUSH_STATE_PERIODIC
&& cacheSize
* (10.0/9) > nCoinCacheUsage
;
1961 // The cache is over the limit, we have to write now.
1962 bool fCacheCritical
= mode
== FLUSH_STATE_IF_NEEDED
&& cacheSize
> nCoinCacheUsage
;
1963 // 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.
1964 bool fPeriodicWrite
= mode
== FLUSH_STATE_PERIODIC
&& nNow
> nLastWrite
+ (int64_t)DATABASE_WRITE_INTERVAL
* 1000000;
1965 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1966 bool fPeriodicFlush
= mode
== FLUSH_STATE_PERIODIC
&& nNow
> nLastFlush
+ (int64_t)DATABASE_FLUSH_INTERVAL
* 1000000;
1967 // Combine all conditions that result in a full cache flush.
1968 bool fDoFullFlush
= (mode
== FLUSH_STATE_ALWAYS
) || fCacheLarge
|| fCacheCritical
|| fPeriodicFlush
|| fFlushForPrune
;
1969 // Write blocks and block index to disk.
1970 if (fDoFullFlush
|| fPeriodicWrite
) {
1971 // Depend on nMinDiskSpace to ensure we can write block index
1972 if (!CheckDiskSpace(0))
1973 return state
.Error("out of disk space");
1974 // First make sure all block and undo data is flushed to disk.
1976 // Then update all block file information (which may refer to block and undo files).
1978 std::vector
<std::pair
<int, const CBlockFileInfo
*> > vFiles
;
1979 vFiles
.reserve(setDirtyFileInfo
.size());
1980 for (set
<int>::iterator it
= setDirtyFileInfo
.begin(); it
!= setDirtyFileInfo
.end(); ) {
1981 vFiles
.push_back(make_pair(*it
, &vinfoBlockFile
[*it
]));
1982 setDirtyFileInfo
.erase(it
++);
1984 std::vector
<const CBlockIndex
*> vBlocks
;
1985 vBlocks
.reserve(setDirtyBlockIndex
.size());
1986 for (set
<CBlockIndex
*>::iterator it
= setDirtyBlockIndex
.begin(); it
!= setDirtyBlockIndex
.end(); ) {
1987 vBlocks
.push_back(*it
);
1988 setDirtyBlockIndex
.erase(it
++);
1990 if (!pblocktree
->WriteBatchSync(vFiles
, nLastBlockFile
, vBlocks
)) {
1991 return AbortNode(state
, "Files to write to block index database");
1994 // Finally remove any pruned files
1996 UnlinkPrunedFiles(setFilesToPrune
);
1999 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2001 // Typical CCoins structures on disk are around 128 bytes in size.
2002 // Pushing a new one to the database can cause it to be written
2003 // twice (once in the log, and once in the tables). This is already
2004 // an overestimation, as most will delete an existing entry or
2005 // overwrite one. Still, use a conservative safety factor of 2.
2006 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip
->GetCacheSize()))
2007 return state
.Error("out of disk space");
2008 // Flush the chainstate (which may refer to block index entries).
2009 if (!pcoinsTip
->Flush())
2010 return AbortNode(state
, "Failed to write to coin database");
2013 if (fDoFullFlush
|| ((mode
== FLUSH_STATE_ALWAYS
|| mode
== FLUSH_STATE_PERIODIC
) && nNow
> nLastSetChain
+ (int64_t)DATABASE_WRITE_INTERVAL
* 1000000)) {
2014 // Update best block in wallet (so we can detect restored wallets).
2015 GetMainSignals().SetBestChain(chainActive
.GetLocator());
2016 nLastSetChain
= nNow
;
2018 } catch (const std::runtime_error
& e
) {
2019 return AbortNode(state
, std::string("System error while flushing: ") + e
.what());
2024 void FlushStateToDisk() {
2025 CValidationState state
;
2026 FlushStateToDisk(state
, FLUSH_STATE_ALWAYS
);
2029 void PruneAndFlush() {
2030 CValidationState state
;
2031 fCheckForPruning
= true;
2032 FlushStateToDisk(state
, FLUSH_STATE_NONE
);
2035 /** Update chainActive and related internal data structures. */
2036 void static UpdateTip(CBlockIndex
*pindexNew
, const CChainParams
& chainParams
) {
2037 chainActive
.SetTip(pindexNew
);
2040 mempool
.AddTransactionsUpdated(1);
2042 cvBlockChange
.notify_all();
2044 static bool fWarned
= false;
2045 std::vector
<std::string
> warningMessages
;
2046 if (!IsInitialBlockDownload())
2049 const CBlockIndex
* pindex
= chainActive
.Tip();
2050 for (int bit
= 0; bit
< VERSIONBITS_NUM_BITS
; bit
++) {
2051 WarningBitsConditionChecker
checker(bit
);
2052 ThresholdState state
= checker
.GetStateFor(pindex
, chainParams
.GetConsensus(), warningcache
[bit
]);
2053 if (state
== THRESHOLD_ACTIVE
|| state
== THRESHOLD_LOCKED_IN
) {
2054 if (state
== THRESHOLD_ACTIVE
) {
2055 strMiscWarning
= strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit
);
2057 AlertNotify(strMiscWarning
);
2061 warningMessages
.push_back(strprintf("unknown new rules are about to activate (versionbit %i)", bit
));
2065 // Check the version of the last 100 blocks to see if we need to upgrade:
2066 for (int i
= 0; i
< 100 && pindex
!= NULL
; i
++)
2068 int32_t nExpectedVersion
= ComputeBlockVersion(pindex
->pprev
, chainParams
.GetConsensus());
2069 if (pindex
->nVersion
> VERSIONBITS_LAST_OLD_BLOCK_VERSION
&& (pindex
->nVersion
& ~nExpectedVersion
) != 0)
2071 pindex
= pindex
->pprev
;
2074 warningMessages
.push_back(strprintf("%d of last 100 blocks have unexpected version", nUpgraded
));
2075 if (nUpgraded
> 100/2)
2077 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2078 strMiscWarning
= _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2080 AlertNotify(strMiscWarning
);
2085 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utx)", __func__
,
2086 chainActive
.Tip()->GetBlockHash().ToString(), chainActive
.Height(), chainActive
.Tip()->nVersion
,
2087 log(chainActive
.Tip()->nChainWork
.getdouble())/log(2.0), (unsigned long)chainActive
.Tip()->nChainTx
,
2088 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive
.Tip()->GetBlockTime()),
2089 Checkpoints::GuessVerificationProgress(chainParams
.Checkpoints(), chainActive
.Tip()), pcoinsTip
->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip
->GetCacheSize());
2090 if (!warningMessages
.empty())
2091 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages
, ", "));
2096 /** Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and manually re-limit mempool size after this, with cs_main held. */
2097 bool static DisconnectTip(CValidationState
& state
, const CChainParams
& chainparams
, bool fBare
= false)
2099 CBlockIndex
*pindexDelete
= chainActive
.Tip();
2100 assert(pindexDelete
);
2101 // Read block from disk.
2103 if (!ReadBlockFromDisk(block
, pindexDelete
, chainparams
.GetConsensus()))
2104 return AbortNode(state
, "Failed to read block");
2105 // Apply the block atomically to the chain state.
2106 int64_t nStart
= GetTimeMicros();
2108 CCoinsViewCache
view(pcoinsTip
);
2109 if (!DisconnectBlock(block
, state
, pindexDelete
, view
))
2110 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete
->GetBlockHash().ToString());
2111 assert(view
.Flush());
2113 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart
) * 0.001);
2114 // Write the chain state to disk, if necessary.
2115 if (!FlushStateToDisk(state
, FLUSH_STATE_IF_NEEDED
))
2119 // Resurrect mempool transactions from the disconnected block.
2120 std::vector
<uint256
> vHashUpdate
;
2121 for (const auto& it
: block
.vtx
) {
2122 const CTransaction
& tx
= *it
;
2123 // ignore validation errors in resurrected transactions
2124 CValidationState stateDummy
;
2125 if (tx
.IsCoinBase() || !AcceptToMemoryPool(mempool
, stateDummy
, tx
, false, NULL
, true)) {
2126 mempool
.removeRecursive(tx
);
2127 } else if (mempool
.exists(tx
.GetHash())) {
2128 vHashUpdate
.push_back(tx
.GetHash());
2131 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
2132 // no in-mempool children, which is generally not true when adding
2133 // previously-confirmed transactions back to the mempool.
2134 // UpdateTransactionsFromBlock finds descendants of any transactions in this
2135 // block that were added back and cleans up the mempool state.
2136 mempool
.UpdateTransactionsFromBlock(vHashUpdate
);
2139 // Update chainActive and related variables.
2140 UpdateTip(pindexDelete
->pprev
, chainparams
);
2141 // Let wallets know transactions went from 1-confirmed to
2142 // 0-confirmed or conflicted:
2143 for (const auto& tx
: block
.vtx
) {
2144 GetMainSignals().SyncTransaction(*tx
, pindexDelete
->pprev
, CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK
);
2149 static int64_t nTimeReadFromDisk
= 0;
2150 static int64_t nTimeConnectTotal
= 0;
2151 static int64_t nTimeFlush
= 0;
2152 static int64_t nTimeChainState
= 0;
2153 static int64_t nTimePostConnect
= 0;
2156 * Used to track conflicted transactions removed from mempool and transactions
2157 * applied to the UTXO state as a part of a single ActivateBestChainStep call.
2159 struct ConnectTrace
{
2160 std::vector
<CTransactionRef
> txConflicted
;
2161 std::vector
<std::pair
<CBlockIndex
*, std::shared_ptr
<const CBlock
> > > blocksConnected
;
2165 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2166 * corresponding to pindexNew, to bypass loading it again from disk.
2168 * The block is always added to connectTrace (either after loading from disk or by copying
2169 * pblock) - if that is not intended, care must be taken to remove the last entry in
2170 * blocksConnected in case of failure.
2172 bool static ConnectTip(CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
* pindexNew
, const std::shared_ptr
<const CBlock
>& pblock
, ConnectTrace
& connectTrace
)
2174 assert(pindexNew
->pprev
== chainActive
.Tip());
2175 // Read block from disk.
2176 int64_t nTime1
= GetTimeMicros();
2178 std::shared_ptr
<CBlock
> pblockNew
= std::make_shared
<CBlock
>();
2179 connectTrace
.blocksConnected
.emplace_back(pindexNew
, pblockNew
);
2180 if (!ReadBlockFromDisk(*pblockNew
, pindexNew
, chainparams
.GetConsensus()))
2181 return AbortNode(state
, "Failed to read block");
2183 connectTrace
.blocksConnected
.emplace_back(pindexNew
, pblock
);
2185 const CBlock
& blockConnecting
= *connectTrace
.blocksConnected
.back().second
;
2186 // Apply the block atomically to the chain state.
2187 int64_t nTime2
= GetTimeMicros(); nTimeReadFromDisk
+= nTime2
- nTime1
;
2189 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2
- nTime1
) * 0.001, nTimeReadFromDisk
* 0.000001);
2191 CCoinsViewCache
view(pcoinsTip
);
2192 bool rv
= ConnectBlock(blockConnecting
, state
, pindexNew
, view
, chainparams
);
2193 GetMainSignals().BlockChecked(blockConnecting
, state
);
2195 if (state
.IsInvalid())
2196 InvalidBlockFound(pindexNew
, state
);
2197 return error("ConnectTip(): ConnectBlock %s failed", pindexNew
->GetBlockHash().ToString());
2199 nTime3
= GetTimeMicros(); nTimeConnectTotal
+= nTime3
- nTime2
;
2200 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3
- nTime2
) * 0.001, nTimeConnectTotal
* 0.000001);
2201 assert(view
.Flush());
2203 int64_t nTime4
= GetTimeMicros(); nTimeFlush
+= nTime4
- nTime3
;
2204 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4
- nTime3
) * 0.001, nTimeFlush
* 0.000001);
2205 // Write the chain state to disk, if necessary.
2206 if (!FlushStateToDisk(state
, FLUSH_STATE_IF_NEEDED
))
2208 int64_t nTime5
= GetTimeMicros(); nTimeChainState
+= nTime5
- nTime4
;
2209 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5
- nTime4
) * 0.001, nTimeChainState
* 0.000001);
2210 // Remove conflicting transactions from the mempool.;
2211 mempool
.removeForBlock(blockConnecting
.vtx
, pindexNew
->nHeight
, &connectTrace
.txConflicted
, !IsInitialBlockDownload());
2212 // Update chainActive & related variables.
2213 UpdateTip(pindexNew
, chainparams
);
2215 int64_t nTime6
= GetTimeMicros(); nTimePostConnect
+= nTime6
- nTime5
; nTimeTotal
+= nTime6
- nTime1
;
2216 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6
- nTime5
) * 0.001, nTimePostConnect
* 0.000001);
2217 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6
- nTime1
) * 0.001, nTimeTotal
* 0.000001);
2222 * Return the tip of the chain with the most work in it, that isn't
2223 * known to be invalid (it's however far from certain to be valid).
2225 static CBlockIndex
* FindMostWorkChain() {
2227 CBlockIndex
*pindexNew
= NULL
;
2229 // Find the best candidate header.
2231 std::set
<CBlockIndex
*, CBlockIndexWorkComparator
>::reverse_iterator it
= setBlockIndexCandidates
.rbegin();
2232 if (it
== setBlockIndexCandidates
.rend())
2237 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2238 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2239 CBlockIndex
*pindexTest
= pindexNew
;
2240 bool fInvalidAncestor
= false;
2241 while (pindexTest
&& !chainActive
.Contains(pindexTest
)) {
2242 assert(pindexTest
->nChainTx
|| pindexTest
->nHeight
== 0);
2244 // Pruned nodes may have entries in setBlockIndexCandidates for
2245 // which block files have been deleted. Remove those as candidates
2246 // for the most work chain if we come across them; we can't switch
2247 // to a chain unless we have all the non-active-chain parent blocks.
2248 bool fFailedChain
= pindexTest
->nStatus
& BLOCK_FAILED_MASK
;
2249 bool fMissingData
= !(pindexTest
->nStatus
& BLOCK_HAVE_DATA
);
2250 if (fFailedChain
|| fMissingData
) {
2251 // Candidate chain is not usable (either invalid or missing data)
2252 if (fFailedChain
&& (pindexBestInvalid
== NULL
|| pindexNew
->nChainWork
> pindexBestInvalid
->nChainWork
))
2253 pindexBestInvalid
= pindexNew
;
2254 CBlockIndex
*pindexFailed
= pindexNew
;
2255 // Remove the entire chain from the set.
2256 while (pindexTest
!= pindexFailed
) {
2258 pindexFailed
->nStatus
|= BLOCK_FAILED_CHILD
;
2259 } else if (fMissingData
) {
2260 // If we're missing data, then add back to mapBlocksUnlinked,
2261 // so that if the block arrives in the future we can try adding
2262 // to setBlockIndexCandidates again.
2263 mapBlocksUnlinked
.insert(std::make_pair(pindexFailed
->pprev
, pindexFailed
));
2265 setBlockIndexCandidates
.erase(pindexFailed
);
2266 pindexFailed
= pindexFailed
->pprev
;
2268 setBlockIndexCandidates
.erase(pindexTest
);
2269 fInvalidAncestor
= true;
2272 pindexTest
= pindexTest
->pprev
;
2274 if (!fInvalidAncestor
)
2279 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2280 static void PruneBlockIndexCandidates() {
2281 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2282 // reorganization to a better block fails.
2283 std::set
<CBlockIndex
*, CBlockIndexWorkComparator
>::iterator it
= setBlockIndexCandidates
.begin();
2284 while (it
!= setBlockIndexCandidates
.end() && setBlockIndexCandidates
.value_comp()(*it
, chainActive
.Tip())) {
2285 setBlockIndexCandidates
.erase(it
++);
2287 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2288 assert(!setBlockIndexCandidates
.empty());
2292 * Try to make some progress towards making pindexMostWork the active block.
2293 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2295 static bool ActivateBestChainStep(CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
* pindexMostWork
, const std::shared_ptr
<const CBlock
>& pblock
, bool& fInvalidFound
, ConnectTrace
& connectTrace
)
2297 AssertLockHeld(cs_main
);
2298 const CBlockIndex
*pindexOldTip
= chainActive
.Tip();
2299 const CBlockIndex
*pindexFork
= chainActive
.FindFork(pindexMostWork
);
2301 // Disconnect active blocks which are no longer in the best chain.
2302 bool fBlocksDisconnected
= false;
2303 while (chainActive
.Tip() && chainActive
.Tip() != pindexFork
) {
2304 if (!DisconnectTip(state
, chainparams
))
2306 fBlocksDisconnected
= true;
2309 // Build list of new blocks to connect.
2310 std::vector
<CBlockIndex
*> vpindexToConnect
;
2311 bool fContinue
= true;
2312 int nHeight
= pindexFork
? pindexFork
->nHeight
: -1;
2313 while (fContinue
&& nHeight
!= pindexMostWork
->nHeight
) {
2314 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2315 // a few blocks along the way.
2316 int nTargetHeight
= std::min(nHeight
+ 32, pindexMostWork
->nHeight
);
2317 vpindexToConnect
.clear();
2318 vpindexToConnect
.reserve(nTargetHeight
- nHeight
);
2319 CBlockIndex
*pindexIter
= pindexMostWork
->GetAncestor(nTargetHeight
);
2320 while (pindexIter
&& pindexIter
->nHeight
!= nHeight
) {
2321 vpindexToConnect
.push_back(pindexIter
);
2322 pindexIter
= pindexIter
->pprev
;
2324 nHeight
= nTargetHeight
;
2326 // Connect new blocks.
2327 BOOST_REVERSE_FOREACH(CBlockIndex
*pindexConnect
, vpindexToConnect
) {
2328 if (!ConnectTip(state
, chainparams
, pindexConnect
, pindexConnect
== pindexMostWork
? pblock
: std::shared_ptr
<const CBlock
>(), connectTrace
)) {
2329 if (state
.IsInvalid()) {
2330 // The block violates a consensus rule.
2331 if (!state
.CorruptionPossible())
2332 InvalidChainFound(vpindexToConnect
.back());
2333 state
= CValidationState();
2334 fInvalidFound
= true;
2336 // If we didn't actually connect the block, don't notify listeners about it
2337 connectTrace
.blocksConnected
.pop_back();
2340 // A system error occurred (disk space, database error, ...).
2344 PruneBlockIndexCandidates();
2345 if (!pindexOldTip
|| chainActive
.Tip()->nChainWork
> pindexOldTip
->nChainWork
) {
2346 // We're in a better position than we were. Return temporarily to release the lock.
2354 if (fBlocksDisconnected
) {
2355 mempool
.removeForReorg(pcoinsTip
, chainActive
.Tip()->nHeight
+ 1, STANDARD_LOCKTIME_VERIFY_FLAGS
);
2356 LimitMempoolSize(mempool
, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY
) * 60 * 60);
2358 mempool
.check(pcoinsTip
);
2360 // Callbacks/notifications for a new best chain.
2362 CheckForkWarningConditionsOnNewFork(vpindexToConnect
.back());
2364 CheckForkWarningConditions();
2369 static void NotifyHeaderTip() {
2370 bool fNotify
= false;
2371 bool fInitialBlockDownload
= false;
2372 static CBlockIndex
* pindexHeaderOld
= NULL
;
2373 CBlockIndex
* pindexHeader
= NULL
;
2376 pindexHeader
= pindexBestHeader
;
2378 if (pindexHeader
!= pindexHeaderOld
) {
2380 fInitialBlockDownload
= IsInitialBlockDownload();
2381 pindexHeaderOld
= pindexHeader
;
2384 // Send block tip changed notifications without cs_main
2386 uiInterface
.NotifyHeaderTip(fInitialBlockDownload
, pindexHeader
);
2391 * Make the best chain active, in multiple steps. The result is either failure
2392 * or an activated best chain. pblock is either NULL or a pointer to a block
2393 * that is already loaded (to avoid loading it again from disk).
2395 bool ActivateBestChain(CValidationState
&state
, const CChainParams
& chainparams
, std::shared_ptr
<const CBlock
> pblock
) {
2396 CBlockIndex
*pindexMostWork
= NULL
;
2397 CBlockIndex
*pindexNewTip
= NULL
;
2399 boost::this_thread::interruption_point();
2400 if (ShutdownRequested())
2403 const CBlockIndex
*pindexFork
;
2404 ConnectTrace connectTrace
;
2405 bool fInitialDownload
;
2408 CBlockIndex
*pindexOldTip
= chainActive
.Tip();
2409 if (pindexMostWork
== NULL
) {
2410 pindexMostWork
= FindMostWorkChain();
2413 // Whether we have anything to do at all.
2414 if (pindexMostWork
== NULL
|| pindexMostWork
== chainActive
.Tip())
2417 bool fInvalidFound
= false;
2418 std::shared_ptr
<const CBlock
> nullBlockPtr
;
2419 if (!ActivateBestChainStep(state
, chainparams
, pindexMostWork
, pblock
&& pblock
->GetHash() == pindexMostWork
->GetBlockHash() ? pblock
: nullBlockPtr
, fInvalidFound
, connectTrace
))
2422 if (fInvalidFound
) {
2423 // Wipe cache, we may need another branch now.
2424 pindexMostWork
= NULL
;
2426 pindexNewTip
= chainActive
.Tip();
2427 pindexFork
= chainActive
.FindFork(pindexOldTip
);
2428 fInitialDownload
= IsInitialBlockDownload();
2430 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2432 // Notifications/callbacks that can run without cs_main
2434 // throw all transactions though the signal-interface
2435 // while _not_ holding the cs_main lock
2436 for (const auto& tx
: connectTrace
.txConflicted
)
2438 GetMainSignals().SyncTransaction(*tx
, pindexNewTip
, CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK
);
2440 // ... and about transactions that got confirmed:
2441 for (const auto& pair
: connectTrace
.blocksConnected
) {
2442 assert(pair
.second
);
2443 const CBlock
& block
= *(pair
.second
);
2444 for (unsigned int i
= 0; i
< block
.vtx
.size(); i
++)
2445 GetMainSignals().SyncTransaction(*block
.vtx
[i
], pair
.first
, i
);
2448 // Notify external listeners about the new tip.
2449 GetMainSignals().UpdatedBlockTip(pindexNewTip
, pindexFork
, fInitialDownload
);
2451 // Always notify the UI if a new block tip was connected
2452 if (pindexFork
!= pindexNewTip
) {
2453 uiInterface
.NotifyBlockTip(fInitialDownload
, pindexNewTip
);
2455 } while (pindexNewTip
!= pindexMostWork
);
2456 CheckBlockIndex(chainparams
.GetConsensus());
2458 // Write changes periodically to disk, after relay.
2459 if (!FlushStateToDisk(state
, FLUSH_STATE_PERIODIC
)) {
2467 bool PreciousBlock(CValidationState
& state
, const CChainParams
& params
, CBlockIndex
*pindex
)
2471 if (pindex
->nChainWork
< chainActive
.Tip()->nChainWork
) {
2472 // Nothing to do, this block is not at the tip.
2475 if (chainActive
.Tip()->nChainWork
> nLastPreciousChainwork
) {
2476 // The chain has been extended since the last call, reset the counter.
2477 nBlockReverseSequenceId
= -1;
2479 nLastPreciousChainwork
= chainActive
.Tip()->nChainWork
;
2480 setBlockIndexCandidates
.erase(pindex
);
2481 pindex
->nSequenceId
= nBlockReverseSequenceId
;
2482 if (nBlockReverseSequenceId
> std::numeric_limits
<int32_t>::min()) {
2483 // We can't keep reducing the counter if somebody really wants to
2484 // call preciousblock 2**31-1 times on the same set of tips...
2485 nBlockReverseSequenceId
--;
2487 if (pindex
->IsValid(BLOCK_VALID_TRANSACTIONS
) && pindex
->nChainTx
) {
2488 setBlockIndexCandidates
.insert(pindex
);
2489 PruneBlockIndexCandidates();
2493 return ActivateBestChain(state
, params
);
2496 bool InvalidateBlock(CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
*pindex
)
2498 AssertLockHeld(cs_main
);
2500 // Mark the block itself as invalid.
2501 pindex
->nStatus
|= BLOCK_FAILED_VALID
;
2502 setDirtyBlockIndex
.insert(pindex
);
2503 setBlockIndexCandidates
.erase(pindex
);
2505 while (chainActive
.Contains(pindex
)) {
2506 CBlockIndex
*pindexWalk
= chainActive
.Tip();
2507 pindexWalk
->nStatus
|= BLOCK_FAILED_CHILD
;
2508 setDirtyBlockIndex
.insert(pindexWalk
);
2509 setBlockIndexCandidates
.erase(pindexWalk
);
2510 // ActivateBestChain considers blocks already in chainActive
2511 // unconditionally valid already, so force disconnect away from it.
2512 if (!DisconnectTip(state
, chainparams
)) {
2513 mempool
.removeForReorg(pcoinsTip
, chainActive
.Tip()->nHeight
+ 1, STANDARD_LOCKTIME_VERIFY_FLAGS
);
2518 LimitMempoolSize(mempool
, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE
) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY
) * 60 * 60);
2520 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2522 BlockMap::iterator it
= mapBlockIndex
.begin();
2523 while (it
!= mapBlockIndex
.end()) {
2524 if (it
->second
->IsValid(BLOCK_VALID_TRANSACTIONS
) && it
->second
->nChainTx
&& !setBlockIndexCandidates
.value_comp()(it
->second
, chainActive
.Tip())) {
2525 setBlockIndexCandidates
.insert(it
->second
);
2530 InvalidChainFound(pindex
);
2531 mempool
.removeForReorg(pcoinsTip
, chainActive
.Tip()->nHeight
+ 1, STANDARD_LOCKTIME_VERIFY_FLAGS
);
2532 uiInterface
.NotifyBlockTip(IsInitialBlockDownload(), pindex
->pprev
);
2536 bool ResetBlockFailureFlags(CBlockIndex
*pindex
) {
2537 AssertLockHeld(cs_main
);
2539 int nHeight
= pindex
->nHeight
;
2541 // Remove the invalidity flag from this block and all its descendants.
2542 BlockMap::iterator it
= mapBlockIndex
.begin();
2543 while (it
!= mapBlockIndex
.end()) {
2544 if (!it
->second
->IsValid() && it
->second
->GetAncestor(nHeight
) == pindex
) {
2545 it
->second
->nStatus
&= ~BLOCK_FAILED_MASK
;
2546 setDirtyBlockIndex
.insert(it
->second
);
2547 if (it
->second
->IsValid(BLOCK_VALID_TRANSACTIONS
) && it
->second
->nChainTx
&& setBlockIndexCandidates
.value_comp()(chainActive
.Tip(), it
->second
)) {
2548 setBlockIndexCandidates
.insert(it
->second
);
2550 if (it
->second
== pindexBestInvalid
) {
2551 // Reset invalid block marker if it was pointing to one of those.
2552 pindexBestInvalid
= NULL
;
2558 // Remove the invalidity flag from all ancestors too.
2559 while (pindex
!= NULL
) {
2560 if (pindex
->nStatus
& BLOCK_FAILED_MASK
) {
2561 pindex
->nStatus
&= ~BLOCK_FAILED_MASK
;
2562 setDirtyBlockIndex
.insert(pindex
);
2564 pindex
= pindex
->pprev
;
2569 CBlockIndex
* AddToBlockIndex(const CBlockHeader
& block
)
2571 // Check for duplicate
2572 uint256 hash
= block
.GetHash();
2573 BlockMap::iterator it
= mapBlockIndex
.find(hash
);
2574 if (it
!= mapBlockIndex
.end())
2577 // Construct new block index object
2578 CBlockIndex
* pindexNew
= new CBlockIndex(block
);
2580 // We assign the sequence id to blocks only when the full data is available,
2581 // to avoid miners withholding blocks but broadcasting headers, to get a
2582 // competitive advantage.
2583 pindexNew
->nSequenceId
= 0;
2584 BlockMap::iterator mi
= mapBlockIndex
.insert(make_pair(hash
, pindexNew
)).first
;
2585 pindexNew
->phashBlock
= &((*mi
).first
);
2586 BlockMap::iterator miPrev
= mapBlockIndex
.find(block
.hashPrevBlock
);
2587 if (miPrev
!= mapBlockIndex
.end())
2589 pindexNew
->pprev
= (*miPrev
).second
;
2590 pindexNew
->nHeight
= pindexNew
->pprev
->nHeight
+ 1;
2591 pindexNew
->BuildSkip();
2593 pindexNew
->nChainWork
= (pindexNew
->pprev
? pindexNew
->pprev
->nChainWork
: 0) + GetBlockProof(*pindexNew
);
2594 pindexNew
->RaiseValidity(BLOCK_VALID_TREE
);
2595 if (pindexBestHeader
== NULL
|| pindexBestHeader
->nChainWork
< pindexNew
->nChainWork
)
2596 pindexBestHeader
= pindexNew
;
2598 setDirtyBlockIndex
.insert(pindexNew
);
2603 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2604 bool ReceivedBlockTransactions(const CBlock
&block
, CValidationState
& state
, CBlockIndex
*pindexNew
, const CDiskBlockPos
& pos
)
2606 pindexNew
->nTx
= block
.vtx
.size();
2607 pindexNew
->nChainTx
= 0;
2608 pindexNew
->nFile
= pos
.nFile
;
2609 pindexNew
->nDataPos
= pos
.nPos
;
2610 pindexNew
->nUndoPos
= 0;
2611 pindexNew
->nStatus
|= BLOCK_HAVE_DATA
;
2612 if (IsWitnessEnabled(pindexNew
->pprev
, Params().GetConsensus())) {
2613 pindexNew
->nStatus
|= BLOCK_OPT_WITNESS
;
2615 pindexNew
->RaiseValidity(BLOCK_VALID_TRANSACTIONS
);
2616 setDirtyBlockIndex
.insert(pindexNew
);
2618 if (pindexNew
->pprev
== NULL
|| pindexNew
->pprev
->nChainTx
) {
2619 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2620 deque
<CBlockIndex
*> queue
;
2621 queue
.push_back(pindexNew
);
2623 // Recursively process any descendant blocks that now may be eligible to be connected.
2624 while (!queue
.empty()) {
2625 CBlockIndex
*pindex
= queue
.front();
2627 pindex
->nChainTx
= (pindex
->pprev
? pindex
->pprev
->nChainTx
: 0) + pindex
->nTx
;
2629 LOCK(cs_nBlockSequenceId
);
2630 pindex
->nSequenceId
= nBlockSequenceId
++;
2632 if (chainActive
.Tip() == NULL
|| !setBlockIndexCandidates
.value_comp()(pindex
, chainActive
.Tip())) {
2633 setBlockIndexCandidates
.insert(pindex
);
2635 std::pair
<std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
, std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
> range
= mapBlocksUnlinked
.equal_range(pindex
);
2636 while (range
.first
!= range
.second
) {
2637 std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator it
= range
.first
;
2638 queue
.push_back(it
->second
);
2640 mapBlocksUnlinked
.erase(it
);
2644 if (pindexNew
->pprev
&& pindexNew
->pprev
->IsValid(BLOCK_VALID_TREE
)) {
2645 mapBlocksUnlinked
.insert(std::make_pair(pindexNew
->pprev
, pindexNew
));
2652 bool FindBlockPos(CValidationState
&state
, CDiskBlockPos
&pos
, unsigned int nAddSize
, unsigned int nHeight
, uint64_t nTime
, bool fKnown
= false)
2654 LOCK(cs_LastBlockFile
);
2656 unsigned int nFile
= fKnown
? pos
.nFile
: nLastBlockFile
;
2657 if (vinfoBlockFile
.size() <= nFile
) {
2658 vinfoBlockFile
.resize(nFile
+ 1);
2662 while (vinfoBlockFile
[nFile
].nSize
+ nAddSize
>= MAX_BLOCKFILE_SIZE
) {
2664 if (vinfoBlockFile
.size() <= nFile
) {
2665 vinfoBlockFile
.resize(nFile
+ 1);
2669 pos
.nPos
= vinfoBlockFile
[nFile
].nSize
;
2672 if ((int)nFile
!= nLastBlockFile
) {
2674 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile
, vinfoBlockFile
[nLastBlockFile
].ToString());
2676 FlushBlockFile(!fKnown
);
2677 nLastBlockFile
= nFile
;
2680 vinfoBlockFile
[nFile
].AddBlock(nHeight
, nTime
);
2682 vinfoBlockFile
[nFile
].nSize
= std::max(pos
.nPos
+ nAddSize
, vinfoBlockFile
[nFile
].nSize
);
2684 vinfoBlockFile
[nFile
].nSize
+= nAddSize
;
2687 unsigned int nOldChunks
= (pos
.nPos
+ BLOCKFILE_CHUNK_SIZE
- 1) / BLOCKFILE_CHUNK_SIZE
;
2688 unsigned int nNewChunks
= (vinfoBlockFile
[nFile
].nSize
+ BLOCKFILE_CHUNK_SIZE
- 1) / BLOCKFILE_CHUNK_SIZE
;
2689 if (nNewChunks
> nOldChunks
) {
2691 fCheckForPruning
= true;
2692 if (CheckDiskSpace(nNewChunks
* BLOCKFILE_CHUNK_SIZE
- pos
.nPos
)) {
2693 FILE *file
= OpenBlockFile(pos
);
2695 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks
* BLOCKFILE_CHUNK_SIZE
, pos
.nFile
);
2696 AllocateFileRange(file
, pos
.nPos
, nNewChunks
* BLOCKFILE_CHUNK_SIZE
- pos
.nPos
);
2701 return state
.Error("out of disk space");
2705 setDirtyFileInfo
.insert(nFile
);
2709 bool FindUndoPos(CValidationState
&state
, int nFile
, CDiskBlockPos
&pos
, unsigned int nAddSize
)
2713 LOCK(cs_LastBlockFile
);
2715 unsigned int nNewSize
;
2716 pos
.nPos
= vinfoBlockFile
[nFile
].nUndoSize
;
2717 nNewSize
= vinfoBlockFile
[nFile
].nUndoSize
+= nAddSize
;
2718 setDirtyFileInfo
.insert(nFile
);
2720 unsigned int nOldChunks
= (pos
.nPos
+ UNDOFILE_CHUNK_SIZE
- 1) / UNDOFILE_CHUNK_SIZE
;
2721 unsigned int nNewChunks
= (nNewSize
+ UNDOFILE_CHUNK_SIZE
- 1) / UNDOFILE_CHUNK_SIZE
;
2722 if (nNewChunks
> nOldChunks
) {
2724 fCheckForPruning
= true;
2725 if (CheckDiskSpace(nNewChunks
* UNDOFILE_CHUNK_SIZE
- pos
.nPos
)) {
2726 FILE *file
= OpenUndoFile(pos
);
2728 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks
* UNDOFILE_CHUNK_SIZE
, pos
.nFile
);
2729 AllocateFileRange(file
, pos
.nPos
, nNewChunks
* UNDOFILE_CHUNK_SIZE
- pos
.nPos
);
2734 return state
.Error("out of disk space");
2740 bool CheckBlockHeader(const CBlockHeader
& block
, CValidationState
& state
, const Consensus::Params
& consensusParams
, bool fCheckPOW
)
2742 // Check proof of work matches claimed amount
2743 if (fCheckPOW
&& !CheckProofOfWork(block
.GetHash(), block
.nBits
, consensusParams
))
2744 return state
.DoS(50, false, REJECT_INVALID
, "high-hash", false, "proof of work failed");
2749 bool CheckBlock(const CBlock
& block
, CValidationState
& state
, const Consensus::Params
& consensusParams
, bool fCheckPOW
, bool fCheckMerkleRoot
)
2751 // These are checks that are independent of context.
2756 // Check that the header is valid (particularly PoW). This is mostly
2757 // redundant with the call in AcceptBlockHeader.
2758 if (!CheckBlockHeader(block
, state
, consensusParams
, fCheckPOW
))
2761 // Check the merkle root.
2762 if (fCheckMerkleRoot
) {
2764 uint256 hashMerkleRoot2
= BlockMerkleRoot(block
, &mutated
);
2765 if (block
.hashMerkleRoot
!= hashMerkleRoot2
)
2766 return state
.DoS(100, false, REJECT_INVALID
, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2768 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2769 // of transactions in a block without affecting the merkle root of a block,
2770 // while still invalidating it.
2772 return state
.DoS(100, false, REJECT_INVALID
, "bad-txns-duplicate", true, "duplicate transaction");
2775 // All potential-corruption validation must be done before we do any
2776 // transaction validation, as otherwise we may mark the header as invalid
2777 // because we receive the wrong transactions for it.
2778 // Note that witness malleability is checked in ContextualCheckBlock, so no
2779 // checks that use witness data may be performed here.
2782 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
)
2783 return state
.DoS(100, false, REJECT_INVALID
, "bad-blk-length", false, "size limits failed");
2785 // First transaction must be coinbase, the rest must not be
2786 if (block
.vtx
.empty() || !block
.vtx
[0]->IsCoinBase())
2787 return state
.DoS(100, false, REJECT_INVALID
, "bad-cb-missing", false, "first tx is not coinbase");
2788 for (unsigned int i
= 1; i
< block
.vtx
.size(); i
++)
2789 if (block
.vtx
[i
]->IsCoinBase())
2790 return state
.DoS(100, false, REJECT_INVALID
, "bad-cb-multiple", false, "more than one coinbase");
2792 // Check transactions
2793 for (const auto& tx
: block
.vtx
)
2794 if (!CheckTransaction(*tx
, state
, false))
2795 return state
.Invalid(false, state
.GetRejectCode(), state
.GetRejectReason(),
2796 strprintf("Transaction check failed (tx hash %s) %s", tx
->GetHash().ToString(), state
.GetDebugMessage()));
2798 unsigned int nSigOps
= 0;
2799 for (const auto& tx
: block
.vtx
)
2801 nSigOps
+= GetLegacySigOpCount(*tx
);
2803 if (nSigOps
* WITNESS_SCALE_FACTOR
> MAX_BLOCK_SIGOPS_COST
)
2804 return state
.DoS(100, false, REJECT_INVALID
, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2806 if (fCheckPOW
&& fCheckMerkleRoot
)
2807 block
.fChecked
= true;
2812 static bool CheckIndexAgainstCheckpoint(const CBlockIndex
* pindexPrev
, CValidationState
& state
, const CChainParams
& chainparams
, const uint256
& hash
)
2814 if (*pindexPrev
->phashBlock
== chainparams
.GetConsensus().hashGenesisBlock
)
2817 int nHeight
= pindexPrev
->nHeight
+1;
2818 // Don't accept any forks from the main chain prior to last checkpoint
2819 CBlockIndex
* pcheckpoint
= Checkpoints::GetLastCheckpoint(chainparams
.Checkpoints());
2820 if (pcheckpoint
&& nHeight
< pcheckpoint
->nHeight
)
2821 return state
.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__
, nHeight
));
2826 bool IsWitnessEnabled(const CBlockIndex
* pindexPrev
, const Consensus::Params
& params
)
2829 return (VersionBitsState(pindexPrev
, params
, Consensus::DEPLOYMENT_SEGWIT
, versionbitscache
) == THRESHOLD_ACTIVE
);
2832 // Compute at which vout of the block's coinbase transaction the witness
2833 // commitment occurs, or -1 if not found.
2834 static int GetWitnessCommitmentIndex(const CBlock
& block
)
2837 for (size_t o
= 0; o
< block
.vtx
[0]->vout
.size(); o
++) {
2838 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) {
2845 void UpdateUncommittedBlockStructures(CBlock
& block
, const CBlockIndex
* pindexPrev
, const Consensus::Params
& consensusParams
)
2847 int commitpos
= GetWitnessCommitmentIndex(block
);
2848 static const std::vector
<unsigned char> nonce(32, 0x00);
2849 if (commitpos
!= -1 && IsWitnessEnabled(pindexPrev
, consensusParams
) && block
.vtx
[0]->wit
.IsEmpty()) {
2850 CMutableTransaction
tx(*block
.vtx
[0]);
2851 tx
.wit
.vtxinwit
.resize(1);
2852 tx
.wit
.vtxinwit
[0].scriptWitness
.stack
.resize(1);
2853 tx
.wit
.vtxinwit
[0].scriptWitness
.stack
[0] = nonce
;
2854 block
.vtx
[0] = MakeTransactionRef(std::move(tx
));
2858 std::vector
<unsigned char> GenerateCoinbaseCommitment(CBlock
& block
, const CBlockIndex
* pindexPrev
, const Consensus::Params
& consensusParams
)
2860 std::vector
<unsigned char> commitment
;
2861 int commitpos
= GetWitnessCommitmentIndex(block
);
2862 std::vector
<unsigned char> ret(32, 0x00);
2863 if (consensusParams
.vDeployments
[Consensus::DEPLOYMENT_SEGWIT
].nTimeout
!= 0) {
2864 if (commitpos
== -1) {
2865 uint256 witnessroot
= BlockWitnessMerkleRoot(block
, NULL
);
2866 CHash256().Write(witnessroot
.begin(), 32).Write(&ret
[0], 32).Finalize(witnessroot
.begin());
2869 out
.scriptPubKey
.resize(38);
2870 out
.scriptPubKey
[0] = OP_RETURN
;
2871 out
.scriptPubKey
[1] = 0x24;
2872 out
.scriptPubKey
[2] = 0xaa;
2873 out
.scriptPubKey
[3] = 0x21;
2874 out
.scriptPubKey
[4] = 0xa9;
2875 out
.scriptPubKey
[5] = 0xed;
2876 memcpy(&out
.scriptPubKey
[6], witnessroot
.begin(), 32);
2877 commitment
= std::vector
<unsigned char>(out
.scriptPubKey
.begin(), out
.scriptPubKey
.end());
2878 CMutableTransaction
tx(*block
.vtx
[0]);
2879 tx
.vout
.push_back(out
);
2880 block
.vtx
[0] = MakeTransactionRef(std::move(tx
));
2883 UpdateUncommittedBlockStructures(block
, pindexPrev
, consensusParams
);
2887 bool ContextualCheckBlockHeader(const CBlockHeader
& block
, CValidationState
& state
, const Consensus::Params
& consensusParams
, const CBlockIndex
* pindexPrev
, int64_t nAdjustedTime
)
2889 const int nHeight
= pindexPrev
== NULL
? 0 : pindexPrev
->nHeight
+ 1;
2890 // Check proof of work
2891 if (block
.nBits
!= GetNextWorkRequired(pindexPrev
, &block
, consensusParams
))
2892 return state
.DoS(100, false, REJECT_INVALID
, "bad-diffbits", false, "incorrect proof of work");
2894 // Check timestamp against prev
2895 if (block
.GetBlockTime() <= pindexPrev
->GetMedianTimePast())
2896 return state
.Invalid(false, REJECT_INVALID
, "time-too-old", "block's timestamp is too early");
2899 if (block
.GetBlockTime() > nAdjustedTime
+ 2 * 60 * 60)
2900 return state
.Invalid(false, REJECT_INVALID
, "time-too-new", "block timestamp too far in the future");
2902 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2903 // check for version 2, 3 and 4 upgrades
2904 if((block
.nVersion
< 2 && nHeight
>= consensusParams
.BIP34Height
) ||
2905 (block
.nVersion
< 3 && nHeight
>= consensusParams
.BIP66Height
) ||
2906 (block
.nVersion
< 4 && nHeight
>= consensusParams
.BIP65Height
))
2907 return state
.Invalid(false, REJECT_OBSOLETE
, strprintf("bad-version(0x%08x)", block
.nVersion
),
2908 strprintf("rejected nVersion=0x%08x block", block
.nVersion
));
2913 bool ContextualCheckBlock(const CBlock
& block
, CValidationState
& state
, const Consensus::Params
& consensusParams
, const CBlockIndex
* pindexPrev
)
2915 const int nHeight
= pindexPrev
== NULL
? 0 : pindexPrev
->nHeight
+ 1;
2917 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
2918 int nLockTimeFlags
= 0;
2919 if (VersionBitsState(pindexPrev
, consensusParams
, Consensus::DEPLOYMENT_CSV
, versionbitscache
) == THRESHOLD_ACTIVE
) {
2920 nLockTimeFlags
|= LOCKTIME_MEDIAN_TIME_PAST
;
2923 int64_t nLockTimeCutoff
= (nLockTimeFlags
& LOCKTIME_MEDIAN_TIME_PAST
)
2924 ? pindexPrev
->GetMedianTimePast()
2925 : block
.GetBlockTime();
2927 // Check that all transactions are finalized
2928 for (const auto& tx
: block
.vtx
) {
2929 if (!IsFinalTx(*tx
, nHeight
, nLockTimeCutoff
)) {
2930 return state
.DoS(10, false, REJECT_INVALID
, "bad-txns-nonfinal", false, "non-final transaction");
2934 // Enforce rule that the coinbase starts with serialized block height
2935 if (nHeight
>= consensusParams
.BIP34Height
)
2937 CScript expect
= CScript() << nHeight
;
2938 if (block
.vtx
[0]->vin
[0].scriptSig
.size() < expect
.size() ||
2939 !std::equal(expect
.begin(), expect
.end(), block
.vtx
[0]->vin
[0].scriptSig
.begin())) {
2940 return state
.DoS(100, false, REJECT_INVALID
, "bad-cb-height", false, "block height mismatch in coinbase");
2944 // Validation for witness commitments.
2945 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
2946 // coinbase (where 0x0000....0000 is used instead).
2947 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
2948 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
2949 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
2950 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
2951 // multiple, the last one is used.
2952 bool fHaveWitness
= false;
2953 if (VersionBitsState(pindexPrev
, consensusParams
, Consensus::DEPLOYMENT_SEGWIT
, versionbitscache
) == THRESHOLD_ACTIVE
) {
2954 int commitpos
= GetWitnessCommitmentIndex(block
);
2955 if (commitpos
!= -1) {
2956 bool malleated
= false;
2957 uint256 hashWitness
= BlockWitnessMerkleRoot(block
, &malleated
);
2958 // The malleation check is ignored; as the transaction tree itself
2959 // already does not permit it, it is impossible to trigger in the
2961 if (block
.vtx
[0]->wit
.vtxinwit
.size() != 1 || block
.vtx
[0]->wit
.vtxinwit
[0].scriptWitness
.stack
.size() != 1 || block
.vtx
[0]->wit
.vtxinwit
[0].scriptWitness
.stack
[0].size() != 32) {
2962 return state
.DoS(100, false, REJECT_INVALID
, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__
));
2964 CHash256().Write(hashWitness
.begin(), 32).Write(&block
.vtx
[0]->wit
.vtxinwit
[0].scriptWitness
.stack
[0][0], 32).Finalize(hashWitness
.begin());
2965 if (memcmp(hashWitness
.begin(), &block
.vtx
[0]->vout
[commitpos
].scriptPubKey
[6], 32)) {
2966 return state
.DoS(100, false, REJECT_INVALID
, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__
));
2968 fHaveWitness
= true;
2972 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
2973 if (!fHaveWitness
) {
2974 for (size_t i
= 0; i
< block
.vtx
.size(); i
++) {
2975 if (!block
.vtx
[i
]->wit
.IsNull()) {
2976 return state
.DoS(100, false, REJECT_INVALID
, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__
));
2981 // After the coinbase witness nonce and commitment are verified,
2982 // we can check if the block weight passes (before we've checked the
2983 // coinbase witness, it would be possible for the weight to be too
2984 // large by filling up the coinbase witness, which doesn't change
2985 // the block hash, so we couldn't mark the block as permanently
2987 if (GetBlockWeight(block
) > MAX_BLOCK_WEIGHT
) {
2988 return state
.DoS(100, false, REJECT_INVALID
, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__
));
2994 static bool AcceptBlockHeader(const CBlockHeader
& block
, CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
** ppindex
)
2996 AssertLockHeld(cs_main
);
2997 // Check for duplicate
2998 uint256 hash
= block
.GetHash();
2999 BlockMap::iterator miSelf
= mapBlockIndex
.find(hash
);
3000 CBlockIndex
*pindex
= NULL
;
3001 if (hash
!= chainparams
.GetConsensus().hashGenesisBlock
) {
3003 if (miSelf
!= mapBlockIndex
.end()) {
3004 // Block header is already known.
3005 pindex
= miSelf
->second
;
3008 if (pindex
->nStatus
& BLOCK_FAILED_MASK
)
3009 return state
.Invalid(error("%s: block %s is marked invalid", __func__
, hash
.ToString()), 0, "duplicate");
3013 if (!CheckBlockHeader(block
, state
, chainparams
.GetConsensus()))
3014 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__
, hash
.ToString(), FormatStateMessage(state
));
3016 // Get prev block index
3017 CBlockIndex
* pindexPrev
= NULL
;
3018 BlockMap::iterator mi
= mapBlockIndex
.find(block
.hashPrevBlock
);
3019 if (mi
== mapBlockIndex
.end())
3020 return state
.DoS(10, error("%s: prev block not found", __func__
), 0, "bad-prevblk");
3021 pindexPrev
= (*mi
).second
;
3022 if (pindexPrev
->nStatus
& BLOCK_FAILED_MASK
)
3023 return state
.DoS(100, error("%s: prev block invalid", __func__
), REJECT_INVALID
, "bad-prevblk");
3026 if (fCheckpointsEnabled
&& !CheckIndexAgainstCheckpoint(pindexPrev
, state
, chainparams
, hash
))
3027 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__
, state
.GetRejectReason().c_str());
3029 if (!ContextualCheckBlockHeader(block
, state
, chainparams
.GetConsensus(), pindexPrev
, GetAdjustedTime()))
3030 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__
, hash
.ToString(), FormatStateMessage(state
));
3033 pindex
= AddToBlockIndex(block
);
3038 CheckBlockIndex(chainparams
.GetConsensus());
3043 // Exposed wrapper for AcceptBlockHeader
3044 bool ProcessNewBlockHeaders(const std::vector
<CBlockHeader
>& headers
, CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
** ppindex
)
3048 for (const CBlockHeader
& header
: headers
) {
3049 if (!AcceptBlockHeader(header
, state
, chainparams
, ppindex
)) {
3058 /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
3059 static bool AcceptBlock(const CBlock
& block
, CValidationState
& state
, const CChainParams
& chainparams
, CBlockIndex
** ppindex
, bool fRequested
, const CDiskBlockPos
* dbp
, bool* fNewBlock
)
3061 if (fNewBlock
) *fNewBlock
= false;
3062 AssertLockHeld(cs_main
);
3064 CBlockIndex
*pindexDummy
= NULL
;
3065 CBlockIndex
*&pindex
= ppindex
? *ppindex
: pindexDummy
;
3067 if (!AcceptBlockHeader(block
, state
, chainparams
, &pindex
))
3070 // Try to process all requested blocks that we don't have, but only
3071 // process an unrequested block if it's new and has enough work to
3072 // advance our tip, and isn't too many blocks ahead.
3073 bool fAlreadyHave
= pindex
->nStatus
& BLOCK_HAVE_DATA
;
3074 bool fHasMoreWork
= (chainActive
.Tip() ? pindex
->nChainWork
> chainActive
.Tip()->nChainWork
: true);
3075 // Blocks that are too out-of-order needlessly limit the effectiveness of
3076 // pruning, because pruning will not delete block files that contain any
3077 // blocks which are too close in height to the tip. Apply this test
3078 // regardless of whether pruning is enabled; it should generally be safe to
3079 // not process unrequested blocks.
3080 bool fTooFarAhead
= (pindex
->nHeight
> int(chainActive
.Height() + MIN_BLOCKS_TO_KEEP
));
3082 // TODO: Decouple this function from the block download logic by removing fRequested
3083 // This requires some new chain datastructure to efficiently look up if a
3084 // block is in a chain leading to a candidate for best tip, despite not
3085 // being such a candidate itself.
3087 // TODO: deal better with return value and error conditions for duplicate
3088 // and unrequested blocks.
3089 if (fAlreadyHave
) return true;
3090 if (!fRequested
) { // If we didn't ask for it:
3091 if (pindex
->nTx
!= 0) return true; // This is a previously-processed block that was pruned
3092 if (!fHasMoreWork
) return true; // Don't process less-work chains
3093 if (fTooFarAhead
) return true; // Block height is too high
3095 if (fNewBlock
) *fNewBlock
= true;
3097 if (!CheckBlock(block
, state
, chainparams
.GetConsensus(), GetAdjustedTime()) ||
3098 !ContextualCheckBlock(block
, state
, chainparams
.GetConsensus(), pindex
->pprev
)) {
3099 if (state
.IsInvalid() && !state
.CorruptionPossible()) {
3100 pindex
->nStatus
|= BLOCK_FAILED_VALID
;
3101 setDirtyBlockIndex
.insert(pindex
);
3103 return error("%s: %s", __func__
, FormatStateMessage(state
));
3106 int nHeight
= pindex
->nHeight
;
3108 // Write block to history file
3110 unsigned int nBlockSize
= ::GetSerializeSize(block
, SER_DISK
, CLIENT_VERSION
);
3111 CDiskBlockPos blockPos
;
3114 if (!FindBlockPos(state
, blockPos
, nBlockSize
+8, nHeight
, block
.GetBlockTime(), dbp
!= NULL
))
3115 return error("AcceptBlock(): FindBlockPos failed");
3117 if (!WriteBlockToDisk(block
, blockPos
, chainparams
.MessageStart()))
3118 AbortNode(state
, "Failed to write block");
3119 if (!ReceivedBlockTransactions(block
, state
, pindex
, blockPos
))
3120 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3121 } catch (const std::runtime_error
& e
) {
3122 return AbortNode(state
, std::string("System error: ") + e
.what());
3125 if (fCheckForPruning
)
3126 FlushStateToDisk(state
, FLUSH_STATE_NONE
); // we just allocated more disk space for block files
3131 bool ProcessNewBlock(const CChainParams
& chainparams
, const std::shared_ptr
<const CBlock
> pblock
, bool fForceProcessing
, const CDiskBlockPos
* dbp
, bool *fNewBlock
)
3137 CBlockIndex
*pindex
= NULL
;
3138 if (fNewBlock
) *fNewBlock
= false;
3139 CValidationState state
;
3140 bool ret
= AcceptBlock(*pblock
, state
, chainparams
, &pindex
, fForceProcessing
, dbp
, fNewBlock
);
3141 CheckBlockIndex(chainparams
.GetConsensus());
3143 GetMainSignals().BlockChecked(*pblock
, state
);
3144 return error("%s: AcceptBlock FAILED", __func__
);
3150 CValidationState state
; // Only used to report errors, not invalidity - ignore it
3151 if (!ActivateBestChain(state
, chainparams
, pblock
))
3152 return error("%s: ActivateBestChain failed", __func__
);
3157 bool TestBlockValidity(CValidationState
& state
, const CChainParams
& chainparams
, const CBlock
& block
, CBlockIndex
* pindexPrev
, bool fCheckPOW
, bool fCheckMerkleRoot
)
3159 AssertLockHeld(cs_main
);
3160 assert(pindexPrev
&& pindexPrev
== chainActive
.Tip());
3161 if (fCheckpointsEnabled
&& !CheckIndexAgainstCheckpoint(pindexPrev
, state
, chainparams
, block
.GetHash()))
3162 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__
, state
.GetRejectReason().c_str());
3164 CCoinsViewCache
viewNew(pcoinsTip
);
3165 CBlockIndex
indexDummy(block
);
3166 indexDummy
.pprev
= pindexPrev
;
3167 indexDummy
.nHeight
= pindexPrev
->nHeight
+ 1;
3169 // NOTE: CheckBlockHeader is called by CheckBlock
3170 if (!ContextualCheckBlockHeader(block
, state
, chainparams
.GetConsensus(), pindexPrev
, GetAdjustedTime()))
3171 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__
, FormatStateMessage(state
));
3172 if (!CheckBlock(block
, state
, chainparams
.GetConsensus(), fCheckPOW
, fCheckMerkleRoot
))
3173 return error("%s: Consensus::CheckBlock: %s", __func__
, FormatStateMessage(state
));
3174 if (!ContextualCheckBlock(block
, state
, chainparams
.GetConsensus(), pindexPrev
))
3175 return error("%s: Consensus::ContextualCheckBlock: %s", __func__
, FormatStateMessage(state
));
3176 if (!ConnectBlock(block
, state
, &indexDummy
, viewNew
, chainparams
, true))
3178 assert(state
.IsValid());
3184 * BLOCK PRUNING CODE
3187 /* Calculate the amount of disk space the block & undo files currently use */
3188 uint64_t CalculateCurrentUsage()
3190 uint64_t retval
= 0;
3191 BOOST_FOREACH(const CBlockFileInfo
&file
, vinfoBlockFile
) {
3192 retval
+= file
.nSize
+ file
.nUndoSize
;
3197 /* Prune a block file (modify associated database entries)*/
3198 void PruneOneBlockFile(const int fileNumber
)
3200 for (BlockMap::iterator it
= mapBlockIndex
.begin(); it
!= mapBlockIndex
.end(); ++it
) {
3201 CBlockIndex
* pindex
= it
->second
;
3202 if (pindex
->nFile
== fileNumber
) {
3203 pindex
->nStatus
&= ~BLOCK_HAVE_DATA
;
3204 pindex
->nStatus
&= ~BLOCK_HAVE_UNDO
;
3206 pindex
->nDataPos
= 0;
3207 pindex
->nUndoPos
= 0;
3208 setDirtyBlockIndex
.insert(pindex
);
3210 // Prune from mapBlocksUnlinked -- any block we prune would have
3211 // to be downloaded again in order to consider its chain, at which
3212 // point it would be considered as a candidate for
3213 // mapBlocksUnlinked or setBlockIndexCandidates.
3214 std::pair
<std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
, std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
> range
= mapBlocksUnlinked
.equal_range(pindex
->pprev
);
3215 while (range
.first
!= range
.second
) {
3216 std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator _it
= range
.first
;
3218 if (_it
->second
== pindex
) {
3219 mapBlocksUnlinked
.erase(_it
);
3225 vinfoBlockFile
[fileNumber
].SetNull();
3226 setDirtyFileInfo
.insert(fileNumber
);
3230 void UnlinkPrunedFiles(std::set
<int>& setFilesToPrune
)
3232 for (set
<int>::iterator it
= setFilesToPrune
.begin(); it
!= setFilesToPrune
.end(); ++it
) {
3233 CDiskBlockPos
pos(*it
, 0);
3234 boost::filesystem::remove(GetBlockPosFilename(pos
, "blk"));
3235 boost::filesystem::remove(GetBlockPosFilename(pos
, "rev"));
3236 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__
, *it
);
3240 /* Calculate the block/rev files that should be deleted to remain under target*/
3241 void FindFilesToPrune(std::set
<int>& setFilesToPrune
, uint64_t nPruneAfterHeight
)
3243 LOCK2(cs_main
, cs_LastBlockFile
);
3244 if (chainActive
.Tip() == NULL
|| nPruneTarget
== 0) {
3247 if ((uint64_t)chainActive
.Tip()->nHeight
<= nPruneAfterHeight
) {
3251 unsigned int nLastBlockWeCanPrune
= chainActive
.Tip()->nHeight
- MIN_BLOCKS_TO_KEEP
;
3252 uint64_t nCurrentUsage
= CalculateCurrentUsage();
3253 // We don't check to prune until after we've allocated new space for files
3254 // So we should leave a buffer under our target to account for another allocation
3255 // before the next pruning.
3256 uint64_t nBuffer
= BLOCKFILE_CHUNK_SIZE
+ UNDOFILE_CHUNK_SIZE
;
3257 uint64_t nBytesToPrune
;
3260 if (nCurrentUsage
+ nBuffer
>= nPruneTarget
) {
3261 for (int fileNumber
= 0; fileNumber
< nLastBlockFile
; fileNumber
++) {
3262 nBytesToPrune
= vinfoBlockFile
[fileNumber
].nSize
+ vinfoBlockFile
[fileNumber
].nUndoSize
;
3264 if (vinfoBlockFile
[fileNumber
].nSize
== 0)
3267 if (nCurrentUsage
+ nBuffer
< nPruneTarget
) // are we below our target?
3270 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3271 if (vinfoBlockFile
[fileNumber
].nHeightLast
> nLastBlockWeCanPrune
)
3274 PruneOneBlockFile(fileNumber
);
3275 // Queue up the files for removal
3276 setFilesToPrune
.insert(fileNumber
);
3277 nCurrentUsage
-= nBytesToPrune
;
3282 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3283 nPruneTarget
/1024/1024, nCurrentUsage
/1024/1024,
3284 ((int64_t)nPruneTarget
- (int64_t)nCurrentUsage
)/1024/1024,
3285 nLastBlockWeCanPrune
, count
);
3288 bool CheckDiskSpace(uint64_t nAdditionalBytes
)
3290 uint64_t nFreeBytesAvailable
= boost::filesystem::space(GetDataDir()).available
;
3292 // Check for nMinDiskSpace bytes (currently 50MB)
3293 if (nFreeBytesAvailable
< nMinDiskSpace
+ nAdditionalBytes
)
3294 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3299 FILE* OpenDiskFile(const CDiskBlockPos
&pos
, const char *prefix
, bool fReadOnly
)
3303 boost::filesystem::path path
= GetBlockPosFilename(pos
, prefix
);
3304 boost::filesystem::create_directories(path
.parent_path());
3305 FILE* file
= fopen(path
.string().c_str(), "rb+");
3306 if (!file
&& !fReadOnly
)
3307 file
= fopen(path
.string().c_str(), "wb+");
3309 LogPrintf("Unable to open file %s\n", path
.string());
3313 if (fseek(file
, pos
.nPos
, SEEK_SET
)) {
3314 LogPrintf("Unable to seek to position %u of %s\n", pos
.nPos
, path
.string());
3322 FILE* OpenBlockFile(const CDiskBlockPos
&pos
, bool fReadOnly
) {
3323 return OpenDiskFile(pos
, "blk", fReadOnly
);
3326 FILE* OpenUndoFile(const CDiskBlockPos
&pos
, bool fReadOnly
) {
3327 return OpenDiskFile(pos
, "rev", fReadOnly
);
3330 boost::filesystem::path
GetBlockPosFilename(const CDiskBlockPos
&pos
, const char *prefix
)
3332 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix
, pos
.nFile
);
3335 CBlockIndex
* InsertBlockIndex(uint256 hash
)
3341 BlockMap::iterator mi
= mapBlockIndex
.find(hash
);
3342 if (mi
!= mapBlockIndex
.end())
3343 return (*mi
).second
;
3346 CBlockIndex
* pindexNew
= new CBlockIndex();
3348 throw runtime_error(std::string(__func__
) + ": new CBlockIndex failed");
3349 mi
= mapBlockIndex
.insert(make_pair(hash
, pindexNew
)).first
;
3350 pindexNew
->phashBlock
= &((*mi
).first
);
3355 bool static LoadBlockIndexDB(const CChainParams
& chainparams
)
3357 if (!pblocktree
->LoadBlockIndexGuts(InsertBlockIndex
))
3360 boost::this_thread::interruption_point();
3362 // Calculate nChainWork
3363 vector
<pair
<int, CBlockIndex
*> > vSortedByHeight
;
3364 vSortedByHeight
.reserve(mapBlockIndex
.size());
3365 BOOST_FOREACH(const PAIRTYPE(uint256
, CBlockIndex
*)& item
, mapBlockIndex
)
3367 CBlockIndex
* pindex
= item
.second
;
3368 vSortedByHeight
.push_back(make_pair(pindex
->nHeight
, pindex
));
3370 sort(vSortedByHeight
.begin(), vSortedByHeight
.end());
3371 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex
*)& item
, vSortedByHeight
)
3373 CBlockIndex
* pindex
= item
.second
;
3374 pindex
->nChainWork
= (pindex
->pprev
? pindex
->pprev
->nChainWork
: 0) + GetBlockProof(*pindex
);
3375 // We can link the chain of blocks for which we've received transactions at some point.
3376 // Pruned nodes may have deleted the block.
3377 if (pindex
->nTx
> 0) {
3378 if (pindex
->pprev
) {
3379 if (pindex
->pprev
->nChainTx
) {
3380 pindex
->nChainTx
= pindex
->pprev
->nChainTx
+ pindex
->nTx
;
3382 pindex
->nChainTx
= 0;
3383 mapBlocksUnlinked
.insert(std::make_pair(pindex
->pprev
, pindex
));
3386 pindex
->nChainTx
= pindex
->nTx
;
3389 if (pindex
->IsValid(BLOCK_VALID_TRANSACTIONS
) && (pindex
->nChainTx
|| pindex
->pprev
== NULL
))
3390 setBlockIndexCandidates
.insert(pindex
);
3391 if (pindex
->nStatus
& BLOCK_FAILED_MASK
&& (!pindexBestInvalid
|| pindex
->nChainWork
> pindexBestInvalid
->nChainWork
))
3392 pindexBestInvalid
= pindex
;
3394 pindex
->BuildSkip();
3395 if (pindex
->IsValid(BLOCK_VALID_TREE
) && (pindexBestHeader
== NULL
|| CBlockIndexWorkComparator()(pindexBestHeader
, pindex
)))
3396 pindexBestHeader
= pindex
;
3399 // Load block file info
3400 pblocktree
->ReadLastBlockFile(nLastBlockFile
);
3401 vinfoBlockFile
.resize(nLastBlockFile
+ 1);
3402 LogPrintf("%s: last block file = %i\n", __func__
, nLastBlockFile
);
3403 for (int nFile
= 0; nFile
<= nLastBlockFile
; nFile
++) {
3404 pblocktree
->ReadBlockFileInfo(nFile
, vinfoBlockFile
[nFile
]);
3406 LogPrintf("%s: last block file info: %s\n", __func__
, vinfoBlockFile
[nLastBlockFile
].ToString());
3407 for (int nFile
= nLastBlockFile
+ 1; true; nFile
++) {
3408 CBlockFileInfo info
;
3409 if (pblocktree
->ReadBlockFileInfo(nFile
, info
)) {
3410 vinfoBlockFile
.push_back(info
);
3416 // Check presence of blk files
3417 LogPrintf("Checking all blk files are present...\n");
3418 set
<int> setBlkDataFiles
;
3419 BOOST_FOREACH(const PAIRTYPE(uint256
, CBlockIndex
*)& item
, mapBlockIndex
)
3421 CBlockIndex
* pindex
= item
.second
;
3422 if (pindex
->nStatus
& BLOCK_HAVE_DATA
) {
3423 setBlkDataFiles
.insert(pindex
->nFile
);
3426 for (std::set
<int>::iterator it
= setBlkDataFiles
.begin(); it
!= setBlkDataFiles
.end(); it
++)
3428 CDiskBlockPos
pos(*it
, 0);
3429 if (CAutoFile(OpenBlockFile(pos
, true), SER_DISK
, CLIENT_VERSION
).IsNull()) {
3434 // Check whether we have ever pruned block & undo files
3435 pblocktree
->ReadFlag("prunedblockfiles", fHavePruned
);
3437 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3439 // Check whether we need to continue reindexing
3440 bool fReindexing
= false;
3441 pblocktree
->ReadReindexing(fReindexing
);
3442 fReindex
|= fReindexing
;
3444 // Check whether we have a transaction index
3445 pblocktree
->ReadFlag("txindex", fTxIndex
);
3446 LogPrintf("%s: transaction index %s\n", __func__
, fTxIndex
? "enabled" : "disabled");
3448 // Load pointer to end of best chain
3449 BlockMap::iterator it
= mapBlockIndex
.find(pcoinsTip
->GetBestBlock());
3450 if (it
== mapBlockIndex
.end())
3452 chainActive
.SetTip(it
->second
);
3454 PruneBlockIndexCandidates();
3456 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__
,
3457 chainActive
.Tip()->GetBlockHash().ToString(), chainActive
.Height(),
3458 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive
.Tip()->GetBlockTime()),
3459 Checkpoints::GuessVerificationProgress(chainparams
.Checkpoints(), chainActive
.Tip()));
3464 CVerifyDB::CVerifyDB()
3466 uiInterface
.ShowProgress(_("Verifying blocks..."), 0);
3469 CVerifyDB::~CVerifyDB()
3471 uiInterface
.ShowProgress("", 100);
3474 bool CVerifyDB::VerifyDB(const CChainParams
& chainparams
, CCoinsView
*coinsview
, int nCheckLevel
, int nCheckDepth
)
3477 if (chainActive
.Tip() == NULL
|| chainActive
.Tip()->pprev
== NULL
)
3480 // Verify blocks in the best chain
3481 if (nCheckDepth
<= 0)
3482 nCheckDepth
= 1000000000; // suffices until the year 19000
3483 if (nCheckDepth
> chainActive
.Height())
3484 nCheckDepth
= chainActive
.Height();
3485 nCheckLevel
= std::max(0, std::min(4, nCheckLevel
));
3486 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth
, nCheckLevel
);
3487 CCoinsViewCache
coins(coinsview
);
3488 CBlockIndex
* pindexState
= chainActive
.Tip();
3489 CBlockIndex
* pindexFailure
= NULL
;
3490 int nGoodTransactions
= 0;
3491 CValidationState state
;
3493 LogPrintf("[0%%]...");
3494 for (CBlockIndex
* pindex
= chainActive
.Tip(); pindex
&& pindex
->pprev
; pindex
= pindex
->pprev
)
3496 boost::this_thread::interruption_point();
3497 int percentageDone
= std::max(1, std::min(99, (int)(((double)(chainActive
.Height() - pindex
->nHeight
)) / (double)nCheckDepth
* (nCheckLevel
>= 4 ? 50 : 100))));
3498 if (reportDone
< percentageDone
/10) {
3499 // report every 10% step
3500 LogPrintf("[%d%%]...", percentageDone
);
3501 reportDone
= percentageDone
/10;
3503 uiInterface
.ShowProgress(_("Verifying blocks..."), percentageDone
);
3504 if (pindex
->nHeight
< chainActive
.Height()-nCheckDepth
)
3506 if (fPruneMode
&& !(pindex
->nStatus
& BLOCK_HAVE_DATA
)) {
3507 // If pruning, only go back as far as we have data.
3508 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex
->nHeight
);
3512 // check level 0: read from disk
3513 if (!ReadBlockFromDisk(block
, pindex
, chainparams
.GetConsensus()))
3514 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
3515 // check level 1: verify block validity
3516 if (nCheckLevel
>= 1 && !CheckBlock(block
, state
, chainparams
.GetConsensus()))
3517 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__
,
3518 pindex
->nHeight
, pindex
->GetBlockHash().ToString(), FormatStateMessage(state
));
3519 // check level 2: verify undo validity
3520 if (nCheckLevel
>= 2 && pindex
) {
3522 CDiskBlockPos pos
= pindex
->GetUndoPos();
3523 if (!pos
.IsNull()) {
3524 if (!UndoReadFromDisk(undo
, pos
, pindex
->pprev
->GetBlockHash()))
3525 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
3528 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3529 if (nCheckLevel
>= 3 && pindex
== pindexState
&& (coins
.DynamicMemoryUsage() + pcoinsTip
->DynamicMemoryUsage()) <= nCoinCacheUsage
) {
3531 if (!DisconnectBlock(block
, state
, pindex
, coins
, &fClean
))
3532 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
3533 pindexState
= pindex
->pprev
;
3535 nGoodTransactions
= 0;
3536 pindexFailure
= pindex
;
3538 nGoodTransactions
+= block
.vtx
.size();
3540 if (ShutdownRequested())
3544 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive
.Height() - pindexFailure
->nHeight
+ 1, nGoodTransactions
);
3546 // check level 4: try reconnecting blocks
3547 if (nCheckLevel
>= 4) {
3548 CBlockIndex
*pindex
= pindexState
;
3549 while (pindex
!= chainActive
.Tip()) {
3550 boost::this_thread::interruption_point();
3551 uiInterface
.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive
.Height() - pindex
->nHeight
)) / (double)nCheckDepth
* 50))));
3552 pindex
= chainActive
.Next(pindex
);
3554 if (!ReadBlockFromDisk(block
, pindex
, chainparams
.GetConsensus()))
3555 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
3556 if (!ConnectBlock(block
, state
, pindex
, coins
, chainparams
))
3557 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex
->nHeight
, pindex
->GetBlockHash().ToString());
3561 LogPrintf("[DONE].\n");
3562 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive
.Height() - pindexState
->nHeight
, nGoodTransactions
);
3567 bool RewindBlockIndex(const CChainParams
& params
)
3572 while (nHeight
<= chainActive
.Height()) {
3573 if (IsWitnessEnabled(chainActive
[nHeight
- 1], params
.GetConsensus()) && !(chainActive
[nHeight
]->nStatus
& BLOCK_OPT_WITNESS
)) {
3579 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3580 CValidationState state
;
3581 CBlockIndex
* pindex
= chainActive
.Tip();
3582 while (chainActive
.Height() >= nHeight
) {
3583 if (fPruneMode
&& !(chainActive
.Tip()->nStatus
& BLOCK_HAVE_DATA
)) {
3584 // If pruning, don't try rewinding past the HAVE_DATA point;
3585 // since older blocks can't be served anyway, there's
3586 // no need to walk further, and trying to DisconnectTip()
3587 // will fail (and require a needless reindex/redownload
3588 // of the blockchain).
3591 if (!DisconnectTip(state
, params
, true)) {
3592 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex
->nHeight
);
3594 // Occasionally flush state to disk.
3595 if (!FlushStateToDisk(state
, FLUSH_STATE_PERIODIC
))
3599 // Reduce validity flag and have-data flags.
3600 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3601 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3602 for (BlockMap::iterator it
= mapBlockIndex
.begin(); it
!= mapBlockIndex
.end(); it
++) {
3603 CBlockIndex
* pindexIter
= it
->second
;
3605 // Note: If we encounter an insufficiently validated block that
3606 // is on chainActive, it must be because we are a pruning node, and
3607 // this block or some successor doesn't HAVE_DATA, so we were unable to
3608 // rewind all the way. Blocks remaining on chainActive at this point
3609 // must not have their validity reduced.
3610 if (IsWitnessEnabled(pindexIter
->pprev
, params
.GetConsensus()) && !(pindexIter
->nStatus
& BLOCK_OPT_WITNESS
) && !chainActive
.Contains(pindexIter
)) {
3612 pindexIter
->nStatus
= std::min
<unsigned int>(pindexIter
->nStatus
& BLOCK_VALID_MASK
, BLOCK_VALID_TREE
) | (pindexIter
->nStatus
& ~BLOCK_VALID_MASK
);
3613 // Remove have-data flags.
3614 pindexIter
->nStatus
&= ~(BLOCK_HAVE_DATA
| BLOCK_HAVE_UNDO
);
3615 // Remove storage location.
3616 pindexIter
->nFile
= 0;
3617 pindexIter
->nDataPos
= 0;
3618 pindexIter
->nUndoPos
= 0;
3619 // Remove various other things
3620 pindexIter
->nTx
= 0;
3621 pindexIter
->nChainTx
= 0;
3622 pindexIter
->nSequenceId
= 0;
3623 // Make sure it gets written.
3624 setDirtyBlockIndex
.insert(pindexIter
);
3626 setBlockIndexCandidates
.erase(pindexIter
);
3627 std::pair
<std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
, std::multimap
<CBlockIndex
*, CBlockIndex
*>::iterator
> ret
= mapBlocksUnlinked
.equal_range(pindexIter
->pprev
);
3628 while (ret
.first
!= ret
.second
) {
3629 if (ret
.first
->second
== pindexIter
) {
3630 mapBlocksUnlinked
.erase(ret
.first
++);
3635 } else if (pindexIter
->IsValid(BLOCK_VALID_TRANSACTIONS
) && pindexIter
->nChainTx
) {
3636 setBlockIndexCandidates
.insert(pindexIter
);
3640 PruneBlockIndexCandidates();
3642 CheckBlockIndex(params
.GetConsensus());
3644 if (!FlushStateToDisk(state
, FLUSH_STATE_ALWAYS
)) {
3651 // May NOT be used after any connections are up as much
3652 // of the peer-processing logic assumes a consistent
3653 // block index state
3654 void UnloadBlockIndex()
3657 setBlockIndexCandidates
.clear();
3658 chainActive
.SetTip(NULL
);
3659 pindexBestInvalid
= NULL
;
3660 pindexBestHeader
= NULL
;
3662 mapBlocksUnlinked
.clear();
3663 vinfoBlockFile
.clear();
3665 nBlockSequenceId
= 1;
3666 setDirtyBlockIndex
.clear();
3667 setDirtyFileInfo
.clear();
3668 versionbitscache
.Clear();
3669 for (int b
= 0; b
< VERSIONBITS_NUM_BITS
; b
++) {
3670 warningcache
[b
].clear();
3673 BOOST_FOREACH(BlockMap::value_type
& entry
, mapBlockIndex
) {
3674 delete entry
.second
;
3676 mapBlockIndex
.clear();
3677 fHavePruned
= false;
3680 bool LoadBlockIndex(const CChainParams
& chainparams
)
3682 // Load block index from databases
3683 if (!fReindex
&& !LoadBlockIndexDB(chainparams
))
3688 bool InitBlockIndex(const CChainParams
& chainparams
)
3692 // Check whether we're already initialized
3693 if (chainActive
.Genesis() != NULL
)
3696 // Use the provided setting for -txindex in the new database
3697 fTxIndex
= GetBoolArg("-txindex", DEFAULT_TXINDEX
);
3698 pblocktree
->WriteFlag("txindex", fTxIndex
);
3699 LogPrintf("Initializing databases...\n");
3701 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3704 CBlock
&block
= const_cast<CBlock
&>(chainparams
.GenesisBlock());
3705 // Start new block file
3706 unsigned int nBlockSize
= ::GetSerializeSize(block
, SER_DISK
, CLIENT_VERSION
);
3707 CDiskBlockPos blockPos
;
3708 CValidationState state
;
3709 if (!FindBlockPos(state
, blockPos
, nBlockSize
+8, 0, block
.GetBlockTime()))
3710 return error("LoadBlockIndex(): FindBlockPos failed");
3711 if (!WriteBlockToDisk(block
, blockPos
, chainparams
.MessageStart()))
3712 return error("LoadBlockIndex(): writing genesis block to disk failed");
3713 CBlockIndex
*pindex
= AddToBlockIndex(block
);
3714 if (!ReceivedBlockTransactions(block
, state
, pindex
, blockPos
))
3715 return error("LoadBlockIndex(): genesis block not accepted");
3716 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3717 return FlushStateToDisk(state
, FLUSH_STATE_ALWAYS
);
3718 } catch (const std::runtime_error
& e
) {
3719 return error("LoadBlockIndex(): failed to initialize block database: %s", e
.what());
3726 bool LoadExternalBlockFile(const CChainParams
& chainparams
, FILE* fileIn
, CDiskBlockPos
*dbp
)
3728 // Map of disk positions for blocks with unknown parent (only used for reindex)
3729 static std::multimap
<uint256
, CDiskBlockPos
> mapBlocksUnknownParent
;
3730 int64_t nStart
= GetTimeMillis();
3734 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3735 CBufferedFile
blkdat(fileIn
, 2*MAX_BLOCK_SERIALIZED_SIZE
, MAX_BLOCK_SERIALIZED_SIZE
+8, SER_DISK
, CLIENT_VERSION
);
3736 uint64_t nRewind
= blkdat
.GetPos();
3737 while (!blkdat
.eof()) {
3738 boost::this_thread::interruption_point();
3740 blkdat
.SetPos(nRewind
);
3741 nRewind
++; // start one byte further next time, in case of failure
3742 blkdat
.SetLimit(); // remove former limit
3743 unsigned int nSize
= 0;
3746 unsigned char buf
[CMessageHeader::MESSAGE_START_SIZE
];
3747 blkdat
.FindByte(chainparams
.MessageStart()[0]);
3748 nRewind
= blkdat
.GetPos()+1;
3749 blkdat
>> FLATDATA(buf
);
3750 if (memcmp(buf
, chainparams
.MessageStart(), CMessageHeader::MESSAGE_START_SIZE
))
3754 if (nSize
< 80 || nSize
> MAX_BLOCK_SERIALIZED_SIZE
)
3756 } catch (const std::exception
&) {
3757 // no valid block header found; don't complain
3762 uint64_t nBlockPos
= blkdat
.GetPos();
3764 dbp
->nPos
= nBlockPos
;
3765 blkdat
.SetLimit(nBlockPos
+ nSize
);
3766 blkdat
.SetPos(nBlockPos
);
3769 nRewind
= blkdat
.GetPos();
3771 // detect out of order blocks, and store them for later
3772 uint256 hash
= block
.GetHash();
3773 if (hash
!= chainparams
.GetConsensus().hashGenesisBlock
&& mapBlockIndex
.find(block
.hashPrevBlock
) == mapBlockIndex
.end()) {
3774 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__
, hash
.ToString(),
3775 block
.hashPrevBlock
.ToString());
3777 mapBlocksUnknownParent
.insert(std::make_pair(block
.hashPrevBlock
, *dbp
));
3781 // process in case the block isn't known yet
3782 if (mapBlockIndex
.count(hash
) == 0 || (mapBlockIndex
[hash
]->nStatus
& BLOCK_HAVE_DATA
) == 0) {
3784 CValidationState state
;
3785 if (AcceptBlock(block
, state
, chainparams
, NULL
, true, dbp
, NULL
))
3787 if (state
.IsError())
3789 } else if (hash
!= chainparams
.GetConsensus().hashGenesisBlock
&& mapBlockIndex
[hash
]->nHeight
% 1000 == 0) {
3790 LogPrint("reindex", "Block Import: already had block %s at height %d\n", hash
.ToString(), mapBlockIndex
[hash
]->nHeight
);
3793 // Activate the genesis block so normal node progress can continue
3794 if (hash
== chainparams
.GetConsensus().hashGenesisBlock
) {
3795 CValidationState state
;
3796 if (!ActivateBestChain(state
, chainparams
)) {
3803 // Recursively process earlier encountered successors of this block
3804 deque
<uint256
> queue
;
3805 queue
.push_back(hash
);
3806 while (!queue
.empty()) {
3807 uint256 head
= queue
.front();
3809 std::pair
<std::multimap
<uint256
, CDiskBlockPos
>::iterator
, std::multimap
<uint256
, CDiskBlockPos
>::iterator
> range
= mapBlocksUnknownParent
.equal_range(head
);
3810 while (range
.first
!= range
.second
) {
3811 std::multimap
<uint256
, CDiskBlockPos
>::iterator it
= range
.first
;
3812 if (ReadBlockFromDisk(block
, it
->second
, chainparams
.GetConsensus()))
3814 LogPrint("reindex", "%s: Processing out of order child %s of %s\n", __func__
, block
.GetHash().ToString(),
3817 CValidationState dummy
;
3818 if (AcceptBlock(block
, dummy
, chainparams
, NULL
, true, &it
->second
, NULL
))
3821 queue
.push_back(block
.GetHash());
3825 mapBlocksUnknownParent
.erase(it
);
3829 } catch (const std::exception
& e
) {
3830 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__
, e
.what());
3833 } catch (const std::runtime_error
& e
) {
3834 AbortNode(std::string("System error: ") + e
.what());
3837 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded
, GetTimeMillis() - nStart
);
3841 void static CheckBlockIndex(const Consensus::Params
& consensusParams
)
3843 if (!fCheckBlockIndex
) {
3849 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3850 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3851 // iterating the block tree require that chainActive has been initialized.)
3852 if (chainActive
.Height() < 0) {
3853 assert(mapBlockIndex
.size() <= 1);
3857 // Build forward-pointing map of the entire block tree.
3858 std::multimap
<CBlockIndex
*,CBlockIndex
*> forward
;
3859 for (BlockMap::iterator it
= mapBlockIndex
.begin(); it
!= mapBlockIndex
.end(); it
++) {
3860 forward
.insert(std::make_pair(it
->second
->pprev
, it
->second
));
3863 assert(forward
.size() == mapBlockIndex
.size());
3865 std::pair
<std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
,std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
> rangeGenesis
= forward
.equal_range(NULL
);
3866 CBlockIndex
*pindex
= rangeGenesis
.first
->second
;
3867 rangeGenesis
.first
++;
3868 assert(rangeGenesis
.first
== rangeGenesis
.second
); // There is only one index entry with parent NULL.
3870 // Iterate over the entire block tree, using depth-first search.
3871 // Along the way, remember whether there are blocks on the path from genesis
3872 // block being explored which are the first to have certain properties.
3875 CBlockIndex
* pindexFirstInvalid
= NULL
; // Oldest ancestor of pindex which is invalid.
3876 CBlockIndex
* pindexFirstMissing
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3877 CBlockIndex
* pindexFirstNeverProcessed
= NULL
; // Oldest ancestor of pindex for which nTx == 0.
3878 CBlockIndex
* pindexFirstNotTreeValid
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3879 CBlockIndex
* pindexFirstNotTransactionsValid
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3880 CBlockIndex
* pindexFirstNotChainValid
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3881 CBlockIndex
* pindexFirstNotScriptsValid
= NULL
; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3882 while (pindex
!= NULL
) {
3884 if (pindexFirstInvalid
== NULL
&& pindex
->nStatus
& BLOCK_FAILED_VALID
) pindexFirstInvalid
= pindex
;
3885 if (pindexFirstMissing
== NULL
&& !(pindex
->nStatus
& BLOCK_HAVE_DATA
)) pindexFirstMissing
= pindex
;
3886 if (pindexFirstNeverProcessed
== NULL
&& pindex
->nTx
== 0) pindexFirstNeverProcessed
= pindex
;
3887 if (pindex
->pprev
!= NULL
&& pindexFirstNotTreeValid
== NULL
&& (pindex
->nStatus
& BLOCK_VALID_MASK
) < BLOCK_VALID_TREE
) pindexFirstNotTreeValid
= pindex
;
3888 if (pindex
->pprev
!= NULL
&& pindexFirstNotTransactionsValid
== NULL
&& (pindex
->nStatus
& BLOCK_VALID_MASK
) < BLOCK_VALID_TRANSACTIONS
) pindexFirstNotTransactionsValid
= pindex
;
3889 if (pindex
->pprev
!= NULL
&& pindexFirstNotChainValid
== NULL
&& (pindex
->nStatus
& BLOCK_VALID_MASK
) < BLOCK_VALID_CHAIN
) pindexFirstNotChainValid
= pindex
;
3890 if (pindex
->pprev
!= NULL
&& pindexFirstNotScriptsValid
== NULL
&& (pindex
->nStatus
& BLOCK_VALID_MASK
) < BLOCK_VALID_SCRIPTS
) pindexFirstNotScriptsValid
= pindex
;
3892 // Begin: actual consistency checks.
3893 if (pindex
->pprev
== NULL
) {
3894 // Genesis block checks.
3895 assert(pindex
->GetBlockHash() == consensusParams
.hashGenesisBlock
); // Genesis block's hash must match.
3896 assert(pindex
== chainActive
.Genesis()); // The current active chain's genesis block must be this block.
3898 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)
3899 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3900 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3902 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3903 assert(!(pindex
->nStatus
& BLOCK_HAVE_DATA
) == (pindex
->nTx
== 0));
3904 assert(pindexFirstMissing
== pindexFirstNeverProcessed
);
3906 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3907 if (pindex
->nStatus
& BLOCK_HAVE_DATA
) assert(pindex
->nTx
> 0);
3909 if (pindex
->nStatus
& BLOCK_HAVE_UNDO
) assert(pindex
->nStatus
& BLOCK_HAVE_DATA
);
3910 assert(((pindex
->nStatus
& BLOCK_VALID_MASK
) >= BLOCK_VALID_TRANSACTIONS
) == (pindex
->nTx
> 0)); // This is pruning-independent.
3911 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3912 assert((pindexFirstNeverProcessed
!= NULL
) == (pindex
->nChainTx
== 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3913 assert((pindexFirstNotTransactionsValid
!= NULL
) == (pindex
->nChainTx
== 0));
3914 assert(pindex
->nHeight
== nHeight
); // nHeight must be consistent.
3915 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.
3916 assert(nHeight
< 2 || (pindex
->pskip
&& (pindex
->pskip
->nHeight
< nHeight
))); // The pskip pointer must point back for all but the first 2 blocks.
3917 assert(pindexFirstNotTreeValid
== NULL
); // All mapBlockIndex entries must at least be TREE valid
3918 if ((pindex
->nStatus
& BLOCK_VALID_MASK
) >= BLOCK_VALID_TREE
) assert(pindexFirstNotTreeValid
== NULL
); // TREE valid implies all parents are TREE valid
3919 if ((pindex
->nStatus
& BLOCK_VALID_MASK
) >= BLOCK_VALID_CHAIN
) assert(pindexFirstNotChainValid
== NULL
); // CHAIN valid implies all parents are CHAIN valid
3920 if ((pindex
->nStatus
& BLOCK_VALID_MASK
) >= BLOCK_VALID_SCRIPTS
) assert(pindexFirstNotScriptsValid
== NULL
); // SCRIPTS valid implies all parents are SCRIPTS valid
3921 if (pindexFirstInvalid
== NULL
) {
3922 // Checks for not-invalid blocks.
3923 assert((pindex
->nStatus
& BLOCK_FAILED_MASK
) == 0); // The failed mask cannot be set for blocks without invalid parents.
3925 if (!CBlockIndexWorkComparator()(pindex
, chainActive
.Tip()) && pindexFirstNeverProcessed
== NULL
) {
3926 if (pindexFirstInvalid
== NULL
) {
3927 // If this block sorts at least as good as the current tip and
3928 // is valid and we have all data for its parents, it must be in
3929 // setBlockIndexCandidates. chainActive.Tip() must also be there
3930 // even if some data has been pruned.
3931 if (pindexFirstMissing
== NULL
|| pindex
== chainActive
.Tip()) {
3932 assert(setBlockIndexCandidates
.count(pindex
));
3934 // If some parent is missing, then it could be that this block was in
3935 // setBlockIndexCandidates but had to be removed because of the missing data.
3936 // In this case it must be in mapBlocksUnlinked -- see test below.
3938 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3939 assert(setBlockIndexCandidates
.count(pindex
) == 0);
3941 // Check whether this block is in mapBlocksUnlinked.
3942 std::pair
<std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
,std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
> rangeUnlinked
= mapBlocksUnlinked
.equal_range(pindex
->pprev
);
3943 bool foundInUnlinked
= false;
3944 while (rangeUnlinked
.first
!= rangeUnlinked
.second
) {
3945 assert(rangeUnlinked
.first
->first
== pindex
->pprev
);
3946 if (rangeUnlinked
.first
->second
== pindex
) {
3947 foundInUnlinked
= true;
3950 rangeUnlinked
.first
++;
3952 if (pindex
->pprev
&& (pindex
->nStatus
& BLOCK_HAVE_DATA
) && pindexFirstNeverProcessed
!= NULL
&& pindexFirstInvalid
== NULL
) {
3953 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3954 assert(foundInUnlinked
);
3956 if (!(pindex
->nStatus
& BLOCK_HAVE_DATA
)) assert(!foundInUnlinked
); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3957 if (pindexFirstMissing
== NULL
) assert(!foundInUnlinked
); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3958 if (pindex
->pprev
&& (pindex
->nStatus
& BLOCK_HAVE_DATA
) && pindexFirstNeverProcessed
== NULL
&& pindexFirstMissing
!= NULL
) {
3959 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3960 assert(fHavePruned
); // We must have pruned.
3961 // This block may have entered mapBlocksUnlinked if:
3962 // - it has a descendant that at some point had more work than the
3964 // - we tried switching to that descendant but were missing
3965 // data for some intermediate block between chainActive and the
3967 // So if this block is itself better than chainActive.Tip() and it wasn't in
3968 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3969 if (!CBlockIndexWorkComparator()(pindex
, chainActive
.Tip()) && setBlockIndexCandidates
.count(pindex
) == 0) {
3970 if (pindexFirstInvalid
== NULL
) {
3971 assert(foundInUnlinked
);
3975 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
3976 // End: actual consistency checks.
3978 // Try descending into the first subnode.
3979 std::pair
<std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
,std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
> range
= forward
.equal_range(pindex
);
3980 if (range
.first
!= range
.second
) {
3981 // A subnode was found.
3982 pindex
= range
.first
->second
;
3986 // This is a leaf node.
3987 // Move upwards until we reach a node of which we have not yet visited the last child.
3989 // We are going to either move to a parent or a sibling of pindex.
3990 // If pindex was the first with a certain property, unset the corresponding variable.
3991 if (pindex
== pindexFirstInvalid
) pindexFirstInvalid
= NULL
;
3992 if (pindex
== pindexFirstMissing
) pindexFirstMissing
= NULL
;
3993 if (pindex
== pindexFirstNeverProcessed
) pindexFirstNeverProcessed
= NULL
;
3994 if (pindex
== pindexFirstNotTreeValid
) pindexFirstNotTreeValid
= NULL
;
3995 if (pindex
== pindexFirstNotTransactionsValid
) pindexFirstNotTransactionsValid
= NULL
;
3996 if (pindex
== pindexFirstNotChainValid
) pindexFirstNotChainValid
= NULL
;
3997 if (pindex
== pindexFirstNotScriptsValid
) pindexFirstNotScriptsValid
= NULL
;
3999 CBlockIndex
* pindexPar
= pindex
->pprev
;
4000 // Find which child we just visited.
4001 std::pair
<std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
,std::multimap
<CBlockIndex
*,CBlockIndex
*>::iterator
> rangePar
= forward
.equal_range(pindexPar
);
4002 while (rangePar
.first
->second
!= pindex
) {
4003 assert(rangePar
.first
!= rangePar
.second
); // Our parent must have at least the node we're coming from as child.
4006 // Proceed to the next one.
4008 if (rangePar
.first
!= rangePar
.second
) {
4009 // Move to the sibling.
4010 pindex
= rangePar
.first
->second
;
4021 // Check that we actually traversed the entire map.
4022 assert(nNodes
== forward
.size());
4025 std::string
GetWarnings(const std::string
& strFor
)
4027 string strStatusBar
;
4030 const string uiAlertSeperator
= "<hr />";
4032 if (!CLIENT_VERSION_IS_RELEASE
) {
4033 strStatusBar
= "This is a pre-release test build - use at your own risk - do not use for mining or merchant applications";
4034 strGUI
= _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4037 if (GetBoolArg("-testsafemode", DEFAULT_TESTSAFEMODE
))
4038 strStatusBar
= strRPC
= strGUI
= "testsafemode enabled";
4040 // Misc warnings like out of disk space and clock is wrong
4041 if (strMiscWarning
!= "")
4043 strStatusBar
= strMiscWarning
;
4044 strGUI
+= (strGUI
.empty() ? "" : uiAlertSeperator
) + strMiscWarning
;
4047 if (fLargeWorkForkFound
)
4049 strStatusBar
= strRPC
= "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.";
4050 strGUI
+= (strGUI
.empty() ? "" : uiAlertSeperator
) + _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4052 else if (fLargeWorkInvalidChainFound
)
4054 strStatusBar
= strRPC
= "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.";
4055 strGUI
+= (strGUI
.empty() ? "" : uiAlertSeperator
) + _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
4058 if (strFor
== "gui")
4060 else if (strFor
== "statusbar")
4061 return strStatusBar
;
4062 else if (strFor
== "rpc")
4064 assert(!"GetWarnings(): invalid parameter");
4067 std::string
CBlockFileInfo::ToString() const {
4068 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
));
4071 ThresholdState
VersionBitsTipState(const Consensus::Params
& params
, Consensus::DeploymentPos pos
)
4074 return VersionBitsState(chainActive
.Tip(), params
, pos
, versionbitscache
);
4077 int VersionBitsTipStateSinceHeight(const Consensus::Params
& params
, Consensus::DeploymentPos pos
)
4080 return VersionBitsStateSinceHeight(chainActive
.Tip(), params
, pos
, versionbitscache
);
4083 static const uint64_t MEMPOOL_DUMP_VERSION
= 1;
4085 bool LoadMempool(void)
4087 int64_t nExpiryTimeout
= GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY
) * 60 * 60;
4088 FILE* filestr
= fopen((GetDataDir() / "mempool.dat").string().c_str(), "r");
4089 CAutoFile
file(filestr
, SER_DISK
, CLIENT_VERSION
);
4090 if (file
.IsNull()) {
4091 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4096 int64_t skipped
= 0;
4098 int64_t nNow
= GetTime();
4103 if (version
!= MEMPOOL_DUMP_VERSION
) {
4108 double prioritydummy
= 0;
4112 CTransaction
tx(deserialize
, file
);
4116 CAmount amountdelta
= nFeeDelta
;
4118 mempool
.PrioritiseTransaction(tx
.GetHash(), tx
.GetHash().ToString(), prioritydummy
, amountdelta
);
4120 CValidationState state
;
4121 if (nTime
+ nExpiryTimeout
> nNow
) {
4123 AcceptToMemoryPoolWithTime(mempool
, state
, tx
, true, NULL
, nTime
);
4124 if (state
.IsValid()) {
4133 std::map
<uint256
, CAmount
> mapDeltas
;
4136 for (const auto& i
: mapDeltas
) {
4137 mempool
.PrioritiseTransaction(i
.first
, i
.first
.ToString(), prioritydummy
, i
.second
);
4139 } catch (const std::exception
& e
) {
4140 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e
.what());
4144 LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count
, failed
, skipped
);
4148 void DumpMempool(void)
4150 int64_t start
= GetTimeMicros();
4152 std::map
<uint256
, CAmount
> mapDeltas
;
4153 std::vector
<TxMempoolInfo
> vinfo
;
4157 for (const auto &i
: mempool
.mapDeltas
) {
4158 mapDeltas
[i
.first
] = i
.second
.first
;
4160 vinfo
= mempool
.infoAll();
4163 int64_t mid
= GetTimeMicros();
4166 FILE* filestr
= fopen((GetDataDir() / "mempool.dat.new").string().c_str(), "w");
4171 CAutoFile
file(filestr
, SER_DISK
, CLIENT_VERSION
);
4173 uint64_t version
= MEMPOOL_DUMP_VERSION
;
4176 file
<< (uint64_t)vinfo
.size();
4177 for (const auto& i
: vinfo
) {
4179 file
<< (int64_t)i
.nTime
;
4180 file
<< (int64_t)i
.nFeeDelta
;
4181 mapDeltas
.erase(i
.tx
->GetHash());
4185 FileCommit(file
.Get());
4187 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4188 int64_t last
= GetTimeMicros();
4189 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid
-start
)*0.000001, (last
-mid
)*0.000001);
4190 } catch (const std::exception
& e
) {
4191 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e
.what());
4201 BlockMap::iterator it1
= mapBlockIndex
.begin();
4202 for (; it1
!= mapBlockIndex
.end(); it1
++)
4203 delete (*it1
).second
;
4204 mapBlockIndex
.clear();
4206 } instance_of_cmaincleanup
;