1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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.
5
6 #include <validation.h>
7
8 #include <arith_uint256.h>
9 #include <chain.h>
10 #include <chainparams.h>
11 #include <checkqueue.h>
12 #include <consensus/consensus.h>
13 #include <consensus/merkle.h>
14 #include <consensus/tx_check.h>
15 #include <consensus/tx_verify.h>
16 #include <consensus/validation.h>
17 #include <cuckoocache.h>
18 #include <deploymentstatus.h>
19 #include <flatfile.h>
20 #include <hash.h>
21 #include <index/blockfilterindex.h>
22 #include <index/txindex.h>
23 #include <logging.h>
24 #include <logging/timer.h>
25 #include <node/blockstorage.h>
26 #include <node/coinstats.h>
27 #include <node/ui_interface.h>
28 #include <policy/policy.h>
29 #include <policy/settings.h>
30 #include <pow.h>
31 #include <primitives/block.h>
32 #include <primitives/transaction.h>
33 #include <random.h>
34 #include <reverse_iterator.h>
35 #include <script/script.h>
36 #include <script/sigcache.h>
37 #include <shutdown.h>
38 #include <signet.h>
39 #include <timedata.h>
40 #include <tinyformat.h>
41 #include <txdb.h>
42 #include <txmempool.h>
43 #include <uint256.h>
44 #include <undo.h>
45 #include <util/check.h> // For NDEBUG compile time check
46 #include <util/hasher.h>
47 #include <util/moneystr.h>
48 #include <util/rbf.h>
49 #include <util/strencodings.h>
50 #include <util/system.h>
51 #include <util/translation.h>
52 #include <validationinterface.h>
53 #include <warnings.h>
54
55 #include <numeric>
56 #include <optional>
57 #include <string>
58
59 #include <boost/algorithm/string/replace.hpp>
60
61 #define MICRO 0.000001
62 #define MILLI 0.001
63
64 /**
65 * An extra transaction can be added to a package, as long as it only has one
66 * ancestor and is no larger than this. Not really any reason to make this
67 * configurable as it doesn't materially change DoS parameters.
68 */
69 static const unsigned int EXTRA_DESCENDANT_TX_SIZE_LIMIT = 10000;
70 /** Maximum kilobytes for transactions to store for processing during reorg */
71 static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000;
72 /** Time to wait between writing blocks/block index to disk. */
73 static constexpr std::chrono::hours DATABASE_WRITE_INTERVAL{1};
74 /** Time to wait between flushing chainstate to disk. */
75 static constexpr std::chrono::hours DATABASE_FLUSH_INTERVAL{24};
76 /** Maximum age of our tip for us to be considered current for fee estimation */
77 static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE{3};
78 const std::vector<std::string> CHECKLEVEL_DOC {
79 "level 0 reads the blocks from disk",
80 "level 1 verifies block validity",
81 "level 2 verifies undo data",
82 "level 3 checks disconnection of tip blocks",
83 "level 4 tries to reconnect the blocks",
84 "each level includes the checks of the previous levels",
85 };
86
operator ()(const CBlockIndex * pa,const CBlockIndex * pb) const87 bool CBlockIndexWorkComparator::operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
88 // First sort by most total work, ...
89 if (pa->nChainWork > pb->nChainWork) return false;
90 if (pa->nChainWork < pb->nChainWork) return true;
91
92 // ... then by earliest time received, ...
93 if (pa->nSequenceId < pb->nSequenceId) return false;
94 if (pa->nSequenceId > pb->nSequenceId) return true;
95
96 // Use pointer address as tie breaker (should only happen with blocks
97 // loaded from disk, as those all have id 0).
98 if (pa < pb) return false;
99 if (pa > pb) return true;
100
101 // Identical blocks.
102 return false;
103 }
104
105 /**
106 * Mutex to guard access to validation specific variables, such as reading
107 * or changing the chainstate.
108 *
109 * This may also need to be locked when updating the transaction pool, e.g. on
110 * AcceptToMemoryPool. See CTxMemPool::cs comment for details.
111 *
112 * The transaction pool has a separate lock to allow reading from it and the
113 * chainstate at the same time.
114 */
115 RecursiveMutex cs_main;
116
117 CBlockIndex *pindexBestHeader = nullptr;
118 Mutex g_best_block_mutex;
119 std::condition_variable g_best_block_cv;
120 uint256 g_best_block;
121 bool g_parallel_script_checks{false};
122 bool fRequireStandard = true;
123 bool fCheckBlockIndex = false;
124 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
125 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
126
127 uint256 hashAssumeValid;
128 arith_uint256 nMinimumChainWork;
129
130 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
131
132 // Internal stuff
133 namespace {
134 CBlockIndex* pindexBestInvalid = nullptr;
135 } // namespace
136
137 // Internal stuff from blockstorage ...
138 extern RecursiveMutex cs_LastBlockFile;
139 extern std::vector<CBlockFileInfo> vinfoBlockFile;
140 extern int nLastBlockFile;
141 extern bool fCheckForPruning;
142 extern std::set<CBlockIndex*> setDirtyBlockIndex;
143 extern std::set<int> setDirtyFileInfo;
144 void FlushBlockFile(bool fFinalize = false, bool finalize_undo = false);
145 // ... TODO move fully to blockstorage
146
LookupBlockIndex(const uint256 & hash) const147 CBlockIndex* BlockManager::LookupBlockIndex(const uint256& hash) const
148 {
149 AssertLockHeld(cs_main);
150 BlockMap::const_iterator it = m_block_index.find(hash);
151 return it == m_block_index.end() ? nullptr : it->second;
152 }
153
FindForkInGlobalIndex(const CChain & chain,const CBlockLocator & locator)154 CBlockIndex* BlockManager::FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
155 {
156 AssertLockHeld(cs_main);
157
158 // Find the latest block common to locator and chain - we expect that
159 // locator.vHave is sorted descending by height.
160 for (const uint256& hash : locator.vHave) {
161 CBlockIndex* pindex = LookupBlockIndex(hash);
162 if (pindex) {
163 if (chain.Contains(pindex))
164 return pindex;
165 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
166 return chain.Tip();
167 }
168 }
169 }
170 return chain.Genesis();
171 }
172
173 std::unique_ptr<CBlockTreeDB> pblocktree;
174
175 bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
176 const CCoinsViewCache& inputs, unsigned int flags, bool cacheSigStore,
177 bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
178 std::vector<CScriptCheck>* pvChecks = nullptr)
179 EXCLUSIVE_LOCKS_REQUIRED(cs_main);
180
CheckFinalTx(const CBlockIndex * active_chain_tip,const CTransaction & tx,int flags)181 bool CheckFinalTx(const CBlockIndex* active_chain_tip, const CTransaction &tx, int flags)
182 {
183 AssertLockHeld(cs_main);
184 assert(active_chain_tip); // TODO: Make active_chain_tip a reference
185
186 // By convention a negative value for flags indicates that the
187 // current network-enforced consensus rules should be used. In
188 // a future soft-fork scenario that would mean checking which
189 // rules would be enforced for the next block and setting the
190 // appropriate flags. At the present time no soft-forks are
191 // scheduled, so no flags are set.
192 flags = std::max(flags, 0);
193
194 // CheckFinalTx() uses active_chain_tip.Height()+1 to evaluate
195 // nLockTime because when IsFinalTx() is called within
196 // CBlock::AcceptBlock(), the height of the block *being*
197 // evaluated is what is used. Thus if we want to know if a
198 // transaction can be part of the *next* block, we need to call
199 // IsFinalTx() with one more than active_chain_tip.Height().
200 const int nBlockHeight = active_chain_tip->nHeight + 1;
201
202 // BIP113 requires that time-locked transactions have nLockTime set to
203 // less than the median time of the previous block they're contained in.
204 // When the next block is created its previous block will be the current
205 // chain tip, so we use that to calculate the median time passed to
206 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
207 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
208 ? active_chain_tip->GetMedianTimePast()
209 : GetAdjustedTime();
210
211 return IsFinalTx(tx, nBlockHeight, nBlockTime);
212 }
213
TestLockPointValidity(CChain & active_chain,const LockPoints * lp)214 bool TestLockPointValidity(CChain& active_chain, const LockPoints* lp)
215 {
216 AssertLockHeld(cs_main);
217 assert(lp);
218 // If there are relative lock times then the maxInputBlock will be set
219 // If there are no relative lock times, the LockPoints don't depend on the chain
220 if (lp->maxInputBlock) {
221 // Check whether ::ChainActive() is an extension of the block at which the LockPoints
222 // calculation was valid. If not LockPoints are no longer valid
223 if (!active_chain.Contains(lp->maxInputBlock)) {
224 return false;
225 }
226 }
227
228 // LockPoints still valid
229 return true;
230 }
231
CheckSequenceLocks(CBlockIndex * tip,const CCoinsView & coins_view,const CTransaction & tx,int flags,LockPoints * lp,bool useExistingLockPoints)232 bool CheckSequenceLocks(CBlockIndex* tip,
233 const CCoinsView& coins_view,
234 const CTransaction& tx,
235 int flags,
236 LockPoints* lp,
237 bool useExistingLockPoints)
238 {
239 assert(tip != nullptr);
240
241 CBlockIndex index;
242 index.pprev = tip;
243 // CheckSequenceLocks() uses active_chainstate.m_chain.Height()+1 to evaluate
244 // height based locks because when SequenceLocks() is called within
245 // ConnectBlock(), the height of the block *being*
246 // evaluated is what is used.
247 // Thus if we want to know if a transaction can be part of the
248 // *next* block, we need to use one more than active_chainstate.m_chain.Height()
249 index.nHeight = tip->nHeight + 1;
250
251 std::pair<int, int64_t> lockPair;
252 if (useExistingLockPoints) {
253 assert(lp);
254 lockPair.first = lp->height;
255 lockPair.second = lp->time;
256 }
257 else {
258 std::vector<int> prevheights;
259 prevheights.resize(tx.vin.size());
260 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
261 const CTxIn& txin = tx.vin[txinIndex];
262 Coin coin;
263 if (!coins_view.GetCoin(txin.prevout, coin)) {
264 return error("%s: Missing input", __func__);
265 }
266 if (coin.nHeight == MEMPOOL_HEIGHT) {
267 // Assume all mempool transaction confirm in the next block
268 prevheights[txinIndex] = tip->nHeight + 1;
269 } else {
270 prevheights[txinIndex] = coin.nHeight;
271 }
272 }
273 lockPair = CalculateSequenceLocks(tx, flags, prevheights, index);
274 if (lp) {
275 lp->height = lockPair.first;
276 lp->time = lockPair.second;
277 // Also store the hash of the block with the highest height of
278 // all the blocks which have sequence locked prevouts.
279 // This hash needs to still be on the chain
280 // for these LockPoint calculations to be valid
281 // Note: It is impossible to correctly calculate a maxInputBlock
282 // if any of the sequence locked inputs depend on unconfirmed txs,
283 // except in the special case where the relative lock time/height
284 // is 0, which is equivalent to no sequence lock. Since we assume
285 // input height of tip+1 for mempool txs and test the resulting
286 // lockPair from CalculateSequenceLocks against tip+1. We know
287 // EvaluateSequenceLocks will fail if there was a non-zero sequence
288 // lock on a mempool input, so we can use the return value of
289 // CheckSequenceLocks to indicate the LockPoints validity
290 int maxInputHeight = 0;
291 for (const int height : prevheights) {
292 // Can ignore mempool inputs since we'll fail if they had non-zero locks
293 if (height != tip->nHeight+1) {
294 maxInputHeight = std::max(maxInputHeight, height);
295 }
296 }
297 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
298 }
299 }
300 return EvaluateSequenceLocks(index, lockPair);
301 }
302
303 // Returns the script flags which should be checked for a given block
304 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
305
LimitMempoolSize(CTxMemPool & pool,CCoinsViewCache & coins_cache,size_t limit,std::chrono::seconds age)306 static void LimitMempoolSize(CTxMemPool& pool, CCoinsViewCache& coins_cache, size_t limit, std::chrono::seconds age)
307 EXCLUSIVE_LOCKS_REQUIRED(pool.cs, ::cs_main)
308 {
309 int expired = pool.Expire(GetTime<std::chrono::seconds>() - age);
310 if (expired != 0) {
311 LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
312 }
313
314 std::vector<COutPoint> vNoSpendsRemaining;
315 pool.TrimToSize(limit, &vNoSpendsRemaining);
316 for (const COutPoint& removed : vNoSpendsRemaining)
317 coins_cache.Uncache(removed);
318 }
319
IsCurrentForFeeEstimation(CChainState & active_chainstate)320 static bool IsCurrentForFeeEstimation(CChainState& active_chainstate) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
321 {
322 AssertLockHeld(cs_main);
323 if (active_chainstate.IsInitialBlockDownload())
324 return false;
325 if (active_chainstate.m_chain.Tip()->GetBlockTime() < count_seconds(GetTime<std::chrono::seconds>() - MAX_FEE_ESTIMATION_TIP_AGE))
326 return false;
327 if (active_chainstate.m_chain.Height() < pindexBestHeader->nHeight - 1)
328 return false;
329 return true;
330 }
331
MaybeUpdateMempoolForReorg(DisconnectedBlockTransactions & disconnectpool,bool fAddToMempool)332 void CChainState::MaybeUpdateMempoolForReorg(
333 DisconnectedBlockTransactions& disconnectpool,
334 bool fAddToMempool)
335 {
336 if (!m_mempool) return;
337
338 AssertLockHeld(cs_main);
339 AssertLockHeld(m_mempool->cs);
340 std::vector<uint256> vHashUpdate;
341 // disconnectpool's insertion_order index sorts the entries from
342 // oldest to newest, but the oldest entry will be the last tx from the
343 // latest mined block that was disconnected.
344 // Iterate disconnectpool in reverse, so that we add transactions
345 // back to the mempool starting with the earliest transaction that had
346 // been previously seen in a block.
347 auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
348 while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
349 // ignore validation errors in resurrected transactions
350 if (!fAddToMempool || (*it)->IsCoinBase() ||
351 AcceptToMemoryPool(
352 *this, *m_mempool, *it, true /* bypass_limits */).m_result_type !=
353 MempoolAcceptResult::ResultType::VALID) {
354 // If the transaction doesn't make it in to the mempool, remove any
355 // transactions that depend on it (which would now be orphans).
356 m_mempool->removeRecursive(**it, MemPoolRemovalReason::REORG);
357 } else if (m_mempool->exists((*it)->GetHash())) {
358 vHashUpdate.push_back((*it)->GetHash());
359 }
360 ++it;
361 }
362 disconnectpool.queuedTx.clear();
363 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
364 // no in-mempool children, which is generally not true when adding
365 // previously-confirmed transactions back to the mempool.
366 // UpdateTransactionsFromBlock finds descendants of any transactions in
367 // the disconnectpool that were added back and cleans up the mempool state.
368 m_mempool->UpdateTransactionsFromBlock(vHashUpdate);
369
370 // We also need to remove any now-immature transactions
371 m_mempool->removeForReorg(*this, STANDARD_LOCKTIME_VERIFY_FLAGS);
372 // Re-limit mempool size, in case we added any transactions
373 LimitMempoolSize(
374 *m_mempool,
375 this->CoinsTip(),
376 gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000,
377 std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
378 }
379
380 /**
381 * Checks to avoid mempool polluting consensus critical paths since cached
382 * signature and script validity results will be reused if we validate this
383 * transaction again during block validation.
384 * */
CheckInputsFromMempoolAndCache(const CTransaction & tx,TxValidationState & state,const CCoinsViewCache & view,const CTxMemPool & pool,unsigned int flags,PrecomputedTransactionData & txdata,CCoinsViewCache & coins_tip)385 static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, TxValidationState& state,
386 const CCoinsViewCache& view, const CTxMemPool& pool,
387 unsigned int flags, PrecomputedTransactionData& txdata, CCoinsViewCache& coins_tip)
388 EXCLUSIVE_LOCKS_REQUIRED(cs_main, pool.cs)
389 {
390 AssertLockHeld(cs_main);
391 AssertLockHeld(pool.cs);
392
393 assert(!tx.IsCoinBase());
394 for (const CTxIn& txin : tx.vin) {
395 const Coin& coin = view.AccessCoin(txin.prevout);
396
397 // This coin was checked in PreChecks and MemPoolAccept
398 // has been holding cs_main since then.
399 Assume(!coin.IsSpent());
400 if (coin.IsSpent()) return false;
401
402 // If the Coin is available, there are 2 possibilities:
403 // it is available in our current ChainstateActive UTXO set,
404 // or it's a UTXO provided by a transaction in our mempool.
405 // Ensure the scriptPubKeys in Coins from CoinsView are correct.
406 const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
407 if (txFrom) {
408 assert(txFrom->GetHash() == txin.prevout.hash);
409 assert(txFrom->vout.size() > txin.prevout.n);
410 assert(txFrom->vout[txin.prevout.n] == coin.out);
411 } else {
412 const Coin& coinFromUTXOSet = coins_tip.AccessCoin(txin.prevout);
413 assert(!coinFromUTXOSet.IsSpent());
414 assert(coinFromUTXOSet.out == coin.out);
415 }
416 }
417
418 // Call CheckInputScripts() to cache signature and script validity against current tip consensus rules.
419 return CheckInputScripts(tx, state, view, flags, /* cacheSigStore = */ true, /* cacheFullSciptStore = */ true, txdata);
420 }
421
422 namespace {
423
424 class MemPoolAccept
425 {
426 public:
MemPoolAccept(CTxMemPool & mempool,CChainState & active_chainstate)427 explicit MemPoolAccept(CTxMemPool& mempool, CChainState& active_chainstate) : m_pool(mempool), m_view(&m_dummy), m_viewmempool(&active_chainstate.CoinsTip(), m_pool), m_active_chainstate(active_chainstate),
428 m_limit_ancestors(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT)),
429 m_limit_ancestor_size(gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000),
430 m_limit_descendants(gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT)),
431 m_limit_descendant_size(gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000) {
432 }
433
434 // We put the arguments we're handed into a struct, so we can pass them
435 // around easier.
436 struct ATMPArgs {
437 const CChainParams& m_chainparams;
438 const int64_t m_accept_time;
439 const bool m_bypass_limits;
440 /*
441 * Return any outpoints which were not previously present in the coins
442 * cache, but were added as a result of validating the tx for mempool
443 * acceptance. This allows the caller to optionally remove the cache
444 * additions if the associated transaction ends up being rejected by
445 * the mempool.
446 */
447 std::vector<COutPoint>& m_coins_to_uncache;
448 const bool m_test_accept;
449 /** Whether we allow transactions to replace mempool transactions by BIP125 rules. If false,
450 * any transaction spending the same inputs as a transaction in the mempool is considered
451 * a conflict. */
452 const bool m_allow_bip125_replacement{true};
453 };
454
455 // Single transaction acceptance
456 MempoolAcceptResult AcceptSingleTransaction(const CTransactionRef& ptx, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
457
458 /**
459 * Multiple transaction acceptance. Transactions may or may not be interdependent,
460 * but must not conflict with each other. Parents must come before children if any
461 * dependencies exist.
462 */
463 PackageMempoolAcceptResult AcceptMultipleTransactions(const std::vector<CTransactionRef>& txns, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
464
465 private:
466 // All the intermediate state that gets passed between the various levels
467 // of checking a given transaction.
468 struct Workspace {
Workspace__anon0589d26d0211::MemPoolAccept::Workspace469 explicit Workspace(const CTransactionRef& ptx) : m_ptx(ptx), m_hash(ptx->GetHash()) {}
470 std::set<uint256> m_conflicts;
471 CTxMemPool::setEntries m_all_conflicting;
472 CTxMemPool::setEntries m_ancestors;
473 std::unique_ptr<CTxMemPoolEntry> m_entry;
474 std::list<CTransactionRef> m_replaced_transactions;
475
476 bool m_replacement_transaction;
477 CAmount m_base_fees;
478 CAmount m_modified_fees;
479 CAmount m_conflicting_fees;
480 size_t m_conflicting_size;
481
482 const CTransactionRef& m_ptx;
483 const uint256& m_hash;
484 TxValidationState m_state;
485 };
486
487 // Run the policy checks on a given transaction, excluding any script checks.
488 // Looks up inputs, calculates feerate, considers replacement, evaluates
489 // package limits, etc. As this function can be invoked for "free" by a peer,
490 // only tests that are fast should be done here (to avoid CPU DoS).
491 bool PreChecks(ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
492
493 // Run the script checks using our policy flags. As this can be slow, we should
494 // only invoke this on transactions that have otherwise passed policy checks.
495 bool PolicyScriptChecks(const ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
496
497 // Re-run the script checks, using consensus flags, and try to cache the
498 // result in the scriptcache. This should be done after
499 // PolicyScriptChecks(). This requires that all inputs either be in our
500 // utxo set or in the mempool.
501 bool ConsensusScriptChecks(const ATMPArgs& args, Workspace& ws, PrecomputedTransactionData &txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
502
503 // Try to add the transaction to the mempool, removing any conflicts first.
504 // Returns true if the transaction is in the mempool after any size
505 // limiting is performed, false otherwise.
506 bool Finalize(const ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
507
508 // Compare a package's feerate against minimum allowed.
CheckFeeRate(size_t package_size,CAmount package_fee,TxValidationState & state)509 bool CheckFeeRate(size_t package_size, CAmount package_fee, TxValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs)
510 {
511 CAmount mempoolRejectFee = m_pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(package_size);
512 if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) {
513 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool min fee not met", strprintf("%d < %d", package_fee, mempoolRejectFee));
514 }
515
516 if (package_fee < ::minRelayTxFee.GetFee(package_size)) {
517 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "min relay fee not met", strprintf("%d < %d", package_fee, ::minRelayTxFee.GetFee(package_size)));
518 }
519 return true;
520 }
521
522 private:
523 CTxMemPool& m_pool;
524 CCoinsViewCache m_view;
525 CCoinsViewMemPool m_viewmempool;
526 CCoinsView m_dummy;
527
528 CChainState& m_active_chainstate;
529
530 // The package limits in effect at the time of invocation.
531 const size_t m_limit_ancestors;
532 const size_t m_limit_ancestor_size;
533 // These may be modified while evaluating a transaction (eg to account for
534 // in-mempool conflicts; see below).
535 size_t m_limit_descendants;
536 size_t m_limit_descendant_size;
537 };
538
PreChecks(ATMPArgs & args,Workspace & ws)539 bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
540 {
541 const CTransactionRef& ptx = ws.m_ptx;
542 const CTransaction& tx = *ws.m_ptx;
543 const uint256& hash = ws.m_hash;
544
545 // Copy/alias what we need out of args
546 const int64_t nAcceptTime = args.m_accept_time;
547 const bool bypass_limits = args.m_bypass_limits;
548 std::vector<COutPoint>& coins_to_uncache = args.m_coins_to_uncache;
549
550 // Alias what we need out of ws
551 TxValidationState& state = ws.m_state;
552 std::set<uint256>& setConflicts = ws.m_conflicts;
553 CTxMemPool::setEntries& allConflicting = ws.m_all_conflicting;
554 CTxMemPool::setEntries& setAncestors = ws.m_ancestors;
555 std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
556 bool& fReplacementTransaction = ws.m_replacement_transaction;
557 CAmount& nModifiedFees = ws.m_modified_fees;
558 CAmount& nConflictingFees = ws.m_conflicting_fees;
559 size_t& nConflictingSize = ws.m_conflicting_size;
560
561 if (!CheckTransaction(tx, state)) {
562 return false; // state filled in by CheckTransaction
563 }
564
565 // Coinbase is only valid in a block, not as a loose transaction
566 if (tx.IsCoinBase())
567 return state.Invalid(TxValidationResult::TX_CONSENSUS, "coinbase");
568
569 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
570 std::string reason;
571 if (fRequireStandard && !IsStandardTx(tx, reason))
572 return state.Invalid(TxValidationResult::TX_NOT_STANDARD, reason);
573
574 // Do not work on transactions that are too small.
575 // A transaction with 1 segwit input and 1 P2WPHK output has non-witness size of 82 bytes.
576 // Transactions smaller than this are not relayed to mitigate CVE-2017-12842 by not relaying
577 // 64-byte transactions.
578 if (::GetSerializeSize(tx, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) < MIN_STANDARD_TX_NONWITNESS_SIZE)
579 return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "tx-size-small");
580
581 // Only accept nLockTime-using transactions that can be mined in the next
582 // block; we don't want our mempool filled up with transactions that can't
583 // be mined yet.
584 if (!CheckFinalTx(m_active_chainstate.m_chain.Tip(), tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
585 return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-final");
586
587 if (m_pool.exists(GenTxid(true, tx.GetWitnessHash()))) {
588 // Exact transaction already exists in the mempool.
589 return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-in-mempool");
590 } else if (m_pool.exists(GenTxid(false, tx.GetHash()))) {
591 // Transaction with the same non-witness data but different witness (same txid, different
592 // wtxid) already exists in the mempool.
593 return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-same-nonwitness-data-in-mempool");
594 }
595
596 // Check for conflicts with in-memory transactions
597 for (const CTxIn &txin : tx.vin)
598 {
599 const CTransaction* ptxConflicting = m_pool.GetConflictTx(txin.prevout);
600 if (ptxConflicting) {
601 if (!args.m_allow_bip125_replacement) {
602 // Transaction conflicts with a mempool tx, but we're not allowing replacements.
603 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "bip125-replacement-disallowed");
604 }
605 if (!setConflicts.count(ptxConflicting->GetHash()))
606 {
607 // Allow opt-out of transaction replacement by setting
608 // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
609 //
610 // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
611 // non-replaceable transactions. All inputs rather than just one
612 // is for the sake of multi-party protocols, where we don't
613 // want a single party to be able to disable replacement.
614 //
615 // Transactions that don't explicitly signal replaceability are
616 // *not* replaceable with the current logic, even if one of their
617 // unconfirmed ancestors signals replaceability. This diverges
618 // from BIP125's inherited signaling description (see CVE-2021-31876).
619 // Applications relying on first-seen mempool behavior should
620 // check all unconfirmed ancestors; otherwise an opt-in ancestor
621 // might be replaced, causing removal of this descendant.
622 bool fReplacementOptOut = true;
623 for (const CTxIn &_txin : ptxConflicting->vin)
624 {
625 if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
626 {
627 fReplacementOptOut = false;
628 break;
629 }
630 }
631 if (fReplacementOptOut) {
632 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "txn-mempool-conflict");
633 }
634
635 setConflicts.insert(ptxConflicting->GetHash());
636 }
637 }
638 }
639
640 LockPoints lp;
641 m_view.SetBackend(m_viewmempool);
642
643 const CCoinsViewCache& coins_cache = m_active_chainstate.CoinsTip();
644 // do all inputs exist?
645 for (const CTxIn& txin : tx.vin) {
646 if (!coins_cache.HaveCoinInCache(txin.prevout)) {
647 coins_to_uncache.push_back(txin.prevout);
648 }
649
650 // Note: this call may add txin.prevout to the coins cache
651 // (coins_cache.cacheCoins) by way of FetchCoin(). It should be removed
652 // later (via coins_to_uncache) if this tx turns out to be invalid.
653 if (!m_view.HaveCoin(txin.prevout)) {
654 // Are inputs missing because we already have the tx?
655 for (size_t out = 0; out < tx.vout.size(); out++) {
656 // Optimistically just do efficient check of cache for outputs
657 if (coins_cache.HaveCoinInCache(COutPoint(hash, out))) {
658 return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-known");
659 }
660 }
661 // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
662 return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent");
663 }
664 }
665
666 // This is const, but calls into the back end CoinsViews. The CCoinsViewDB at the bottom of the
667 // hierarchy brings the best block into scope. See CCoinsViewDB::GetBestBlock().
668 m_view.GetBestBlock();
669
670 // we have all inputs cached now, so switch back to dummy (to protect
671 // against bugs where we pull more inputs from disk that miss being added
672 // to coins_to_uncache)
673 m_view.SetBackend(m_dummy);
674
675 // Only accept BIP68 sequence locked transactions that can be mined in the next
676 // block; we don't want our mempool filled up with transactions that can't
677 // be mined yet.
678 // Pass in m_view which has all of the relevant inputs cached. Note that, since m_view's
679 // backend was removed, it no longer pulls coins from the mempool.
680 if (!CheckSequenceLocks(m_active_chainstate.m_chain.Tip(), m_view, tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
681 return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-BIP68-final");
682
683 if (!Consensus::CheckTxInputs(tx, state, m_view, m_active_chainstate.m_blockman.GetSpendHeight(m_view), ws.m_base_fees)) {
684 return false; // state filled in by CheckTxInputs
685 }
686
687 // Check for non-standard pay-to-script-hash in inputs
688 const bool taproot_active = DeploymentActiveAfter(m_active_chainstate.m_chain.Tip(), args.m_chainparams.GetConsensus(), Consensus::DEPLOYMENT_TAPROOT);
689 if (fRequireStandard && !AreInputsStandard(tx, m_view, taproot_active)) {
690 return state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs");
691 }
692
693 // Check for non-standard witnesses.
694 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, m_view))
695 return state.Invalid(TxValidationResult::TX_WITNESS_MUTATED, "bad-witness-nonstandard");
696
697 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, m_view, STANDARD_SCRIPT_VERIFY_FLAGS);
698
699 // nModifiedFees includes any fee deltas from PrioritiseTransaction
700 nModifiedFees = ws.m_base_fees;
701 m_pool.ApplyDelta(hash, nModifiedFees);
702
703 // Keep track of transactions that spend a coinbase, which we re-scan
704 // during reorgs to ensure COINBASE_MATURITY is still met.
705 bool fSpendsCoinbase = false;
706 for (const CTxIn &txin : tx.vin) {
707 const Coin &coin = m_view.AccessCoin(txin.prevout);
708 if (coin.IsCoinBase()) {
709 fSpendsCoinbase = true;
710 break;
711 }
712 }
713
714 entry.reset(new CTxMemPoolEntry(ptx, ws.m_base_fees, nAcceptTime, m_active_chainstate.m_chain.Height(),
715 fSpendsCoinbase, nSigOpsCost, lp));
716 unsigned int nSize = entry->GetTxSize();
717
718 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
719 return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "bad-txns-too-many-sigops",
720 strprintf("%d", nSigOpsCost));
721
722 // No transactions are allowed below minRelayTxFee except from disconnected
723 // blocks
724 if (!bypass_limits && !CheckFeeRate(nSize, nModifiedFees, state)) return false;
725
726 const CTxMemPool::setEntries setIterConflicting = m_pool.GetIterSet(setConflicts);
727 // Calculate in-mempool ancestors, up to a limit.
728 if (setConflicts.size() == 1) {
729 // In general, when we receive an RBF transaction with mempool conflicts, we want to know whether we
730 // would meet the chain limits after the conflicts have been removed. However, there isn't a practical
731 // way to do this short of calculating the ancestor and descendant sets with an overlay cache of
732 // changed mempool entries. Due to both implementation and runtime complexity concerns, this isn't
733 // very realistic, thus we only ensure a limited set of transactions are RBF'able despite mempool
734 // conflicts here. Importantly, we need to ensure that some transactions which were accepted using
735 // the below carve-out are able to be RBF'ed, without impacting the security the carve-out provides
736 // for off-chain contract systems (see link in the comment below).
737 //
738 // Specifically, the subset of RBF transactions which we allow despite chain limits are those which
739 // conflict directly with exactly one other transaction (but may evict children of said transaction),
740 // and which are not adding any new mempool dependencies. Note that the "no new mempool dependencies"
741 // check is accomplished later, so we don't bother doing anything about it here, but if BIP 125 is
742 // amended, we may need to move that check to here instead of removing it wholesale.
743 //
744 // Such transactions are clearly not merging any existing packages, so we are only concerned with
745 // ensuring that (a) no package is growing past the package size (not count) limits and (b) we are
746 // not allowing something to effectively use the (below) carve-out spot when it shouldn't be allowed
747 // to.
748 //
749 // To check these we first check if we meet the RBF criteria, above, and increment the descendant
750 // limits by the direct conflict and its descendants (as these are recalculated in
751 // CalculateMempoolAncestors by assuming the new transaction being added is a new descendant, with no
752 // removals, of each parent's existing dependent set). The ancestor count limits are unmodified (as
753 // the ancestor limits should be the same for both our new transaction and any conflicts).
754 // We don't bother incrementing m_limit_descendants by the full removal count as that limit never comes
755 // into force here (as we're only adding a single transaction).
756 assert(setIterConflicting.size() == 1);
757 CTxMemPool::txiter conflict = *setIterConflicting.begin();
758
759 m_limit_descendants += 1;
760 m_limit_descendant_size += conflict->GetSizeWithDescendants();
761 }
762
763 std::string errString;
764 if (!m_pool.CalculateMemPoolAncestors(*entry, setAncestors, m_limit_ancestors, m_limit_ancestor_size, m_limit_descendants, m_limit_descendant_size, errString)) {
765 setAncestors.clear();
766 // If CalculateMemPoolAncestors fails second time, we want the original error string.
767 std::string dummy_err_string;
768 // Contracting/payment channels CPFP carve-out:
769 // If the new transaction is relatively small (up to 40k weight)
770 // and has at most one ancestor (ie ancestor limit of 2, including
771 // the new transaction), allow it if its parent has exactly the
772 // descendant limit descendants.
773 //
774 // This allows protocols which rely on distrusting counterparties
775 // being able to broadcast descendants of an unconfirmed transaction
776 // to be secure by simply only having two immediately-spendable
777 // outputs - one for each counterparty. For more info on the uses for
778 // this, see https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html
779 if (nSize > EXTRA_DESCENDANT_TX_SIZE_LIMIT ||
780 !m_pool.CalculateMemPoolAncestors(*entry, setAncestors, 2, m_limit_ancestor_size, m_limit_descendants + 1, m_limit_descendant_size + EXTRA_DESCENDANT_TX_SIZE_LIMIT, dummy_err_string)) {
781 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too-long-mempool-chain", errString);
782 }
783 }
784
785 // A transaction that spends outputs that would be replaced by it is invalid. Now
786 // that we have the set of all ancestors we can detect this
787 // pathological case by making sure setConflicts and setAncestors don't
788 // intersect.
789 for (CTxMemPool::txiter ancestorIt : setAncestors)
790 {
791 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
792 if (setConflicts.count(hashAncestor))
793 {
794 return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-spends-conflicting-tx",
795 strprintf("%s spends conflicting transaction %s",
796 hash.ToString(),
797 hashAncestor.ToString()));
798 }
799 }
800
801 // Check if it's economically rational to mine this transaction rather
802 // than the ones it replaces.
803 nConflictingFees = 0;
804 nConflictingSize = 0;
805 uint64_t nConflictingCount = 0;
806
807 // If we don't hold the lock allConflicting might be incomplete; the
808 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
809 // mempool consistency for us.
810 fReplacementTransaction = setConflicts.size();
811 if (fReplacementTransaction)
812 {
813 CFeeRate newFeeRate(nModifiedFees, nSize);
814 std::set<uint256> setConflictsParents;
815 const int maxDescendantsToVisit = 100;
816 for (const auto& mi : setIterConflicting) {
817 // Don't allow the replacement to reduce the feerate of the
818 // mempool.
819 //
820 // We usually don't want to accept replacements with lower
821 // feerates than what they replaced as that would lower the
822 // feerate of the next block. Requiring that the feerate always
823 // be increased is also an easy-to-reason about way to prevent
824 // DoS attacks via replacements.
825 //
826 // We only consider the feerates of transactions being directly
827 // replaced, not their indirect descendants. While that does
828 // mean high feerate children are ignored when deciding whether
829 // or not to replace, we do require the replacement to pay more
830 // overall fees too, mitigating most cases.
831 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
832 if (newFeeRate <= oldFeeRate)
833 {
834 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee",
835 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
836 hash.ToString(),
837 newFeeRate.ToString(),
838 oldFeeRate.ToString()));
839 }
840
841 for (const CTxIn &txin : mi->GetTx().vin)
842 {
843 setConflictsParents.insert(txin.prevout.hash);
844 }
845
846 nConflictingCount += mi->GetCountWithDescendants();
847 }
848 // This potentially overestimates the number of actual descendants
849 // but we just want to be conservative to avoid doing too much
850 // work.
851 if (nConflictingCount <= maxDescendantsToVisit) {
852 // If not too many to replace, then calculate the set of
853 // transactions that would have to be evicted
854 for (CTxMemPool::txiter it : setIterConflicting) {
855 m_pool.CalculateDescendants(it, allConflicting);
856 }
857 for (CTxMemPool::txiter it : allConflicting) {
858 nConflictingFees += it->GetModifiedFee();
859 nConflictingSize += it->GetTxSize();
860 }
861 } else {
862 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too many potential replacements",
863 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
864 hash.ToString(),
865 nConflictingCount,
866 maxDescendantsToVisit));
867 }
868
869 for (unsigned int j = 0; j < tx.vin.size(); j++)
870 {
871 // We don't want to accept replacements that require low
872 // feerate junk to be mined first. Ideally we'd keep track of
873 // the ancestor feerates and make the decision based on that,
874 // but for now requiring all new inputs to be confirmed works.
875 //
876 // Note that if you relax this to make RBF a little more useful,
877 // this may break the CalculateMempoolAncestors RBF relaxation,
878 // above. See the comment above the first CalculateMempoolAncestors
879 // call for more info.
880 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
881 {
882 // Rather than check the UTXO set - potentially expensive -
883 // it's cheaper to just check if the new input refers to a
884 // tx that's in the mempool.
885 if (m_pool.exists(tx.vin[j].prevout.hash)) {
886 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "replacement-adds-unconfirmed",
887 strprintf("replacement %s adds unconfirmed input, idx %d",
888 hash.ToString(), j));
889 }
890 }
891 }
892
893 // The replacement must pay greater fees than the transactions it
894 // replaces - if we did the bandwidth used by those conflicting
895 // transactions would not be paid for.
896 if (nModifiedFees < nConflictingFees)
897 {
898 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee",
899 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
900 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
901 }
902
903 // Finally in addition to paying more fees than the conflicts the
904 // new transaction must pay for its own bandwidth.
905 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
906 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
907 {
908 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee",
909 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
910 hash.ToString(),
911 FormatMoney(nDeltaFees),
912 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
913 }
914 }
915 return true;
916 }
917
PolicyScriptChecks(const ATMPArgs & args,Workspace & ws,PrecomputedTransactionData & txdata)918 bool MemPoolAccept::PolicyScriptChecks(const ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata)
919 {
920 const CTransaction& tx = *ws.m_ptx;
921 TxValidationState& state = ws.m_state;
922
923 constexpr unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
924
925 // Check input scripts and signatures.
926 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
927 if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, false, txdata)) {
928 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
929 // need to turn both off, and compare against just turning off CLEANSTACK
930 // to see if the failure is specifically due to witness validation.
931 TxValidationState state_dummy; // Want reported failures to be from first CheckInputScripts
932 if (!tx.HasWitness() && CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
933 !CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
934 // Only the witness is missing, so the transaction itself may be fine.
935 state.Invalid(TxValidationResult::TX_WITNESS_STRIPPED,
936 state.GetRejectReason(), state.GetDebugMessage());
937 }
938 return false; // state filled in by CheckInputScripts
939 }
940
941 return true;
942 }
943
ConsensusScriptChecks(const ATMPArgs & args,Workspace & ws,PrecomputedTransactionData & txdata)944 bool MemPoolAccept::ConsensusScriptChecks(const ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata)
945 {
946 const CTransaction& tx = *ws.m_ptx;
947 const uint256& hash = ws.m_hash;
948 TxValidationState& state = ws.m_state;
949 const CChainParams& chainparams = args.m_chainparams;
950
951 // Check again against the current block tip's script verification
952 // flags to cache our script execution flags. This is, of course,
953 // useless if the next block has different script flags from the
954 // previous one, but because the cache tracks script flags for us it
955 // will auto-invalidate and we'll just have a few blocks of extra
956 // misses on soft-fork activation.
957 //
958 // This is also useful in case of bugs in the standard flags that cause
959 // transactions to pass as valid when they're actually invalid. For
960 // instance the STRICTENC flag was incorrectly allowing certain
961 // CHECKSIG NOT scripts to pass, even though they were invalid.
962 //
963 // There is a similar check in CreateNewBlock() to prevent creating
964 // invalid blocks (using TestBlockValidity), however allowing such
965 // transactions into the mempool can be exploited as a DoS attack.
966 unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(m_active_chainstate.m_chain.Tip(), chainparams.GetConsensus());
967 if (!CheckInputsFromMempoolAndCache(tx, state, m_view, m_pool, currentBlockScriptVerifyFlags, txdata, m_active_chainstate.CoinsTip())) {
968 return error("%s: BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not STANDARD flags %s, %s",
969 __func__, hash.ToString(), state.ToString());
970 }
971
972 return true;
973 }
974
Finalize(const ATMPArgs & args,Workspace & ws)975 bool MemPoolAccept::Finalize(const ATMPArgs& args, Workspace& ws)
976 {
977 const CTransaction& tx = *ws.m_ptx;
978 const uint256& hash = ws.m_hash;
979 TxValidationState& state = ws.m_state;
980 const bool bypass_limits = args.m_bypass_limits;
981
982 CTxMemPool::setEntries& allConflicting = ws.m_all_conflicting;
983 CTxMemPool::setEntries& setAncestors = ws.m_ancestors;
984 const CAmount& nModifiedFees = ws.m_modified_fees;
985 const CAmount& nConflictingFees = ws.m_conflicting_fees;
986 const size_t& nConflictingSize = ws.m_conflicting_size;
987 const bool fReplacementTransaction = ws.m_replacement_transaction;
988 std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
989
990 // Remove conflicting transactions from the mempool
991 for (CTxMemPool::txiter it : allConflicting)
992 {
993 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s additional fees, %d delta bytes\n",
994 it->GetTx().GetHash().ToString(),
995 hash.ToString(),
996 FormatMoney(nModifiedFees - nConflictingFees),
997 (int)entry->GetTxSize() - (int)nConflictingSize);
998 ws.m_replaced_transactions.push_back(it->GetSharedTx());
999 }
1000 m_pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
1001
1002 // This transaction should only count for fee estimation if:
1003 // - it isn't a BIP 125 replacement transaction (may not be widely supported)
1004 // - it's not being re-added during a reorg which bypasses typical mempool fee limits
1005 // - the node is not behind
1006 // - the transaction is not dependent on any other transactions in the mempool
1007 bool validForFeeEstimation = !fReplacementTransaction && !bypass_limits && IsCurrentForFeeEstimation(m_active_chainstate) && m_pool.HasNoInputsOf(tx);
1008
1009 // Store transaction in memory
1010 m_pool.addUnchecked(*entry, setAncestors, validForFeeEstimation);
1011
1012 // trim mempool and check if tx was trimmed
1013 if (!bypass_limits) {
1014 LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip(), gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
1015 if (!m_pool.exists(hash))
1016 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
1017 }
1018 return true;
1019 }
1020
AcceptSingleTransaction(const CTransactionRef & ptx,ATMPArgs & args)1021 MempoolAcceptResult MemPoolAccept::AcceptSingleTransaction(const CTransactionRef& ptx, ATMPArgs& args)
1022 {
1023 AssertLockHeld(cs_main);
1024 LOCK(m_pool.cs); // mempool "read lock" (held through GetMainSignals().TransactionAddedToMempool())
1025
1026 Workspace ws(ptx);
1027
1028 if (!PreChecks(args, ws)) return MempoolAcceptResult::Failure(ws.m_state);
1029
1030 // Only compute the precomputed transaction data if we need to verify
1031 // scripts (ie, other policy checks pass). We perform the inexpensive
1032 // checks first and avoid hashing and signature verification unless those
1033 // checks pass, to mitigate CPU exhaustion denial-of-service attacks.
1034 PrecomputedTransactionData txdata;
1035
1036 if (!PolicyScriptChecks(args, ws, txdata)) return MempoolAcceptResult::Failure(ws.m_state);
1037
1038 if (!ConsensusScriptChecks(args, ws, txdata)) return MempoolAcceptResult::Failure(ws.m_state);
1039
1040 // Tx was accepted, but not added
1041 if (args.m_test_accept) {
1042 return MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions), ws.m_base_fees);
1043 }
1044
1045 if (!Finalize(args, ws)) return MempoolAcceptResult::Failure(ws.m_state);
1046
1047 GetMainSignals().TransactionAddedToMempool(ptx, m_pool.GetAndIncrementSequence());
1048
1049 return MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions), ws.m_base_fees);
1050 }
1051
AcceptMultipleTransactions(const std::vector<CTransactionRef> & txns,ATMPArgs & args)1052 PackageMempoolAcceptResult MemPoolAccept::AcceptMultipleTransactions(const std::vector<CTransactionRef>& txns, ATMPArgs& args)
1053 {
1054 AssertLockHeld(cs_main);
1055
1056 // These context-free package limits can be done before taking the mempool lock.
1057 PackageValidationState package_state;
1058 if (!CheckPackage(txns, package_state)) return PackageMempoolAcceptResult(package_state, {});
1059
1060 std::vector<Workspace> workspaces{};
1061 workspaces.reserve(txns.size());
1062 std::transform(txns.cbegin(), txns.cend(), std::back_inserter(workspaces),
1063 [](const auto& tx) { return Workspace(tx); });
1064 std::map<const uint256, const MempoolAcceptResult> results;
1065
1066 LOCK(m_pool.cs);
1067
1068 // Do all PreChecks first and fail fast to avoid running expensive script checks when unnecessary.
1069 for (Workspace& ws : workspaces) {
1070 if (!PreChecks(args, ws)) {
1071 package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1072 // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
1073 results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1074 return PackageMempoolAcceptResult(package_state, std::move(results));
1075 }
1076 // Make the coins created by this transaction available for subsequent transactions in the
1077 // package to spend. Since we already checked conflicts in the package and we don't allow
1078 // replacements, we don't need to track the coins spent. Note that this logic will need to be
1079 // updated if package replace-by-fee is allowed in the future.
1080 assert(!args.m_allow_bip125_replacement);
1081 m_viewmempool.PackageAddTransaction(ws.m_ptx);
1082 }
1083
1084 for (Workspace& ws : workspaces) {
1085 PrecomputedTransactionData txdata;
1086 if (!PolicyScriptChecks(args, ws, txdata)) {
1087 // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
1088 package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1089 results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1090 return PackageMempoolAcceptResult(package_state, std::move(results));
1091 }
1092 if (args.m_test_accept) {
1093 // When test_accept=true, transactions that pass PolicyScriptChecks are valid because there are
1094 // no further mempool checks (passing PolicyScriptChecks implies passing ConsensusScriptChecks).
1095 results.emplace(ws.m_ptx->GetWitnessHash(),
1096 MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions), ws.m_base_fees));
1097 }
1098 }
1099
1100 return PackageMempoolAcceptResult(package_state, std::move(results));
1101 }
1102
1103 } // anon namespace
1104
1105 /** (try to) add transaction to memory pool with a specified acceptance time **/
AcceptToMemoryPoolWithTime(const CChainParams & chainparams,CTxMemPool & pool,CChainState & active_chainstate,const CTransactionRef & tx,int64_t nAcceptTime,bool bypass_limits,bool test_accept)1106 static MempoolAcceptResult AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool,
1107 CChainState& active_chainstate,
1108 const CTransactionRef &tx, int64_t nAcceptTime,
1109 bool bypass_limits, bool test_accept)
1110 EXCLUSIVE_LOCKS_REQUIRED(cs_main)
1111 {
1112 std::vector<COutPoint> coins_to_uncache;
1113 MemPoolAccept::ATMPArgs args { chainparams, nAcceptTime, bypass_limits, coins_to_uncache,
1114 test_accept, /* m_allow_bip125_replacement */ true };
1115
1116 const MempoolAcceptResult result = MemPoolAccept(pool, active_chainstate).AcceptSingleTransaction(tx, args);
1117 if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {
1118 // Remove coins that were not present in the coins cache before calling
1119 // AcceptSingleTransaction(); this is to prevent memory DoS in case we receive a large
1120 // number of invalid transactions that attempt to overrun the in-memory coins cache
1121 // (`CCoinsViewCache::cacheCoins`).
1122
1123 for (const COutPoint& hashTx : coins_to_uncache)
1124 active_chainstate.CoinsTip().Uncache(hashTx);
1125 }
1126 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
1127 BlockValidationState state_dummy;
1128 active_chainstate.FlushStateToDisk(state_dummy, FlushStateMode::PERIODIC);
1129 return result;
1130 }
1131
AcceptToMemoryPool(CChainState & active_chainstate,CTxMemPool & pool,const CTransactionRef & tx,bool bypass_limits,bool test_accept)1132 MempoolAcceptResult AcceptToMemoryPool(CChainState& active_chainstate, CTxMemPool& pool, const CTransactionRef& tx,
1133 bool bypass_limits, bool test_accept)
1134 {
1135 return AcceptToMemoryPoolWithTime(Params(), pool, active_chainstate, tx, GetTime(), bypass_limits, test_accept);
1136 }
1137
ProcessNewPackage(CChainState & active_chainstate,CTxMemPool & pool,const Package & package,bool test_accept)1138 PackageMempoolAcceptResult ProcessNewPackage(CChainState& active_chainstate, CTxMemPool& pool,
1139 const Package& package, bool test_accept)
1140 {
1141 AssertLockHeld(cs_main);
1142 assert(test_accept); // Only allow package accept dry-runs (testmempoolaccept RPC).
1143 assert(!package.empty());
1144 assert(std::all_of(package.cbegin(), package.cend(), [](const auto& tx){return tx != nullptr;}));
1145
1146 std::vector<COutPoint> coins_to_uncache;
1147 const CChainParams& chainparams = Params();
1148 MemPoolAccept::ATMPArgs args { chainparams, GetTime(), /* bypass_limits */ false, coins_to_uncache,
1149 test_accept, /* m_allow_bip125_replacement */ false };
1150 const PackageMempoolAcceptResult result = MemPoolAccept(pool, active_chainstate).AcceptMultipleTransactions(package, args);
1151
1152 // Uncache coins pertaining to transactions that were not submitted to the mempool.
1153 for (const COutPoint& hashTx : coins_to_uncache) {
1154 active_chainstate.CoinsTip().Uncache(hashTx);
1155 }
1156 return result;
1157 }
1158
GetTransaction(const CBlockIndex * const block_index,const CTxMemPool * const mempool,const uint256 & hash,const Consensus::Params & consensusParams,uint256 & hashBlock)1159 CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const uint256& hash, const Consensus::Params& consensusParams, uint256& hashBlock)
1160 {
1161 LOCK(cs_main);
1162
1163 if (block_index) {
1164 CBlock block;
1165 if (ReadBlockFromDisk(block, block_index, consensusParams)) {
1166 for (const auto& tx : block.vtx) {
1167 if (tx->GetHash() == hash) {
1168 hashBlock = block_index->GetBlockHash();
1169 return tx;
1170 }
1171 }
1172 }
1173 return nullptr;
1174 }
1175 if (mempool) {
1176 CTransactionRef ptx = mempool->get(hash);
1177 if (ptx) return ptx;
1178 }
1179 if (g_txindex) {
1180 CTransactionRef tx;
1181 if (g_txindex->FindTx(hash, hashBlock, tx)) return tx;
1182 }
1183 return nullptr;
1184 }
1185
GetBlockSubsidy(int nHeight,const Consensus::Params & consensusParams)1186 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1187 {
1188 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1189 // Force block reward to zero when right shift is undefined.
1190 if (halvings >= 64)
1191 return 0;
1192
1193 CAmount nSubsidy = 50 * COIN;
1194 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1195 nSubsidy >>= halvings;
1196 return nSubsidy;
1197 }
1198
CoinsViews(std::string ldb_name,size_t cache_size_bytes,bool in_memory,bool should_wipe)1199 CoinsViews::CoinsViews(
1200 std::string ldb_name,
1201 size_t cache_size_bytes,
1202 bool in_memory,
1203 bool should_wipe) : m_dbview(
1204 gArgs.GetDataDirNet() / ldb_name, cache_size_bytes, in_memory, should_wipe),
1205 m_catcherview(&m_dbview) {}
1206
InitCache()1207 void CoinsViews::InitCache()
1208 {
1209 m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
1210 }
1211
CChainState(CTxMemPool * mempool,BlockManager & blockman,std::optional<uint256> from_snapshot_blockhash)1212 CChainState::CChainState(CTxMemPool* mempool, BlockManager& blockman, std::optional<uint256> from_snapshot_blockhash)
1213 : m_mempool(mempool),
1214 m_params(::Params()),
1215 m_blockman(blockman),
1216 m_from_snapshot_blockhash(from_snapshot_blockhash) {}
1217
InitCoinsDB(size_t cache_size_bytes,bool in_memory,bool should_wipe,std::string leveldb_name)1218 void CChainState::InitCoinsDB(
1219 size_t cache_size_bytes,
1220 bool in_memory,
1221 bool should_wipe,
1222 std::string leveldb_name)
1223 {
1224 if (m_from_snapshot_blockhash) {
1225 leveldb_name += "_" + m_from_snapshot_blockhash->ToString();
1226 }
1227
1228 m_coins_views = std::make_unique<CoinsViews>(
1229 leveldb_name, cache_size_bytes, in_memory, should_wipe);
1230 }
1231
InitCoinsCache(size_t cache_size_bytes)1232 void CChainState::InitCoinsCache(size_t cache_size_bytes)
1233 {
1234 assert(m_coins_views != nullptr);
1235 m_coinstip_cache_size_bytes = cache_size_bytes;
1236 m_coins_views->InitCache();
1237 }
1238
1239 // Note that though this is marked const, we may end up modifying `m_cached_finished_ibd`, which
1240 // is a performance-related implementation detail. This function must be marked
1241 // `const` so that `CValidationInterface` clients (which are given a `const CChainState*`)
1242 // can call it.
1243 //
IsInitialBlockDownload() const1244 bool CChainState::IsInitialBlockDownload() const
1245 {
1246 // Optimization: pre-test latch before taking the lock.
1247 if (m_cached_finished_ibd.load(std::memory_order_relaxed))
1248 return false;
1249
1250 LOCK(cs_main);
1251 if (m_cached_finished_ibd.load(std::memory_order_relaxed))
1252 return false;
1253 if (fImporting || fReindex)
1254 return true;
1255 if (m_chain.Tip() == nullptr)
1256 return true;
1257 if (m_chain.Tip()->nChainWork < nMinimumChainWork)
1258 return true;
1259 if (m_chain.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1260 return true;
1261 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1262 m_cached_finished_ibd.store(true, std::memory_order_relaxed);
1263 return false;
1264 }
1265
AlertNotify(const std::string & strMessage)1266 static void AlertNotify(const std::string& strMessage)
1267 {
1268 uiInterface.NotifyAlertChanged();
1269 #if HAVE_SYSTEM
1270 std::string strCmd = gArgs.GetArg("-alertnotify", "");
1271 if (strCmd.empty()) return;
1272
1273 // Alert text should be plain ascii coming from a trusted source, but to
1274 // be safe we first strip anything not in safeChars, then add single quotes around
1275 // the whole string before passing it to the shell:
1276 std::string singleQuote("'");
1277 std::string safeStatus = SanitizeString(strMessage);
1278 safeStatus = singleQuote+safeStatus+singleQuote;
1279 boost::replace_all(strCmd, "%s", safeStatus);
1280
1281 std::thread t(runCommand, strCmd);
1282 t.detach(); // thread runs free
1283 #endif
1284 }
1285
CheckForkWarningConditions()1286 void CChainState::CheckForkWarningConditions()
1287 {
1288 AssertLockHeld(cs_main);
1289
1290 // Before we get past initial download, we cannot reliably alert about forks
1291 // (we assume we don't get stuck on a fork before finishing our initial sync)
1292 if (IsInitialBlockDownload()) {
1293 return;
1294 }
1295
1296 if (pindexBestInvalid && pindexBestInvalid->nChainWork > m_chain.Tip()->nChainWork + (GetBlockProof(*m_chain.Tip()) * 6)) {
1297 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1298 SetfLargeWorkInvalidChainFound(true);
1299 } else {
1300 SetfLargeWorkInvalidChainFound(false);
1301 }
1302 }
1303
1304 // Called both upon regular invalid block discovery *and* InvalidateBlock
InvalidChainFound(CBlockIndex * pindexNew)1305 void CChainState::InvalidChainFound(CBlockIndex* pindexNew)
1306 {
1307 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1308 pindexBestInvalid = pindexNew;
1309 if (pindexBestHeader != nullptr && pindexBestHeader->GetAncestor(pindexNew->nHeight) == pindexNew) {
1310 pindexBestHeader = m_chain.Tip();
1311 }
1312
1313 LogPrintf("%s: invalid block=%s height=%d log2_work=%f date=%s\n", __func__,
1314 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1315 log(pindexNew->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(pindexNew->GetBlockTime()));
1316 CBlockIndex *tip = m_chain.Tip();
1317 assert (tip);
1318 LogPrintf("%s: current best=%s height=%d log2_work=%f date=%s\n", __func__,
1319 tip->GetBlockHash().ToString(), m_chain.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1320 FormatISO8601DateTime(tip->GetBlockTime()));
1321 CheckForkWarningConditions();
1322 }
1323
1324 // Same as InvalidChainFound, above, except not called directly from InvalidateBlock,
1325 // which does its own setBlockIndexCandidates management.
InvalidBlockFound(CBlockIndex * pindex,const BlockValidationState & state)1326 void CChainState::InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state)
1327 {
1328 if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
1329 pindex->nStatus |= BLOCK_FAILED_VALID;
1330 m_blockman.m_failed_blocks.insert(pindex);
1331 setDirtyBlockIndex.insert(pindex);
1332 setBlockIndexCandidates.erase(pindex);
1333 InvalidChainFound(pindex);
1334 }
1335 }
1336
UpdateCoins(const CTransaction & tx,CCoinsViewCache & inputs,CTxUndo & txundo,int nHeight)1337 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1338 {
1339 // mark inputs spent
1340 if (!tx.IsCoinBase()) {
1341 txundo.vprevout.reserve(tx.vin.size());
1342 for (const CTxIn &txin : tx.vin) {
1343 txundo.vprevout.emplace_back();
1344 bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1345 assert(is_spent);
1346 }
1347 }
1348 // add outputs
1349 AddCoins(inputs, tx, nHeight);
1350 }
1351
UpdateCoins(const CTransaction & tx,CCoinsViewCache & inputs,int nHeight)1352 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1353 {
1354 CTxUndo txundo;
1355 UpdateCoins(tx, inputs, txundo, nHeight);
1356 }
1357
operator ()()1358 bool CScriptCheck::operator()() {
1359 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1360 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1361 return VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *txdata), &error);
1362 }
1363
GetSpendHeight(const CCoinsViewCache & inputs)1364 int BlockManager::GetSpendHeight(const CCoinsViewCache& inputs)
1365 {
1366 AssertLockHeld(cs_main);
1367 CBlockIndex* pindexPrev = LookupBlockIndex(inputs.GetBestBlock());
1368 return pindexPrev->nHeight + 1;
1369 }
1370
1371
1372 static CuckooCache::cache<uint256, SignatureCacheHasher> g_scriptExecutionCache;
1373 static CSHA256 g_scriptExecutionCacheHasher;
1374
InitScriptExecutionCache()1375 void InitScriptExecutionCache() {
1376 // Setup the salted hasher
1377 uint256 nonce = GetRandHash();
1378 // We want the nonce to be 64 bytes long to force the hasher to process
1379 // this chunk, which makes later hash computations more efficient. We
1380 // just write our 32-byte entropy twice to fill the 64 bytes.
1381 g_scriptExecutionCacheHasher.Write(nonce.begin(), 32);
1382 g_scriptExecutionCacheHasher.Write(nonce.begin(), 32);
1383 // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1384 // setup_bytes creates the minimum possible cache (2 elements).
1385 size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
1386 size_t nElems = g_scriptExecutionCache.setup_bytes(nMaxCacheSize);
1387 LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1388 (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1389 }
1390
1391 /**
1392 * Check whether all of this transaction's input scripts succeed.
1393 *
1394 * This involves ECDSA signature checks so can be computationally intensive. This function should
1395 * only be called after the cheap sanity checks in CheckTxInputs passed.
1396 *
1397 * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
1398 * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
1399 * not pushed onto pvChecks/run.
1400 *
1401 * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
1402 * which are matched. This is useful for checking blocks where we will likely never need the cache
1403 * entry again.
1404 *
1405 * Note that we may set state.reason to NOT_STANDARD for extra soft-fork flags in flags, block-checking
1406 * callers should probably reset it to CONSENSUS in such cases.
1407 *
1408 * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
1409 */
CheckInputScripts(const CTransaction & tx,TxValidationState & state,const CCoinsViewCache & inputs,unsigned int flags,bool cacheSigStore,bool cacheFullScriptStore,PrecomputedTransactionData & txdata,std::vector<CScriptCheck> * pvChecks)1410 bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
1411 const CCoinsViewCache& inputs, unsigned int flags, bool cacheSigStore,
1412 bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
1413 std::vector<CScriptCheck>* pvChecks)
1414 {
1415 if (tx.IsCoinBase()) return true;
1416
1417 if (pvChecks) {
1418 pvChecks->reserve(tx.vin.size());
1419 }
1420
1421 // First check if script executions have been cached with the same
1422 // flags. Note that this assumes that the inputs provided are
1423 // correct (ie that the transaction hash which is in tx's prevouts
1424 // properly commits to the scriptPubKey in the inputs view of that
1425 // transaction).
1426 uint256 hashCacheEntry;
1427 CSHA256 hasher = g_scriptExecutionCacheHasher;
1428 hasher.Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1429 AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1430 if (g_scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1431 return true;
1432 }
1433
1434 if (!txdata.m_spent_outputs_ready) {
1435 std::vector<CTxOut> spent_outputs;
1436 spent_outputs.reserve(tx.vin.size());
1437
1438 for (const auto& txin : tx.vin) {
1439 const COutPoint& prevout = txin.prevout;
1440 const Coin& coin = inputs.AccessCoin(prevout);
1441 assert(!coin.IsSpent());
1442 spent_outputs.emplace_back(coin.out);
1443 }
1444 txdata.Init(tx, std::move(spent_outputs));
1445 }
1446 assert(txdata.m_spent_outputs.size() == tx.vin.size());
1447
1448 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1449
1450 // We very carefully only pass in things to CScriptCheck which
1451 // are clearly committed to by tx' witness hash. This provides
1452 // a sanity check that our caching is not introducing consensus
1453 // failures through additional data in, eg, the coins being
1454 // spent being checked as a part of CScriptCheck.
1455
1456 // Verify signature
1457 CScriptCheck check(txdata.m_spent_outputs[i], tx, i, flags, cacheSigStore, &txdata);
1458 if (pvChecks) {
1459 pvChecks->push_back(CScriptCheck());
1460 check.swap(pvChecks->back());
1461 } else if (!check()) {
1462 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1463 // Check whether the failure was caused by a
1464 // non-mandatory script verification check, such as
1465 // non-standard DER encodings or non-null dummy
1466 // arguments; if so, ensure we return NOT_STANDARD
1467 // instead of CONSENSUS to avoid downstream users
1468 // splitting the network between upgraded and
1469 // non-upgraded nodes by banning CONSENSUS-failing
1470 // data providers.
1471 CScriptCheck check2(txdata.m_spent_outputs[i], tx, i,
1472 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1473 if (check2())
1474 return state.Invalid(TxValidationResult::TX_NOT_STANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1475 }
1476 // MANDATORY flag failures correspond to
1477 // TxValidationResult::TX_CONSENSUS. Because CONSENSUS
1478 // failures are the most serious case of validation
1479 // failures, we may need to consider using
1480 // RECENT_CONSENSUS_CHANGE for any script failure that
1481 // could be due to non-upgraded nodes which we may want to
1482 // support, to avoid splitting the network (but this
1483 // depends on the details of how net_processing handles
1484 // such errors).
1485 return state.Invalid(TxValidationResult::TX_CONSENSUS, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1486 }
1487 }
1488
1489 if (cacheFullScriptStore && !pvChecks) {
1490 // We executed all of the provided scripts, and were told to
1491 // cache the result. Do so now.
1492 g_scriptExecutionCache.insert(hashCacheEntry);
1493 }
1494
1495 return true;
1496 }
1497
AbortNode(BlockValidationState & state,const std::string & strMessage,const bilingual_str & userMessage)1498 bool AbortNode(BlockValidationState& state, const std::string& strMessage, const bilingual_str& userMessage)
1499 {
1500 AbortNode(strMessage, userMessage);
1501 return state.Error(strMessage);
1502 }
1503
1504 /**
1505 * Restore the UTXO in a Coin at a given COutPoint
1506 * @param undo The Coin to be restored.
1507 * @param view The coins view to which to apply the changes.
1508 * @param out The out point that corresponds to the tx input.
1509 * @return A DisconnectResult as an int
1510 */
ApplyTxInUndo(Coin && undo,CCoinsViewCache & view,const COutPoint & out)1511 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1512 {
1513 bool fClean = true;
1514
1515 if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1516
1517 if (undo.nHeight == 0) {
1518 // Missing undo metadata (height and coinbase). Older versions included this
1519 // information only in undo records for the last spend of a transactions'
1520 // outputs. This implies that it must be present for some other output of the same tx.
1521 const Coin& alternate = AccessByTxid(view, out.hash);
1522 if (!alternate.IsSpent()) {
1523 undo.nHeight = alternate.nHeight;
1524 undo.fCoinBase = alternate.fCoinBase;
1525 } else {
1526 return DISCONNECT_FAILED; // adding output for transaction without known metadata
1527 }
1528 }
1529 // If the coin already exists as an unspent coin in the cache, then the
1530 // possible_overwrite parameter to AddCoin must be set to true. We have
1531 // already checked whether an unspent coin exists above using HaveCoin, so
1532 // we don't need to guess. When fClean is false, an unspent coin already
1533 // existed and it is an overwrite.
1534 view.AddCoin(out, std::move(undo), !fClean);
1535
1536 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1537 }
1538
1539 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1540 * When FAILED is returned, view is left in an indeterminate state. */
DisconnectBlock(const CBlock & block,const CBlockIndex * pindex,CCoinsViewCache & view)1541 DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1542 {
1543 bool fClean = true;
1544
1545 CBlockUndo blockUndo;
1546 if (!UndoReadFromDisk(blockUndo, pindex)) {
1547 error("DisconnectBlock(): failure reading undo data");
1548 return DISCONNECT_FAILED;
1549 }
1550
1551 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1552 error("DisconnectBlock(): block and undo data inconsistent");
1553 return DISCONNECT_FAILED;
1554 }
1555
1556 // undo transactions in reverse order
1557 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1558 const CTransaction &tx = *(block.vtx[i]);
1559 uint256 hash = tx.GetHash();
1560 bool is_coinbase = tx.IsCoinBase();
1561
1562 // Check that all outputs are available and match the outputs in the block itself
1563 // exactly.
1564 for (size_t o = 0; o < tx.vout.size(); o++) {
1565 if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1566 COutPoint out(hash, o);
1567 Coin coin;
1568 bool is_spent = view.SpendCoin(out, &coin);
1569 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1570 fClean = false; // transaction output mismatch
1571 }
1572 }
1573 }
1574
1575 // restore inputs
1576 if (i > 0) { // not coinbases
1577 CTxUndo &txundo = blockUndo.vtxundo[i-1];
1578 if (txundo.vprevout.size() != tx.vin.size()) {
1579 error("DisconnectBlock(): transaction and undo data inconsistent");
1580 return DISCONNECT_FAILED;
1581 }
1582 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1583 const COutPoint &out = tx.vin[j].prevout;
1584 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1585 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1586 fClean = fClean && res != DISCONNECT_UNCLEAN;
1587 }
1588 // At this point, all of txundo.vprevout should have been moved out.
1589 }
1590 }
1591
1592 // move best block pointer to prevout block
1593 view.SetBestBlock(pindex->pprev->GetBlockHash());
1594
1595 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1596 }
1597
1598 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1599
StartScriptCheckWorkerThreads(int threads_num)1600 void StartScriptCheckWorkerThreads(int threads_num)
1601 {
1602 scriptcheckqueue.StartWorkerThreads(threads_num);
1603 }
1604
StopScriptCheckWorkerThreads()1605 void StopScriptCheckWorkerThreads()
1606 {
1607 scriptcheckqueue.StopWorkerThreads();
1608 }
1609
1610 /**
1611 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1612 */
1613 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1614 {
1615 private:
1616 int bit;
1617
1618 public:
WarningBitsConditionChecker(int bitIn)1619 explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1620
BeginTime(const Consensus::Params & params) const1621 int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
EndTime(const Consensus::Params & params) const1622 int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
Period(const Consensus::Params & params) const1623 int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
Threshold(const Consensus::Params & params) const1624 int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1625
Condition(const CBlockIndex * pindex,const Consensus::Params & params) const1626 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1627 {
1628 return pindex->nHeight >= params.MinBIP9WarningHeight &&
1629 ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1630 ((pindex->nVersion >> bit) & 1) != 0 &&
1631 ((g_versionbitscache.ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1632 }
1633 };
1634
1635 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS] GUARDED_BY(cs_main);
1636
GetBlockScriptFlags(const CBlockIndex * pindex,const Consensus::Params & consensusparams)1637 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams)
1638 {
1639 unsigned int flags = SCRIPT_VERIFY_NONE;
1640
1641 // BIP16 didn't become active until Apr 1 2012 (on mainnet, and
1642 // retroactively applied to testnet)
1643 // However, only one historical block violated the P2SH rules (on both
1644 // mainnet and testnet), so for simplicity, always leave P2SH
1645 // on except for the one violating block.
1646 if (consensusparams.BIP16Exception.IsNull() || // no bip16 exception on this chain
1647 pindex->phashBlock == nullptr || // this is a new candidate block, eg from TestBlockValidity()
1648 *pindex->phashBlock != consensusparams.BIP16Exception) // this block isn't the historical exception
1649 {
1650 flags |= SCRIPT_VERIFY_P2SH;
1651 }
1652
1653 // Enforce WITNESS rules whenever P2SH is in effect (and the segwit
1654 // deployment is defined).
1655 if (flags & SCRIPT_VERIFY_P2SH && DeploymentEnabled(consensusparams, Consensus::DEPLOYMENT_SEGWIT)) {
1656 flags |= SCRIPT_VERIFY_WITNESS;
1657 }
1658
1659 // Enforce the DERSIG (BIP66) rule
1660 if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_DERSIG)) {
1661 flags |= SCRIPT_VERIFY_DERSIG;
1662 }
1663
1664 // Enforce CHECKLOCKTIMEVERIFY (BIP65)
1665 if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_CLTV)) {
1666 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1667 }
1668
1669 // Enforce CHECKSEQUENCEVERIFY (BIP112)
1670 if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_CSV)) {
1671 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1672 }
1673
1674 // Enforce Taproot (BIP340-BIP342)
1675 if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_TAPROOT)) {
1676 flags |= SCRIPT_VERIFY_TAPROOT;
1677 }
1678
1679 // Enforce BIP147 NULLDUMMY (activated simultaneously with segwit)
1680 if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_SEGWIT)) {
1681 flags |= SCRIPT_VERIFY_NULLDUMMY;
1682 }
1683
1684 return flags;
1685 }
1686
1687
1688
1689 static int64_t nTimeCheck = 0;
1690 static int64_t nTimeForks = 0;
1691 static int64_t nTimeVerify = 0;
1692 static int64_t nTimeConnect = 0;
1693 static int64_t nTimeIndex = 0;
1694 static int64_t nTimeCallbacks = 0;
1695 static int64_t nTimeTotal = 0;
1696 static int64_t nBlocksTotal = 0;
1697
1698 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1699 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1700 * can fail if those validity checks fail (among other reasons). */
ConnectBlock(const CBlock & block,BlockValidationState & state,CBlockIndex * pindex,CCoinsViewCache & view,bool fJustCheck)1701 bool CChainState::ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
1702 CCoinsViewCache& view, bool fJustCheck)
1703 {
1704 AssertLockHeld(cs_main);
1705 assert(pindex);
1706 assert(*pindex->phashBlock == block.GetHash());
1707 int64_t nTimeStart = GetTimeMicros();
1708
1709 // Check it again in case a previous version let a bad block in
1710 // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
1711 // ContextualCheckBlockHeader() here. This means that if we add a new
1712 // consensus rule that is enforced in one of those two functions, then we
1713 // may have let in a block that violates the rule prior to updating the
1714 // software, and we would NOT be enforcing the rule here. Fully solving
1715 // upgrade from one software version to the next after a consensus rule
1716 // change is potentially tricky and issue-specific (see NeedsRedownload()
1717 // for one approach that was used for BIP 141 deployment).
1718 // Also, currently the rule against blocks more than 2 hours in the future
1719 // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
1720 // re-enforce that rule here (at least until we make it impossible for
1721 // GetAdjustedTime() to go backward).
1722 if (!CheckBlock(block, state, m_params.GetConsensus(), !fJustCheck, !fJustCheck)) {
1723 if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED) {
1724 // We don't write down blocks to disk if they may have been
1725 // corrupted, so this should be impossible unless we're having hardware
1726 // problems.
1727 return AbortNode(state, "Corrupt block found indicating potential hardware failure; shutting down");
1728 }
1729 return error("%s: Consensus::CheckBlock: %s", __func__, state.ToString());
1730 }
1731
1732 // verify that the view's current state corresponds to the previous block
1733 uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
1734 assert(hashPrevBlock == view.GetBestBlock());
1735
1736 nBlocksTotal++;
1737
1738 // Special case for the genesis block, skipping connection of its transactions
1739 // (its coinbase is unspendable)
1740 if (block.GetHash() == m_params.GetConsensus().hashGenesisBlock) {
1741 if (!fJustCheck)
1742 view.SetBestBlock(pindex->GetBlockHash());
1743 return true;
1744 }
1745
1746 bool fScriptChecks = true;
1747 if (!hashAssumeValid.IsNull()) {
1748 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1749 // A suitable default value is included with the software and updated from time to time. Because validity
1750 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1751 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1752 // effectively caching the result of part of the verification.
1753 BlockMap::const_iterator it = m_blockman.m_block_index.find(hashAssumeValid);
1754 if (it != m_blockman.m_block_index.end()) {
1755 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1756 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1757 pindexBestHeader->nChainWork >= nMinimumChainWork) {
1758 // This block is a member of the assumed verified chain and an ancestor of the best header.
1759 // Script verification is skipped when connecting blocks under the
1760 // assumevalid block. Assuming the assumevalid block is valid this
1761 // is safe because block merkle hashes are still computed and checked,
1762 // Of course, if an assumed valid block is invalid due to false scriptSigs
1763 // this optimization would allow an invalid chain to be accepted.
1764 // The equivalent time check discourages hash power from extorting the network via DOS attack
1765 // into accepting an invalid block through telling users they must manually set assumevalid.
1766 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1767 // it hard to hide the implication of the demand. This also avoids having release candidates
1768 // that are hardly doing any signature verification at all in testing without having to
1769 // artificially set the default assumed verified block further back.
1770 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1771 // least as good as the expected chain.
1772 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, m_params.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1773 }
1774 }
1775 }
1776
1777 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1778 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
1779
1780 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1781 // unless those are already completely spent.
1782 // If such overwrites are allowed, coinbases and transactions depending upon those
1783 // can be duplicated to remove the ability to spend the first instance -- even after
1784 // being sent to another address.
1785 // See BIP30, CVE-2012-1909, and http://r6.ca/blog/20120206T005236Z.html for more information.
1786 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1787 // already refuses previously-known transaction ids entirely.
1788 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1789 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1790 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1791 // initial block download.
1792 bool fEnforceBIP30 = !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1793 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1794
1795 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1796 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1797 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1798 // before the first had been spent. Since those coinbases are sufficiently buried it's no longer possible to create further
1799 // duplicate transactions descending from the known pairs either.
1800 // 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.
1801
1802 // BIP34 requires that a block at height X (block X) has its coinbase
1803 // scriptSig start with a CScriptNum of X (indicated height X). The above
1804 // logic of no longer requiring BIP30 once BIP34 activates is flawed in the
1805 // case that there is a block X before the BIP34 height of 227,931 which has
1806 // an indicated height Y where Y is greater than X. The coinbase for block
1807 // X would also be a valid coinbase for block Y, which could be a BIP30
1808 // violation. An exhaustive search of all mainnet coinbases before the
1809 // BIP34 height which have an indicated height greater than the block height
1810 // reveals many occurrences. The 3 lowest indicated heights found are
1811 // 209,921, 490,897, and 1,983,702 and thus coinbases for blocks at these 3
1812 // heights would be the first opportunity for BIP30 to be violated.
1813
1814 // The search reveals a great many blocks which have an indicated height
1815 // greater than 1,983,702, so we simply remove the optimization to skip
1816 // BIP30 checking for blocks at height 1,983,702 or higher. Before we reach
1817 // that block in another 25 years or so, we should take advantage of a
1818 // future consensus change to do a new and improved version of BIP34 that
1819 // will actually prevent ever creating any duplicate coinbases in the
1820 // future.
1821 static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
1822
1823 // There is no potential to create a duplicate coinbase at block 209,921
1824 // because this is still before the BIP34 height and so explicit BIP30
1825 // checking is still active.
1826
1827 // The final case is block 176,684 which has an indicated height of
1828 // 490,897. Unfortunately, this issue was not discovered until about 2 weeks
1829 // before block 490,897 so there was not much opportunity to address this
1830 // case other than to carefully analyze it and determine it would not be a
1831 // problem. Block 490,897 was, in fact, mined with a different coinbase than
1832 // block 176,684, but it is important to note that even if it hadn't been or
1833 // is remined on an alternate fork with a duplicate coinbase, we would still
1834 // not run into a BIP30 violation. This is because the coinbase for 176,684
1835 // is spent in block 185,956 in transaction
1836 // d4f7fbbf92f4a3014a230b2dc70b8058d02eb36ac06b4a0736d9d60eaa9e8781. This
1837 // spending transaction can't be duplicated because it also spends coinbase
1838 // 0328dd85c331237f18e781d692c92de57649529bd5edf1d01036daea32ffde29. This
1839 // coinbase has an indicated height of over 4.2 billion, and wouldn't be
1840 // duplicatable until that height, and it's currently impossible to create a
1841 // chain that long. Nevertheless we may wish to consider a future soft fork
1842 // which retroactively prevents block 490,897 from creating a duplicate
1843 // coinbase. The two historical BIP30 violations often provide a confusing
1844 // edge case when manipulating the UTXO and it would be simpler not to have
1845 // another edge case to deal with.
1846
1847 // testnet3 has no blocks before the BIP34 height with indicated heights
1848 // post BIP34 before approximately height 486,000,000 and presumably will
1849 // be reset before it reaches block 1,983,702 and starts doing unnecessary
1850 // BIP30 checking again.
1851 assert(pindex->pprev);
1852 CBlockIndex* pindexBIP34height = pindex->pprev->GetAncestor(m_params.GetConsensus().BIP34Height);
1853 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1854 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == m_params.GetConsensus().BIP34Hash));
1855
1856 // TODO: Remove BIP30 checking from block height 1,983,702 on, once we have a
1857 // consensus change that ensures coinbases at those heights can not
1858 // duplicate earlier coinbases.
1859 if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
1860 for (const auto& tx : block.vtx) {
1861 for (size_t o = 0; o < tx->vout.size(); o++) {
1862 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
1863 LogPrintf("ERROR: ConnectBlock(): tried to overwrite transaction\n");
1864 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-BIP30");
1865 }
1866 }
1867 }
1868 }
1869
1870 // Enforce BIP68 (sequence locks)
1871 int nLockTimeFlags = 0;
1872 if (DeploymentActiveAt(*pindex, m_params.GetConsensus(), Consensus::DEPLOYMENT_CSV)) {
1873 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1874 }
1875
1876 // Get the script flags for this block
1877 unsigned int flags = GetBlockScriptFlags(pindex, m_params.GetConsensus());
1878
1879 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1880 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
1881
1882 CBlockUndo blockundo;
1883
1884 // Precomputed transaction data pointers must not be invalidated
1885 // until after `control` has run the script checks (potentially
1886 // in multiple threads). Preallocate the vector size so a new allocation
1887 // doesn't invalidate pointers into the vector, and keep txsdata in scope
1888 // for as long as `control`.
1889 CCheckQueueControl<CScriptCheck> control(fScriptChecks && g_parallel_script_checks ? &scriptcheckqueue : nullptr);
1890 std::vector<PrecomputedTransactionData> txsdata(block.vtx.size());
1891
1892 std::vector<int> prevheights;
1893 CAmount nFees = 0;
1894 int nInputs = 0;
1895 int64_t nSigOpsCost = 0;
1896 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1897 for (unsigned int i = 0; i < block.vtx.size(); i++)
1898 {
1899 const CTransaction &tx = *(block.vtx[i]);
1900
1901 nInputs += tx.vin.size();
1902
1903 if (!tx.IsCoinBase())
1904 {
1905 CAmount txfee = 0;
1906 TxValidationState tx_state;
1907 if (!Consensus::CheckTxInputs(tx, tx_state, view, pindex->nHeight, txfee)) {
1908 // Any transaction validation failure in ConnectBlock is a block consensus failure
1909 state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,
1910 tx_state.GetRejectReason(), tx_state.GetDebugMessage());
1911 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), state.ToString());
1912 }
1913 nFees += txfee;
1914 if (!MoneyRange(nFees)) {
1915 LogPrintf("ERROR: %s: accumulated fee in the block out of range.\n", __func__);
1916 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-accumulated-fee-outofrange");
1917 }
1918
1919 // Check that transaction is BIP68 final
1920 // BIP68 lock checks (as opposed to nLockTime checks) must
1921 // be in ConnectBlock because they require the UTXO set
1922 prevheights.resize(tx.vin.size());
1923 for (size_t j = 0; j < tx.vin.size(); j++) {
1924 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
1925 }
1926
1927 if (!SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
1928 LogPrintf("ERROR: %s: contains a non-BIP68-final transaction\n", __func__);
1929 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal");
1930 }
1931 }
1932
1933 // GetTransactionSigOpCost counts 3 types of sigops:
1934 // * legacy (always)
1935 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1936 // * witness (when witness enabled in flags and excludes coinbase)
1937 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1938 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST) {
1939 LogPrintf("ERROR: ConnectBlock(): too many sigops\n");
1940 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops");
1941 }
1942
1943 if (!tx.IsCoinBase())
1944 {
1945 std::vector<CScriptCheck> vChecks;
1946 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1947 TxValidationState tx_state;
1948 if (fScriptChecks && !CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], g_parallel_script_checks ? &vChecks : nullptr)) {
1949 // Any transaction validation failure in ConnectBlock is a block consensus failure
1950 state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,
1951 tx_state.GetRejectReason(), tx_state.GetDebugMessage());
1952 return error("ConnectBlock(): CheckInputScripts on %s failed with %s",
1953 tx.GetHash().ToString(), state.ToString());
1954 }
1955 control.Add(vChecks);
1956 }
1957
1958 CTxUndo undoDummy;
1959 if (i > 0) {
1960 blockundo.vtxundo.push_back(CTxUndo());
1961 }
1962 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1963 }
1964 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1965 LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(), MILLI * (nTime3 - nTime2), MILLI * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : MILLI * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * MICRO, nTimeConnect * MILLI / nBlocksTotal);
1966
1967 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, m_params.GetConsensus());
1968 if (block.vtx[0]->GetValueOut() > blockReward) {
1969 LogPrintf("ERROR: ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)\n", block.vtx[0]->GetValueOut(), blockReward);
1970 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-amount");
1971 }
1972
1973 if (!control.Wait()) {
1974 LogPrintf("ERROR: %s: CheckQueue failed\n", __func__);
1975 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "block-validation-failed");
1976 }
1977 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1978 LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1, MILLI * (nTime4 - nTime2), nInputs <= 1 ? 0 : MILLI * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * MICRO, nTimeVerify * MILLI / nBlocksTotal);
1979
1980 if (fJustCheck)
1981 return true;
1982
1983 if (!WriteUndoDataForBlock(blockundo, state, pindex, m_params)) {
1984 return false;
1985 }
1986
1987 if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
1988 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1989 setDirtyBlockIndex.insert(pindex);
1990 }
1991
1992 assert(pindex->phashBlock);
1993 // add this block to the view's block chain
1994 view.SetBestBlock(pindex->GetBlockHash());
1995
1996 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1997 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
1998
1999 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
2000 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
2001
2002 return true;
2003 }
2004
GetCoinsCacheSizeState()2005 CoinsCacheSizeState CChainState::GetCoinsCacheSizeState()
2006 {
2007 return this->GetCoinsCacheSizeState(
2008 m_coinstip_cache_size_bytes,
2009 gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
2010 }
2011
GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes,size_t max_mempool_size_bytes)2012 CoinsCacheSizeState CChainState::GetCoinsCacheSizeState(
2013 size_t max_coins_cache_size_bytes,
2014 size_t max_mempool_size_bytes)
2015 {
2016 const int64_t nMempoolUsage = m_mempool ? m_mempool->DynamicMemoryUsage() : 0;
2017 int64_t cacheSize = CoinsTip().DynamicMemoryUsage();
2018 int64_t nTotalSpace =
2019 max_coins_cache_size_bytes + std::max<int64_t>(max_mempool_size_bytes - nMempoolUsage, 0);
2020
2021 //! No need to periodic flush if at least this much space still available.
2022 static constexpr int64_t MAX_BLOCK_COINSDB_USAGE_BYTES = 10 * 1024 * 1024; // 10MB
2023 int64_t large_threshold =
2024 std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE_BYTES);
2025
2026 if (cacheSize > nTotalSpace) {
2027 LogPrintf("Cache size (%s) exceeds total space (%s)\n", cacheSize, nTotalSpace);
2028 return CoinsCacheSizeState::CRITICAL;
2029 } else if (cacheSize > large_threshold) {
2030 return CoinsCacheSizeState::LARGE;
2031 }
2032 return CoinsCacheSizeState::OK;
2033 }
2034
FlushStateToDisk(BlockValidationState & state,FlushStateMode mode,int nManualPruneHeight)2035 bool CChainState::FlushStateToDisk(
2036 BlockValidationState &state,
2037 FlushStateMode mode,
2038 int nManualPruneHeight)
2039 {
2040 LOCK(cs_main);
2041 assert(this->CanFlushToDisk());
2042 static std::chrono::microseconds nLastWrite{0};
2043 static std::chrono::microseconds nLastFlush{0};
2044 std::set<int> setFilesToPrune;
2045 bool full_flush_completed = false;
2046
2047 const size_t coins_count = CoinsTip().GetCacheSize();
2048 const size_t coins_mem_usage = CoinsTip().DynamicMemoryUsage();
2049
2050 try {
2051 {
2052 bool fFlushForPrune = false;
2053 bool fDoFullFlush = false;
2054
2055 CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
2056 LOCK(cs_LastBlockFile);
2057 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
2058 // make sure we don't prune above the blockfilterindexes bestblocks
2059 // pruning is height-based
2060 int last_prune = m_chain.Height(); // last height we can prune
2061 ForEachBlockFilterIndex([&](BlockFilterIndex& index) {
2062 last_prune = std::max(1, std::min(last_prune, index.GetSummary().best_block_height));
2063 });
2064
2065 if (nManualPruneHeight > 0) {
2066 LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune (manual)", BCLog::BENCH);
2067
2068 m_blockman.FindFilesToPruneManual(setFilesToPrune, std::min(last_prune, nManualPruneHeight), m_chain.Height());
2069 } else {
2070 LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune", BCLog::BENCH);
2071
2072 m_blockman.FindFilesToPrune(setFilesToPrune, m_params.PruneAfterHeight(), m_chain.Height(), last_prune, IsInitialBlockDownload());
2073 fCheckForPruning = false;
2074 }
2075 if (!setFilesToPrune.empty()) {
2076 fFlushForPrune = true;
2077 if (!fHavePruned) {
2078 pblocktree->WriteFlag("prunedblockfiles", true);
2079 fHavePruned = true;
2080 }
2081 }
2082 }
2083 const auto nNow = GetTime<std::chrono::microseconds>();
2084 // Avoid writing/flushing immediately after startup.
2085 if (nLastWrite.count() == 0) {
2086 nLastWrite = nNow;
2087 }
2088 if (nLastFlush.count() == 0) {
2089 nLastFlush = nNow;
2090 }
2091 // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
2092 bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
2093 // The cache is over the limit, we have to write now.
2094 bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
2095 // 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.
2096 bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > nLastWrite + DATABASE_WRITE_INTERVAL;
2097 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2098 bool fPeriodicFlush = mode == FlushStateMode::PERIODIC && nNow > nLastFlush + DATABASE_FLUSH_INTERVAL;
2099 // Combine all conditions that result in a full cache flush.
2100 fDoFullFlush = (mode == FlushStateMode::ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2101 // Write blocks and block index to disk.
2102 if (fDoFullFlush || fPeriodicWrite) {
2103 // Depend on nMinDiskSpace to ensure we can write block index
2104 if (!CheckDiskSpace(gArgs.GetBlocksDirPath())) {
2105 return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
2106 }
2107 {
2108 LOG_TIME_MILLIS_WITH_CATEGORY("write block and undo data to disk", BCLog::BENCH);
2109
2110 // First make sure all block and undo data is flushed to disk.
2111 FlushBlockFile();
2112 }
2113
2114 // Then update all block file information (which may refer to block and undo files).
2115 {
2116 LOG_TIME_MILLIS_WITH_CATEGORY("write block index to disk", BCLog::BENCH);
2117
2118 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2119 vFiles.reserve(setDirtyFileInfo.size());
2120 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2121 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
2122 setDirtyFileInfo.erase(it++);
2123 }
2124 std::vector<const CBlockIndex*> vBlocks;
2125 vBlocks.reserve(setDirtyBlockIndex.size());
2126 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2127 vBlocks.push_back(*it);
2128 setDirtyBlockIndex.erase(it++);
2129 }
2130 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2131 return AbortNode(state, "Failed to write to block index database");
2132 }
2133 }
2134 // Finally remove any pruned files
2135 if (fFlushForPrune) {
2136 LOG_TIME_MILLIS_WITH_CATEGORY("unlink pruned files", BCLog::BENCH);
2137
2138 UnlinkPrunedFiles(setFilesToPrune);
2139 }
2140 nLastWrite = nNow;
2141 }
2142 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2143 if (fDoFullFlush && !CoinsTip().GetBestBlock().IsNull()) {
2144 LOG_TIME_SECONDS(strprintf("write coins cache to disk (%d coins, %.2fkB)",
2145 coins_count, coins_mem_usage / 1000));
2146
2147 // Typical Coin structures on disk are around 48 bytes in size.
2148 // Pushing a new one to the database can cause it to be written
2149 // twice (once in the log, and once in the tables). This is already
2150 // an overestimation, as most will delete an existing entry or
2151 // overwrite one. Still, use a conservative safety factor of 2.
2152 if (!CheckDiskSpace(gArgs.GetDataDirNet(), 48 * 2 * 2 * CoinsTip().GetCacheSize())) {
2153 return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
2154 }
2155 // Flush the chainstate (which may refer to block index entries).
2156 if (!CoinsTip().Flush())
2157 return AbortNode(state, "Failed to write to coin database");
2158 nLastFlush = nNow;
2159 full_flush_completed = true;
2160 }
2161 }
2162 if (full_flush_completed) {
2163 // Update best block in wallet (so we can detect restored wallets).
2164 GetMainSignals().ChainStateFlushed(m_chain.GetLocator());
2165 }
2166 } catch (const std::runtime_error& e) {
2167 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2168 }
2169 return true;
2170 }
2171
ForceFlushStateToDisk()2172 void CChainState::ForceFlushStateToDisk()
2173 {
2174 BlockValidationState state;
2175 if (!this->FlushStateToDisk(state, FlushStateMode::ALWAYS)) {
2176 LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
2177 }
2178 }
2179
PruneAndFlush()2180 void CChainState::PruneAndFlush()
2181 {
2182 BlockValidationState state;
2183 fCheckForPruning = true;
2184 if (!this->FlushStateToDisk(state, FlushStateMode::NONE)) {
2185 LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
2186 }
2187 }
2188
DoWarning(const bilingual_str & warning)2189 static void DoWarning(const bilingual_str& warning)
2190 {
2191 static bool fWarned = false;
2192 SetMiscWarning(warning);
2193 if (!fWarned) {
2194 AlertNotify(warning.original);
2195 fWarned = true;
2196 }
2197 }
2198
2199 /** Private helper function that concatenates warning messages. */
AppendWarning(bilingual_str & res,const bilingual_str & warn)2200 static void AppendWarning(bilingual_str& res, const bilingual_str& warn)
2201 {
2202 if (!res.empty()) res += Untranslated(", ");
2203 res += warn;
2204 }
2205
UpdateTip(const CBlockIndex * pindexNew)2206 void CChainState::UpdateTip(const CBlockIndex* pindexNew)
2207 {
2208 // New best block
2209 if (m_mempool) {
2210 m_mempool->AddTransactionsUpdated(1);
2211 }
2212
2213 {
2214 LOCK(g_best_block_mutex);
2215 g_best_block = pindexNew->GetBlockHash();
2216 g_best_block_cv.notify_all();
2217 }
2218
2219 bilingual_str warning_messages;
2220 if (!this->IsInitialBlockDownload()) {
2221 const CBlockIndex* pindex = pindexNew;
2222 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2223 WarningBitsConditionChecker checker(bit);
2224 ThresholdState state = checker.GetStateFor(pindex, m_params.GetConsensus(), warningcache[bit]);
2225 if (state == ThresholdState::ACTIVE || state == ThresholdState::LOCKED_IN) {
2226 const bilingual_str warning = strprintf(_("Unknown new rules activated (versionbit %i)"), bit);
2227 if (state == ThresholdState::ACTIVE) {
2228 DoWarning(warning);
2229 } else {
2230 AppendWarning(warning_messages, warning);
2231 }
2232 }
2233 }
2234 }
2235 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)%s\n", __func__,
2236 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, pindexNew->nVersion,
2237 log(pindexNew->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
2238 FormatISO8601DateTime(pindexNew->GetBlockTime()),
2239 GuessVerificationProgress(m_params.TxData(), pindexNew), this->CoinsTip().DynamicMemoryUsage() * (1.0 / (1<<20)), this->CoinsTip().GetCacheSize(),
2240 !warning_messages.empty() ? strprintf(" warning='%s'", warning_messages.original) : "");
2241 }
2242
2243 /** Disconnect m_chain's tip.
2244 * After calling, the mempool will be in an inconsistent state, with
2245 * transactions from disconnected blocks being added to disconnectpool. You
2246 * should make the mempool consistent again by calling MaybeUpdateMempoolForReorg.
2247 * with cs_main held.
2248 *
2249 * If disconnectpool is nullptr, then no disconnected transactions are added to
2250 * disconnectpool (note that the caller is responsible for mempool consistency
2251 * in any case).
2252 */
DisconnectTip(BlockValidationState & state,DisconnectedBlockTransactions * disconnectpool)2253 bool CChainState::DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool)
2254 {
2255 AssertLockHeld(cs_main);
2256 if (m_mempool) AssertLockHeld(m_mempool->cs);
2257
2258 CBlockIndex *pindexDelete = m_chain.Tip();
2259 assert(pindexDelete);
2260 // Read block from disk.
2261 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2262 CBlock& block = *pblock;
2263 if (!ReadBlockFromDisk(block, pindexDelete, m_params.GetConsensus())) {
2264 return error("DisconnectTip(): Failed to read block");
2265 }
2266 // Apply the block atomically to the chain state.
2267 int64_t nStart = GetTimeMicros();
2268 {
2269 CCoinsViewCache view(&CoinsTip());
2270 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2271 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2272 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2273 bool flushed = view.Flush();
2274 assert(flushed);
2275 }
2276 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
2277 // Write the chain state to disk, if necessary.
2278 if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
2279 return false;
2280 }
2281
2282 if (disconnectpool && m_mempool) {
2283 // Save transactions to re-add to mempool at end of reorg
2284 for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2285 disconnectpool->addTransaction(*it);
2286 }
2287 while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2288 // Drop the earliest entry, and remove its children from the mempool.
2289 auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2290 m_mempool->removeRecursive(**it, MemPoolRemovalReason::REORG);
2291 disconnectpool->removeEntry(it);
2292 }
2293 }
2294
2295 m_chain.SetTip(pindexDelete->pprev);
2296
2297 UpdateTip(pindexDelete->pprev);
2298 // Let wallets know transactions went from 1-confirmed to
2299 // 0-confirmed or conflicted:
2300 GetMainSignals().BlockDisconnected(pblock, pindexDelete);
2301 return true;
2302 }
2303
2304 static int64_t nTimeReadFromDisk = 0;
2305 static int64_t nTimeConnectTotal = 0;
2306 static int64_t nTimeFlush = 0;
2307 static int64_t nTimeChainState = 0;
2308 static int64_t nTimePostConnect = 0;
2309
2310 struct PerBlockConnectTrace {
2311 CBlockIndex* pindex = nullptr;
2312 std::shared_ptr<const CBlock> pblock;
PerBlockConnectTracePerBlockConnectTrace2313 PerBlockConnectTrace() {}
2314 };
2315 /**
2316 * Used to track blocks whose transactions were applied to the UTXO state as a
2317 * part of a single ActivateBestChainStep call.
2318 *
2319 * This class is single-use, once you call GetBlocksConnected() you have to throw
2320 * it away and make a new one.
2321 */
2322 class ConnectTrace {
2323 private:
2324 std::vector<PerBlockConnectTrace> blocksConnected;
2325
2326 public:
ConnectTrace()2327 explicit ConnectTrace() : blocksConnected(1) {}
2328
BlockConnected(CBlockIndex * pindex,std::shared_ptr<const CBlock> pblock)2329 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2330 assert(!blocksConnected.back().pindex);
2331 assert(pindex);
2332 assert(pblock);
2333 blocksConnected.back().pindex = pindex;
2334 blocksConnected.back().pblock = std::move(pblock);
2335 blocksConnected.emplace_back();
2336 }
2337
GetBlocksConnected()2338 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2339 // We always keep one extra block at the end of our list because
2340 // blocks are added after all the conflicted transactions have
2341 // been filled in. Thus, the last entry should always be an empty
2342 // one waiting for the transactions from the next block. We pop
2343 // the last entry here to make sure the list we return is sane.
2344 assert(!blocksConnected.back().pindex);
2345 blocksConnected.pop_back();
2346 return blocksConnected;
2347 }
2348 };
2349
2350 /**
2351 * Connect a new block to m_chain. pblock is either nullptr or a pointer to a CBlock
2352 * corresponding to pindexNew, to bypass loading it again from disk.
2353 *
2354 * The block is added to connectTrace if connection succeeds.
2355 */
ConnectTip(BlockValidationState & state,CBlockIndex * pindexNew,const std::shared_ptr<const CBlock> & pblock,ConnectTrace & connectTrace,DisconnectedBlockTransactions & disconnectpool)2356 bool CChainState::ConnectTip(BlockValidationState& state, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions& disconnectpool)
2357 {
2358 AssertLockHeld(cs_main);
2359 if (m_mempool) AssertLockHeld(m_mempool->cs);
2360
2361 assert(pindexNew->pprev == m_chain.Tip());
2362 // Read block from disk.
2363 int64_t nTime1 = GetTimeMicros();
2364 std::shared_ptr<const CBlock> pthisBlock;
2365 if (!pblock) {
2366 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2367 if (!ReadBlockFromDisk(*pblockNew, pindexNew, m_params.GetConsensus())) {
2368 return AbortNode(state, "Failed to read block");
2369 }
2370 pthisBlock = pblockNew;
2371 } else {
2372 pthisBlock = pblock;
2373 }
2374 const CBlock& blockConnecting = *pthisBlock;
2375 // Apply the block atomically to the chain state.
2376 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2377 int64_t nTime3;
2378 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
2379 {
2380 CCoinsViewCache view(&CoinsTip());
2381 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view);
2382 GetMainSignals().BlockChecked(blockConnecting, state);
2383 if (!rv) {
2384 if (state.IsInvalid())
2385 InvalidBlockFound(pindexNew, state);
2386 return error("%s: ConnectBlock %s failed, %s", __func__, pindexNew->GetBlockHash().ToString(), state.ToString());
2387 }
2388 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2389 assert(nBlocksTotal > 0);
2390 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
2391 bool flushed = view.Flush();
2392 assert(flushed);
2393 }
2394 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2395 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
2396 // Write the chain state to disk, if necessary.
2397 if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
2398 return false;
2399 }
2400 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2401 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
2402 // Remove conflicting transactions from the mempool.;
2403 if (m_mempool) {
2404 m_mempool->removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2405 disconnectpool.removeForBlock(blockConnecting.vtx);
2406 }
2407 // Update m_chain & related variables.
2408 m_chain.SetTip(pindexNew);
2409 UpdateTip(pindexNew);
2410
2411 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2412 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
2413 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
2414
2415 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2416 return true;
2417 }
2418
2419 /**
2420 * Return the tip of the chain with the most work in it, that isn't
2421 * known to be invalid (it's however far from certain to be valid).
2422 */
FindMostWorkChain()2423 CBlockIndex* CChainState::FindMostWorkChain() {
2424 do {
2425 CBlockIndex *pindexNew = nullptr;
2426
2427 // Find the best candidate header.
2428 {
2429 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2430 if (it == setBlockIndexCandidates.rend())
2431 return nullptr;
2432 pindexNew = *it;
2433 }
2434
2435 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2436 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2437 CBlockIndex *pindexTest = pindexNew;
2438 bool fInvalidAncestor = false;
2439 while (pindexTest && !m_chain.Contains(pindexTest)) {
2440 assert(pindexTest->HaveTxsDownloaded() || pindexTest->nHeight == 0);
2441
2442 // Pruned nodes may have entries in setBlockIndexCandidates for
2443 // which block files have been deleted. Remove those as candidates
2444 // for the most work chain if we come across them; we can't switch
2445 // to a chain unless we have all the non-active-chain parent blocks.
2446 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2447 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2448 if (fFailedChain || fMissingData) {
2449 // Candidate chain is not usable (either invalid or missing data)
2450 if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2451 pindexBestInvalid = pindexNew;
2452 CBlockIndex *pindexFailed = pindexNew;
2453 // Remove the entire chain from the set.
2454 while (pindexTest != pindexFailed) {
2455 if (fFailedChain) {
2456 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2457 } else if (fMissingData) {
2458 // If we're missing data, then add back to m_blocks_unlinked,
2459 // so that if the block arrives in the future we can try adding
2460 // to setBlockIndexCandidates again.
2461 m_blockman.m_blocks_unlinked.insert(
2462 std::make_pair(pindexFailed->pprev, pindexFailed));
2463 }
2464 setBlockIndexCandidates.erase(pindexFailed);
2465 pindexFailed = pindexFailed->pprev;
2466 }
2467 setBlockIndexCandidates.erase(pindexTest);
2468 fInvalidAncestor = true;
2469 break;
2470 }
2471 pindexTest = pindexTest->pprev;
2472 }
2473 if (!fInvalidAncestor)
2474 return pindexNew;
2475 } while(true);
2476 }
2477
2478 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
PruneBlockIndexCandidates()2479 void CChainState::PruneBlockIndexCandidates() {
2480 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2481 // reorganization to a better block fails.
2482 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2483 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) {
2484 setBlockIndexCandidates.erase(it++);
2485 }
2486 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2487 assert(!setBlockIndexCandidates.empty());
2488 }
2489
2490 /**
2491 * Try to make some progress towards making pindexMostWork the active block.
2492 * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
2493 *
2494 * @returns true unless a system error occurred
2495 */
ActivateBestChainStep(BlockValidationState & state,CBlockIndex * pindexMostWork,const std::shared_ptr<const CBlock> & pblock,bool & fInvalidFound,ConnectTrace & connectTrace)2496 bool CChainState::ActivateBestChainStep(BlockValidationState& state, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2497 {
2498 AssertLockHeld(cs_main);
2499 if (m_mempool) AssertLockHeld(m_mempool->cs);
2500
2501 const CBlockIndex* pindexOldTip = m_chain.Tip();
2502 const CBlockIndex* pindexFork = m_chain.FindFork(pindexMostWork);
2503
2504 // Disconnect active blocks which are no longer in the best chain.
2505 bool fBlocksDisconnected = false;
2506 DisconnectedBlockTransactions disconnectpool;
2507 while (m_chain.Tip() && m_chain.Tip() != pindexFork) {
2508 if (!DisconnectTip(state, &disconnectpool)) {
2509 // This is likely a fatal error, but keep the mempool consistent,
2510 // just in case. Only remove from the mempool in this case.
2511 MaybeUpdateMempoolForReorg(disconnectpool, false);
2512
2513 // If we're unable to disconnect a block during normal operation,
2514 // then that is a failure of our local system -- we should abort
2515 // rather than stay on a less work chain.
2516 AbortNode(state, "Failed to disconnect block; see debug.log for details");
2517 return false;
2518 }
2519 fBlocksDisconnected = true;
2520 }
2521
2522 // Build list of new blocks to connect (in descending height order).
2523 std::vector<CBlockIndex*> vpindexToConnect;
2524 bool fContinue = true;
2525 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2526 while (fContinue && nHeight != pindexMostWork->nHeight) {
2527 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2528 // a few blocks along the way.
2529 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2530 vpindexToConnect.clear();
2531 vpindexToConnect.reserve(nTargetHeight - nHeight);
2532 CBlockIndex* pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2533 while (pindexIter && pindexIter->nHeight != nHeight) {
2534 vpindexToConnect.push_back(pindexIter);
2535 pindexIter = pindexIter->pprev;
2536 }
2537 nHeight = nTargetHeight;
2538
2539 // Connect new blocks.
2540 for (CBlockIndex* pindexConnect : reverse_iterate(vpindexToConnect)) {
2541 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2542 if (state.IsInvalid()) {
2543 // The block violates a consensus rule.
2544 if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
2545 InvalidChainFound(vpindexToConnect.front());
2546 }
2547 state = BlockValidationState();
2548 fInvalidFound = true;
2549 fContinue = false;
2550 break;
2551 } else {
2552 // A system error occurred (disk space, database error, ...).
2553 // Make the mempool consistent with the current tip, just in case
2554 // any observers try to use it before shutdown.
2555 MaybeUpdateMempoolForReorg(disconnectpool, false);
2556 return false;
2557 }
2558 } else {
2559 PruneBlockIndexCandidates();
2560 if (!pindexOldTip || m_chain.Tip()->nChainWork > pindexOldTip->nChainWork) {
2561 // We're in a better position than we were. Return temporarily to release the lock.
2562 fContinue = false;
2563 break;
2564 }
2565 }
2566 }
2567 }
2568
2569 if (fBlocksDisconnected) {
2570 // If any blocks were disconnected, disconnectpool may be non empty. Add
2571 // any disconnected transactions back to the mempool.
2572 MaybeUpdateMempoolForReorg(disconnectpool, true);
2573 }
2574 if (m_mempool) m_mempool->check(*this);
2575
2576 CheckForkWarningConditions();
2577
2578 return true;
2579 }
2580
GetSynchronizationState(bool init)2581 static SynchronizationState GetSynchronizationState(bool init)
2582 {
2583 if (!init) return SynchronizationState::POST_INIT;
2584 if (::fReindex) return SynchronizationState::INIT_REINDEX;
2585 return SynchronizationState::INIT_DOWNLOAD;
2586 }
2587
NotifyHeaderTip(CChainState & chainstate)2588 static bool NotifyHeaderTip(CChainState& chainstate) LOCKS_EXCLUDED(cs_main) {
2589 bool fNotify = false;
2590 bool fInitialBlockDownload = false;
2591 static CBlockIndex* pindexHeaderOld = nullptr;
2592 CBlockIndex* pindexHeader = nullptr;
2593 {
2594 LOCK(cs_main);
2595 pindexHeader = pindexBestHeader;
2596
2597 if (pindexHeader != pindexHeaderOld) {
2598 fNotify = true;
2599 fInitialBlockDownload = chainstate.IsInitialBlockDownload();
2600 pindexHeaderOld = pindexHeader;
2601 }
2602 }
2603 // Send block tip changed notifications without cs_main
2604 if (fNotify) {
2605 uiInterface.NotifyHeaderTip(GetSynchronizationState(fInitialBlockDownload), pindexHeader);
2606 }
2607 return fNotify;
2608 }
2609
LimitValidationInterfaceQueue()2610 static void LimitValidationInterfaceQueue() LOCKS_EXCLUDED(cs_main) {
2611 AssertLockNotHeld(cs_main);
2612
2613 if (GetMainSignals().CallbacksPending() > 10) {
2614 SyncWithValidationInterfaceQueue();
2615 }
2616 }
2617
ActivateBestChain(BlockValidationState & state,std::shared_ptr<const CBlock> pblock)2618 bool CChainState::ActivateBestChain(BlockValidationState& state, std::shared_ptr<const CBlock> pblock)
2619 {
2620 // Note that while we're often called here from ProcessNewBlock, this is
2621 // far from a guarantee. Things in the P2P/RPC will often end up calling
2622 // us in the middle of ProcessNewBlock - do not assume pblock is set
2623 // sanely for performance or correctness!
2624 AssertLockNotHeld(cs_main);
2625
2626 // ABC maintains a fair degree of expensive-to-calculate internal state
2627 // because this function periodically releases cs_main so that it does not lock up other threads for too long
2628 // during large connects - and to allow for e.g. the callback queue to drain
2629 // we use m_cs_chainstate to enforce mutual exclusion so that only one caller may execute this function at a time
2630 LOCK(m_cs_chainstate);
2631
2632 CBlockIndex *pindexMostWork = nullptr;
2633 CBlockIndex *pindexNewTip = nullptr;
2634 int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2635 do {
2636 // Block until the validation queue drains. This should largely
2637 // never happen in normal operation, however may happen during
2638 // reindex, causing memory blowup if we run too far ahead.
2639 // Note that if a validationinterface callback ends up calling
2640 // ActivateBestChain this may lead to a deadlock! We should
2641 // probably have a DEBUG_LOCKORDER test for this in the future.
2642 LimitValidationInterfaceQueue();
2643
2644 {
2645 LOCK(cs_main);
2646 // Lock transaction pool for at least as long as it takes for connectTrace to be consumed
2647 LOCK(MempoolMutex());
2648 CBlockIndex* starting_tip = m_chain.Tip();
2649 bool blocks_connected = false;
2650 do {
2651 // We absolutely may not unlock cs_main until we've made forward progress
2652 // (with the exception of shutdown due to hardware issues, low disk space, etc).
2653 ConnectTrace connectTrace; // Destructed before cs_main is unlocked
2654
2655 if (pindexMostWork == nullptr) {
2656 pindexMostWork = FindMostWorkChain();
2657 }
2658
2659 // Whether we have anything to do at all.
2660 if (pindexMostWork == nullptr || pindexMostWork == m_chain.Tip()) {
2661 break;
2662 }
2663
2664 bool fInvalidFound = false;
2665 std::shared_ptr<const CBlock> nullBlockPtr;
2666 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace)) {
2667 // A system error occurred
2668 return false;
2669 }
2670 blocks_connected = true;
2671
2672 if (fInvalidFound) {
2673 // Wipe cache, we may need another branch now.
2674 pindexMostWork = nullptr;
2675 }
2676 pindexNewTip = m_chain.Tip();
2677
2678 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2679 assert(trace.pblock && trace.pindex);
2680 GetMainSignals().BlockConnected(trace.pblock, trace.pindex);
2681 }
2682 } while (!m_chain.Tip() || (starting_tip && CBlockIndexWorkComparator()(m_chain.Tip(), starting_tip)));
2683 if (!blocks_connected) return true;
2684
2685 const CBlockIndex* pindexFork = m_chain.FindFork(starting_tip);
2686 bool fInitialDownload = IsInitialBlockDownload();
2687
2688 // Notify external listeners about the new tip.
2689 // Enqueue while holding cs_main to ensure that UpdatedBlockTip is called in the order in which blocks are connected
2690 if (pindexFork != pindexNewTip) {
2691 // Notify ValidationInterface subscribers
2692 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2693
2694 // Always notify the UI if a new block tip was connected
2695 uiInterface.NotifyBlockTip(GetSynchronizationState(fInitialDownload), pindexNewTip);
2696 }
2697 }
2698 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2699
2700 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2701
2702 // We check shutdown only after giving ActivateBestChainStep a chance to run once so that we
2703 // never shutdown before connecting the genesis block during LoadChainTip(). Previously this
2704 // caused an assert() failure during shutdown in such cases as the UTXO DB flushing checks
2705 // that the best block hash is non-null.
2706 if (ShutdownRequested()) break;
2707 } while (pindexNewTip != pindexMostWork);
2708 CheckBlockIndex();
2709
2710 // Write changes periodically to disk, after relay.
2711 if (!FlushStateToDisk(state, FlushStateMode::PERIODIC)) {
2712 return false;
2713 }
2714
2715 return true;
2716 }
2717
PreciousBlock(BlockValidationState & state,CBlockIndex * pindex)2718 bool CChainState::PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
2719 {
2720 {
2721 LOCK(cs_main);
2722 if (pindex->nChainWork < m_chain.Tip()->nChainWork) {
2723 // Nothing to do, this block is not at the tip.
2724 return true;
2725 }
2726 if (m_chain.Tip()->nChainWork > nLastPreciousChainwork) {
2727 // The chain has been extended since the last call, reset the counter.
2728 nBlockReverseSequenceId = -1;
2729 }
2730 nLastPreciousChainwork = m_chain.Tip()->nChainWork;
2731 setBlockIndexCandidates.erase(pindex);
2732 pindex->nSequenceId = nBlockReverseSequenceId;
2733 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2734 // We can't keep reducing the counter if somebody really wants to
2735 // call preciousblock 2**31-1 times on the same set of tips...
2736 nBlockReverseSequenceId--;
2737 }
2738 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->HaveTxsDownloaded()) {
2739 setBlockIndexCandidates.insert(pindex);
2740 PruneBlockIndexCandidates();
2741 }
2742 }
2743
2744 return ActivateBestChain(state, std::shared_ptr<const CBlock>());
2745 }
2746
InvalidateBlock(BlockValidationState & state,CBlockIndex * pindex)2747 bool CChainState::InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex)
2748 {
2749 // Genesis block can't be invalidated
2750 assert(pindex);
2751 if (pindex->nHeight == 0) return false;
2752
2753 CBlockIndex* to_mark_failed = pindex;
2754 bool pindex_was_in_chain = false;
2755 int disconnected = 0;
2756
2757 // We do not allow ActivateBestChain() to run while InvalidateBlock() is
2758 // running, as that could cause the tip to change while we disconnect
2759 // blocks.
2760 LOCK(m_cs_chainstate);
2761
2762 // We'll be acquiring and releasing cs_main below, to allow the validation
2763 // callbacks to run. However, we should keep the block index in a
2764 // consistent state as we disconnect blocks -- in particular we need to
2765 // add equal-work blocks to setBlockIndexCandidates as we disconnect.
2766 // To avoid walking the block index repeatedly in search of candidates,
2767 // build a map once so that we can look up candidate blocks by chain
2768 // work as we go.
2769 std::multimap<const arith_uint256, CBlockIndex *> candidate_blocks_by_work;
2770
2771 {
2772 LOCK(cs_main);
2773 for (const auto& entry : m_blockman.m_block_index) {
2774 CBlockIndex *candidate = entry.second;
2775 // We don't need to put anything in our active chain into the
2776 // multimap, because those candidates will be found and considered
2777 // as we disconnect.
2778 // Instead, consider only non-active-chain blocks that have at
2779 // least as much work as where we expect the new tip to end up.
2780 if (!m_chain.Contains(candidate) &&
2781 !CBlockIndexWorkComparator()(candidate, pindex->pprev) &&
2782 candidate->IsValid(BLOCK_VALID_TRANSACTIONS) &&
2783 candidate->HaveTxsDownloaded()) {
2784 candidate_blocks_by_work.insert(std::make_pair(candidate->nChainWork, candidate));
2785 }
2786 }
2787 }
2788
2789 // Disconnect (descendants of) pindex, and mark them invalid.
2790 while (true) {
2791 if (ShutdownRequested()) break;
2792
2793 // Make sure the queue of validation callbacks doesn't grow unboundedly.
2794 LimitValidationInterfaceQueue();
2795
2796 LOCK(cs_main);
2797 // Lock for as long as disconnectpool is in scope to make sure MaybeUpdateMempoolForReorg is
2798 // called after DisconnectTip without unlocking in between
2799 LOCK(MempoolMutex());
2800 if (!m_chain.Contains(pindex)) break;
2801 pindex_was_in_chain = true;
2802 CBlockIndex *invalid_walk_tip = m_chain.Tip();
2803
2804 // ActivateBestChain considers blocks already in m_chain
2805 // unconditionally valid already, so force disconnect away from it.
2806 DisconnectedBlockTransactions disconnectpool;
2807 bool ret = DisconnectTip(state, &disconnectpool);
2808 // DisconnectTip will add transactions to disconnectpool.
2809 // Adjust the mempool to be consistent with the new tip, adding
2810 // transactions back to the mempool if disconnecting was successful,
2811 // and we're not doing a very deep invalidation (in which case
2812 // keeping the mempool up to date is probably futile anyway).
2813 MaybeUpdateMempoolForReorg(disconnectpool, /* fAddToMempool = */ (++disconnected <= 10) && ret);
2814 if (!ret) return false;
2815 assert(invalid_walk_tip->pprev == m_chain.Tip());
2816
2817 // We immediately mark the disconnected blocks as invalid.
2818 // This prevents a case where pruned nodes may fail to invalidateblock
2819 // and be left unable to start as they have no tip candidates (as there
2820 // are no blocks that meet the "have data and are not invalid per
2821 // nStatus" criteria for inclusion in setBlockIndexCandidates).
2822 invalid_walk_tip->nStatus |= BLOCK_FAILED_VALID;
2823 setDirtyBlockIndex.insert(invalid_walk_tip);
2824 setBlockIndexCandidates.erase(invalid_walk_tip);
2825 setBlockIndexCandidates.insert(invalid_walk_tip->pprev);
2826 if (invalid_walk_tip->pprev == to_mark_failed && (to_mark_failed->nStatus & BLOCK_FAILED_VALID)) {
2827 // We only want to mark the last disconnected block as BLOCK_FAILED_VALID; its children
2828 // need to be BLOCK_FAILED_CHILD instead.
2829 to_mark_failed->nStatus = (to_mark_failed->nStatus ^ BLOCK_FAILED_VALID) | BLOCK_FAILED_CHILD;
2830 setDirtyBlockIndex.insert(to_mark_failed);
2831 }
2832
2833 // Add any equal or more work headers to setBlockIndexCandidates
2834 auto candidate_it = candidate_blocks_by_work.lower_bound(invalid_walk_tip->pprev->nChainWork);
2835 while (candidate_it != candidate_blocks_by_work.end()) {
2836 if (!CBlockIndexWorkComparator()(candidate_it->second, invalid_walk_tip->pprev)) {
2837 setBlockIndexCandidates.insert(candidate_it->second);
2838 candidate_it = candidate_blocks_by_work.erase(candidate_it);
2839 } else {
2840 ++candidate_it;
2841 }
2842 }
2843
2844 // Track the last disconnected block, so we can correct its BLOCK_FAILED_CHILD status in future
2845 // iterations, or, if it's the last one, call InvalidChainFound on it.
2846 to_mark_failed = invalid_walk_tip;
2847 }
2848
2849 CheckBlockIndex();
2850
2851 {
2852 LOCK(cs_main);
2853 if (m_chain.Contains(to_mark_failed)) {
2854 // If the to-be-marked invalid block is in the active chain, something is interfering and we can't proceed.
2855 return false;
2856 }
2857
2858 // Mark pindex (or the last disconnected block) as invalid, even when it never was in the main chain
2859 to_mark_failed->nStatus |= BLOCK_FAILED_VALID;
2860 setDirtyBlockIndex.insert(to_mark_failed);
2861 setBlockIndexCandidates.erase(to_mark_failed);
2862 m_blockman.m_failed_blocks.insert(to_mark_failed);
2863
2864 // If any new blocks somehow arrived while we were disconnecting
2865 // (above), then the pre-calculation of what should go into
2866 // setBlockIndexCandidates may have missed entries. This would
2867 // technically be an inconsistency in the block index, but if we clean
2868 // it up here, this should be an essentially unobservable error.
2869 // Loop back over all block index entries and add any missing entries
2870 // to setBlockIndexCandidates.
2871 BlockMap::iterator it = m_blockman.m_block_index.begin();
2872 while (it != m_blockman.m_block_index.end()) {
2873 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && !setBlockIndexCandidates.value_comp()(it->second, m_chain.Tip())) {
2874 setBlockIndexCandidates.insert(it->second);
2875 }
2876 it++;
2877 }
2878
2879 InvalidChainFound(to_mark_failed);
2880 }
2881
2882 // Only notify about a new block tip if the active chain was modified.
2883 if (pindex_was_in_chain) {
2884 uiInterface.NotifyBlockTip(GetSynchronizationState(IsInitialBlockDownload()), to_mark_failed->pprev);
2885 }
2886 return true;
2887 }
2888
ResetBlockFailureFlags(CBlockIndex * pindex)2889 void CChainState::ResetBlockFailureFlags(CBlockIndex *pindex) {
2890 AssertLockHeld(cs_main);
2891
2892 int nHeight = pindex->nHeight;
2893
2894 // Remove the invalidity flag from this block and all its descendants.
2895 BlockMap::iterator it = m_blockman.m_block_index.begin();
2896 while (it != m_blockman.m_block_index.end()) {
2897 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2898 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2899 setDirtyBlockIndex.insert(it->second);
2900 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && setBlockIndexCandidates.value_comp()(m_chain.Tip(), it->second)) {
2901 setBlockIndexCandidates.insert(it->second);
2902 }
2903 if (it->second == pindexBestInvalid) {
2904 // Reset invalid block marker if it was pointing to one of those.
2905 pindexBestInvalid = nullptr;
2906 }
2907 m_blockman.m_failed_blocks.erase(it->second);
2908 }
2909 it++;
2910 }
2911
2912 // Remove the invalidity flag from all ancestors too.
2913 while (pindex != nullptr) {
2914 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2915 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2916 setDirtyBlockIndex.insert(pindex);
2917 m_blockman.m_failed_blocks.erase(pindex);
2918 }
2919 pindex = pindex->pprev;
2920 }
2921 }
2922
AddToBlockIndex(const CBlockHeader & block)2923 CBlockIndex* BlockManager::AddToBlockIndex(const CBlockHeader& block)
2924 {
2925 AssertLockHeld(cs_main);
2926
2927 // Check for duplicate
2928 uint256 hash = block.GetHash();
2929 BlockMap::iterator it = m_block_index.find(hash);
2930 if (it != m_block_index.end())
2931 return it->second;
2932
2933 // Construct new block index object
2934 CBlockIndex* pindexNew = new CBlockIndex(block);
2935 // We assign the sequence id to blocks only when the full data is available,
2936 // to avoid miners withholding blocks but broadcasting headers, to get a
2937 // competitive advantage.
2938 pindexNew->nSequenceId = 0;
2939 BlockMap::iterator mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
2940 pindexNew->phashBlock = &((*mi).first);
2941 BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
2942 if (miPrev != m_block_index.end())
2943 {
2944 pindexNew->pprev = (*miPrev).second;
2945 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2946 pindexNew->BuildSkip();
2947 }
2948 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2949 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2950 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2951 if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2952 pindexBestHeader = pindexNew;
2953
2954 setDirtyBlockIndex.insert(pindexNew);
2955
2956 return pindexNew;
2957 }
2958
2959 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
ReceivedBlockTransactions(const CBlock & block,CBlockIndex * pindexNew,const FlatFilePos & pos)2960 void CChainState::ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos)
2961 {
2962 pindexNew->nTx = block.vtx.size();
2963 pindexNew->nChainTx = 0;
2964 pindexNew->nFile = pos.nFile;
2965 pindexNew->nDataPos = pos.nPos;
2966 pindexNew->nUndoPos = 0;
2967 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2968 if (DeploymentActiveAt(*pindexNew, m_params.GetConsensus(), Consensus::DEPLOYMENT_SEGWIT)) {
2969 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2970 }
2971 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2972 setDirtyBlockIndex.insert(pindexNew);
2973
2974 if (pindexNew->pprev == nullptr || pindexNew->pprev->HaveTxsDownloaded()) {
2975 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2976 std::deque<CBlockIndex*> queue;
2977 queue.push_back(pindexNew);
2978
2979 // Recursively process any descendant blocks that now may be eligible to be connected.
2980 while (!queue.empty()) {
2981 CBlockIndex *pindex = queue.front();
2982 queue.pop_front();
2983 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2984 {
2985 LOCK(cs_nBlockSequenceId);
2986 pindex->nSequenceId = nBlockSequenceId++;
2987 }
2988 if (m_chain.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) {
2989 setBlockIndexCandidates.insert(pindex);
2990 }
2991 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = m_blockman.m_blocks_unlinked.equal_range(pindex);
2992 while (range.first != range.second) {
2993 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2994 queue.push_back(it->second);
2995 range.first++;
2996 m_blockman.m_blocks_unlinked.erase(it);
2997 }
2998 }
2999 } else {
3000 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3001 m_blockman.m_blocks_unlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3002 }
3003 }
3004 }
3005
CheckBlockHeader(const CBlockHeader & block,BlockValidationState & state,const Consensus::Params & consensusParams,bool fCheckPOW=true)3006 static bool CheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
3007 {
3008 // Check proof of work matches claimed amount
3009 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
3010 return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "high-hash", "proof of work failed");
3011
3012 return true;
3013 }
3014
CheckBlock(const CBlock & block,BlockValidationState & state,const Consensus::Params & consensusParams,bool fCheckPOW,bool fCheckMerkleRoot)3015 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
3016 {
3017 // These are checks that are independent of context.
3018
3019 if (block.fChecked)
3020 return true;
3021
3022 // Check that the header is valid (particularly PoW). This is mostly
3023 // redundant with the call in AcceptBlockHeader.
3024 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
3025 return false;
3026
3027 // Signet only: check block solution
3028 if (consensusParams.signet_blocks && fCheckPOW && !CheckSignetBlockSolution(block, consensusParams)) {
3029 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-signet-blksig", "signet block signature validation failure");
3030 }
3031
3032 // Check the merkle root.
3033 if (fCheckMerkleRoot) {
3034 bool mutated;
3035 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
3036 if (block.hashMerkleRoot != hashMerkleRoot2)
3037 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txnmrklroot", "hashMerkleRoot mismatch");
3038
3039 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3040 // of transactions in a block without affecting the merkle root of a block,
3041 // while still invalidating it.
3042 if (mutated)
3043 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txns-duplicate", "duplicate transaction");
3044 }
3045
3046 // All potential-corruption validation must be done before we do any
3047 // transaction validation, as otherwise we may mark the header as invalid
3048 // because we receive the wrong transactions for it.
3049 // Note that witness malleability is checked in ContextualCheckBlock, so no
3050 // checks that use witness data may be performed here.
3051
3052 // Size limits
3053 if (block.vtx.empty() || block.vtx.size() * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT || ::GetSerializeSize(block, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)
3054 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-length", "size limits failed");
3055
3056 // First transaction must be coinbase, the rest must not be
3057 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
3058 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-missing", "first tx is not coinbase");
3059 for (unsigned int i = 1; i < block.vtx.size(); i++)
3060 if (block.vtx[i]->IsCoinBase())
3061 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple", "more than one coinbase");
3062
3063 // Check transactions
3064 // Must check for duplicate inputs (see CVE-2018-17144)
3065 for (const auto& tx : block.vtx) {
3066 TxValidationState tx_state;
3067 if (!CheckTransaction(*tx, tx_state)) {
3068 // CheckBlock() does context-free validation checks. The only
3069 // possible failures are consensus failures.
3070 assert(tx_state.GetResult() == TxValidationResult::TX_CONSENSUS);
3071 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, tx_state.GetRejectReason(),
3072 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), tx_state.GetDebugMessage()));
3073 }
3074 }
3075 unsigned int nSigOps = 0;
3076 for (const auto& tx : block.vtx)
3077 {
3078 nSigOps += GetLegacySigOpCount(*tx);
3079 }
3080 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
3081 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "out-of-bounds SigOpCount");
3082
3083 if (fCheckPOW && fCheckMerkleRoot)
3084 block.fChecked = true;
3085
3086 return true;
3087 }
3088
UpdateUncommittedBlockStructures(CBlock & block,const CBlockIndex * pindexPrev,const Consensus::Params & consensusParams)3089 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
3090 {
3091 int commitpos = GetWitnessCommitmentIndex(block);
3092 static const std::vector<unsigned char> nonce(32, 0x00);
3093 if (commitpos != NO_WITNESS_COMMITMENT && DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT) && !block.vtx[0]->HasWitness()) {
3094 CMutableTransaction tx(*block.vtx[0]);
3095 tx.vin[0].scriptWitness.stack.resize(1);
3096 tx.vin[0].scriptWitness.stack[0] = nonce;
3097 block.vtx[0] = MakeTransactionRef(std::move(tx));
3098 }
3099 }
3100
GenerateCoinbaseCommitment(CBlock & block,const CBlockIndex * pindexPrev,const Consensus::Params & consensusParams)3101 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
3102 {
3103 std::vector<unsigned char> commitment;
3104 int commitpos = GetWitnessCommitmentIndex(block);
3105 std::vector<unsigned char> ret(32, 0x00);
3106 if (DeploymentEnabled(consensusParams, Consensus::DEPLOYMENT_SEGWIT)) {
3107 if (commitpos == NO_WITNESS_COMMITMENT) {
3108 uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
3109 CHash256().Write(witnessroot).Write(ret).Finalize(witnessroot);
3110 CTxOut out;
3111 out.nValue = 0;
3112 out.scriptPubKey.resize(MINIMUM_WITNESS_COMMITMENT);
3113 out.scriptPubKey[0] = OP_RETURN;
3114 out.scriptPubKey[1] = 0x24;
3115 out.scriptPubKey[2] = 0xaa;
3116 out.scriptPubKey[3] = 0x21;
3117 out.scriptPubKey[4] = 0xa9;
3118 out.scriptPubKey[5] = 0xed;
3119 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
3120 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
3121 CMutableTransaction tx(*block.vtx[0]);
3122 tx.vout.push_back(out);
3123 block.vtx[0] = MakeTransactionRef(std::move(tx));
3124 }
3125 }
3126 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
3127 return commitment;
3128 }
3129
GetLastCheckpoint(const CCheckpointData & data)3130 CBlockIndex* BlockManager::GetLastCheckpoint(const CCheckpointData& data)
3131 {
3132 const MapCheckpoints& checkpoints = data.mapCheckpoints;
3133
3134 for (const MapCheckpoints::value_type& i : reverse_iterate(checkpoints))
3135 {
3136 const uint256& hash = i.second;
3137 CBlockIndex* pindex = LookupBlockIndex(hash);
3138 if (pindex) {
3139 return pindex;
3140 }
3141 }
3142 return nullptr;
3143 }
3144
3145 /** Context-dependent validity checks.
3146 * By "context", we mean only the previous block headers, but not the UTXO
3147 * set; UTXO-related validity checks are done in ConnectBlock().
3148 * NOTE: This function is not currently invoked by ConnectBlock(), so we
3149 * should consider upgrade issues if we change which consensus rules are
3150 * enforced in this function (eg by adding a new consensus rule). See comment
3151 * in ConnectBlock().
3152 * Note that -reindex-chainstate skips the validation that happens here!
3153 */
ContextualCheckBlockHeader(const CBlockHeader & block,BlockValidationState & state,BlockManager & blockman,const CChainParams & params,const CBlockIndex * pindexPrev,int64_t nAdjustedTime)3154 static bool ContextualCheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, BlockManager& blockman, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
3155 {
3156 assert(pindexPrev != nullptr);
3157 const int nHeight = pindexPrev->nHeight + 1;
3158
3159 // Check proof of work
3160 const Consensus::Params& consensusParams = params.GetConsensus();
3161 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3162 return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits", "incorrect proof of work");
3163
3164 // Check against checkpoints
3165 if (fCheckpointsEnabled) {
3166 // Don't accept any forks from the main chain prior to last checkpoint.
3167 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
3168 // BlockIndex().
3169 CBlockIndex* pcheckpoint = blockman.GetLastCheckpoint(params.Checkpoints());
3170 if (pcheckpoint && nHeight < pcheckpoint->nHeight) {
3171 LogPrintf("ERROR: %s: forked chain older than last checkpoint (height %d)\n", __func__, nHeight);
3172 return state.Invalid(BlockValidationResult::BLOCK_CHECKPOINT, "bad-fork-prior-to-checkpoint");
3173 }
3174 }
3175
3176 // Check timestamp against prev
3177 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3178 return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-too-old", "block's timestamp is too early");
3179
3180 // Check timestamp
3181 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
3182 return state.Invalid(BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new", "block timestamp too far in the future");
3183
3184 // Reject blocks with outdated version
3185 if ((block.nVersion < 2 && DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_HEIGHTINCB)) ||
3186 (block.nVersion < 3 && DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_DERSIG)) ||
3187 (block.nVersion < 4 && DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CLTV))) {
3188 return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, strprintf("bad-version(0x%08x)", block.nVersion),
3189 strprintf("rejected nVersion=0x%08x block", block.nVersion));
3190 }
3191
3192 return true;
3193 }
3194
3195 /** NOTE: This function is not currently invoked by ConnectBlock(), so we
3196 * should consider upgrade issues if we change which consensus rules are
3197 * enforced in this function (eg by adding a new consensus rule). See comment
3198 * in ConnectBlock().
3199 * Note that -reindex-chainstate skips the validation that happens here!
3200 */
ContextualCheckBlock(const CBlock & block,BlockValidationState & state,const Consensus::Params & consensusParams,const CBlockIndex * pindexPrev)3201 static bool ContextualCheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
3202 {
3203 const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
3204
3205 // Enforce BIP113 (Median Time Past).
3206 int nLockTimeFlags = 0;
3207 if (DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV)) {
3208 assert(pindexPrev != nullptr);
3209 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
3210 }
3211
3212 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3213 ? pindexPrev->GetMedianTimePast()
3214 : block.GetBlockTime();
3215
3216 // Check that all transactions are finalized
3217 for (const auto& tx : block.vtx) {
3218 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
3219 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal", "non-final transaction");
3220 }
3221 }
3222
3223 // Enforce rule that the coinbase starts with serialized block height
3224 if (DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_HEIGHTINCB))
3225 {
3226 CScript expect = CScript() << nHeight;
3227 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
3228 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
3229 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-height", "block height mismatch in coinbase");
3230 }
3231 }
3232
3233 // Validation for witness commitments.
3234 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
3235 // coinbase (where 0x0000....0000 is used instead).
3236 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness reserved value (unconstrained).
3237 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
3238 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
3239 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness reserved value). In case there are
3240 // multiple, the last one is used.
3241 bool fHaveWitness = false;
3242 if (DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT)) {
3243 int commitpos = GetWitnessCommitmentIndex(block);
3244 if (commitpos != NO_WITNESS_COMMITMENT) {
3245 bool malleated = false;
3246 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
3247 // The malleation check is ignored; as the transaction tree itself
3248 // already does not permit it, it is impossible to trigger in the
3249 // witness tree.
3250 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3251 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-nonce-size", strprintf("%s : invalid witness reserved value size", __func__));
3252 }
3253 CHash256().Write(hashWitness).Write(block.vtx[0]->vin[0].scriptWitness.stack[0]).Finalize(hashWitness);
3254 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3255 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-merkle-match", strprintf("%s : witness merkle commitment mismatch", __func__));
3256 }
3257 fHaveWitness = true;
3258 }
3259 }
3260
3261 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3262 if (!fHaveWitness) {
3263 for (const auto& tx : block.vtx) {
3264 if (tx->HasWitness()) {
3265 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "unexpected-witness", strprintf("%s : unexpected witness data found", __func__));
3266 }
3267 }
3268 }
3269
3270 // After the coinbase witness reserved value and commitment are verified,
3271 // we can check if the block weight passes (before we've checked the
3272 // coinbase witness, it would be possible for the weight to be too
3273 // large by filling up the coinbase witness, which doesn't change
3274 // the block hash, so we couldn't mark the block as permanently
3275 // failed).
3276 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3277 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-weight", strprintf("%s : weight limit failed", __func__));
3278 }
3279
3280 return true;
3281 }
3282
AcceptBlockHeader(const CBlockHeader & block,BlockValidationState & state,const CChainParams & chainparams,CBlockIndex ** ppindex)3283 bool BlockManager::AcceptBlockHeader(const CBlockHeader& block, BlockValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3284 {
3285 AssertLockHeld(cs_main);
3286 // Check for duplicate
3287 uint256 hash = block.GetHash();
3288 BlockMap::iterator miSelf = m_block_index.find(hash);
3289 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3290 if (miSelf != m_block_index.end()) {
3291 // Block header is already known.
3292 CBlockIndex* pindex = miSelf->second;
3293 if (ppindex)
3294 *ppindex = pindex;
3295 if (pindex->nStatus & BLOCK_FAILED_MASK) {
3296 LogPrintf("ERROR: %s: block %s is marked invalid\n", __func__, hash.ToString());
3297 return state.Invalid(BlockValidationResult::BLOCK_CACHED_INVALID, "duplicate");
3298 }
3299 return true;
3300 }
3301
3302 if (!CheckBlockHeader(block, state, chainparams.GetConsensus())) {
3303 LogPrint(BCLog::VALIDATION, "%s: Consensus::CheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
3304 return false;
3305 }
3306
3307 // Get prev block index
3308 CBlockIndex* pindexPrev = nullptr;
3309 BlockMap::iterator mi = m_block_index.find(block.hashPrevBlock);
3310 if (mi == m_block_index.end()) {
3311 LogPrintf("ERROR: %s: prev block not found\n", __func__);
3312 return state.Invalid(BlockValidationResult::BLOCK_MISSING_PREV, "prev-blk-not-found");
3313 }
3314 pindexPrev = (*mi).second;
3315 if (pindexPrev->nStatus & BLOCK_FAILED_MASK) {
3316 LogPrintf("ERROR: %s: prev block invalid\n", __func__);
3317 return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
3318 }
3319 if (!ContextualCheckBlockHeader(block, state, *this, chainparams, pindexPrev, GetAdjustedTime()))
3320 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), state.ToString());
3321
3322 /* Determine if this block descends from any block which has been found
3323 * invalid (m_failed_blocks), then mark pindexPrev and any blocks between
3324 * them as failed. For example:
3325 *
3326 * D3
3327 * /
3328 * B2 - C2
3329 * / \
3330 * A D2 - E2 - F2
3331 * \
3332 * B1 - C1 - D1 - E1
3333 *
3334 * In the case that we attempted to reorg from E1 to F2, only to find
3335 * C2 to be invalid, we would mark D2, E2, and F2 as BLOCK_FAILED_CHILD
3336 * but NOT D3 (it was not in any of our candidate sets at the time).
3337 *
3338 * In any case D3 will also be marked as BLOCK_FAILED_CHILD at restart
3339 * in LoadBlockIndex.
3340 */
3341 if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
3342 // The above does not mean "invalid": it checks if the previous block
3343 // hasn't been validated up to BLOCK_VALID_SCRIPTS. This is a performance
3344 // optimization, in the common case of adding a new block to the tip,
3345 // we don't need to iterate over the failed blocks list.
3346 for (const CBlockIndex* failedit : m_failed_blocks) {
3347 if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
3348 assert(failedit->nStatus & BLOCK_FAILED_VALID);
3349 CBlockIndex* invalid_walk = pindexPrev;
3350 while (invalid_walk != failedit) {
3351 invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
3352 setDirtyBlockIndex.insert(invalid_walk);
3353 invalid_walk = invalid_walk->pprev;
3354 }
3355 LogPrintf("ERROR: %s: prev block invalid\n", __func__);
3356 return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
3357 }
3358 }
3359 }
3360 }
3361 CBlockIndex* pindex = AddToBlockIndex(block);
3362
3363 if (ppindex)
3364 *ppindex = pindex;
3365
3366 return true;
3367 }
3368
3369 // Exposed wrapper for AcceptBlockHeader
ProcessNewBlockHeaders(const std::vector<CBlockHeader> & headers,BlockValidationState & state,const CChainParams & chainparams,const CBlockIndex ** ppindex)3370 bool ChainstateManager::ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, BlockValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
3371 {
3372 AssertLockNotHeld(cs_main);
3373 {
3374 LOCK(cs_main);
3375 for (const CBlockHeader& header : headers) {
3376 CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3377 bool accepted = m_blockman.AcceptBlockHeader(
3378 header, state, chainparams, &pindex);
3379 ActiveChainstate().CheckBlockIndex();
3380
3381 if (!accepted) {
3382 return false;
3383 }
3384 if (ppindex) {
3385 *ppindex = pindex;
3386 }
3387 }
3388 }
3389 if (NotifyHeaderTip(ActiveChainstate())) {
3390 if (ActiveChainstate().IsInitialBlockDownload() && ppindex && *ppindex) {
3391 LogPrintf("Synchronizing blockheaders, height: %d (~%.2f%%)\n", (*ppindex)->nHeight, 100.0/((*ppindex)->nHeight+(GetAdjustedTime() - (*ppindex)->GetBlockTime()) / Params().GetConsensus().nPowTargetSpacing) * (*ppindex)->nHeight);
3392 }
3393 }
3394 return true;
3395 }
3396
3397 /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
AcceptBlock(const std::shared_ptr<const CBlock> & pblock,BlockValidationState & state,CBlockIndex ** ppindex,bool fRequested,const FlatFilePos * dbp,bool * fNewBlock)3398 bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock)
3399 {
3400 const CBlock& block = *pblock;
3401
3402 if (fNewBlock) *fNewBlock = false;
3403 AssertLockHeld(cs_main);
3404
3405 CBlockIndex *pindexDummy = nullptr;
3406 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3407
3408 bool accepted_header = m_blockman.AcceptBlockHeader(block, state, m_params, &pindex);
3409 CheckBlockIndex();
3410
3411 if (!accepted_header)
3412 return false;
3413
3414 // Try to process all requested blocks that we don't have, but only
3415 // process an unrequested block if it's new and has enough work to
3416 // advance our tip, and isn't too many blocks ahead.
3417 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3418 bool fHasMoreOrSameWork = (m_chain.Tip() ? pindex->nChainWork >= m_chain.Tip()->nChainWork : true);
3419 // Blocks that are too out-of-order needlessly limit the effectiveness of
3420 // pruning, because pruning will not delete block files that contain any
3421 // blocks which are too close in height to the tip. Apply this test
3422 // regardless of whether pruning is enabled; it should generally be safe to
3423 // not process unrequested blocks.
3424 bool fTooFarAhead = (pindex->nHeight > int(m_chain.Height() + MIN_BLOCKS_TO_KEEP));
3425
3426 // TODO: Decouple this function from the block download logic by removing fRequested
3427 // This requires some new chain data structure to efficiently look up if a
3428 // block is in a chain leading to a candidate for best tip, despite not
3429 // being such a candidate itself.
3430
3431 // TODO: deal better with return value and error conditions for duplicate
3432 // and unrequested blocks.
3433 if (fAlreadyHave) return true;
3434 if (!fRequested) { // If we didn't ask for it:
3435 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3436 if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
3437 if (fTooFarAhead) return true; // Block height is too high
3438
3439 // Protect against DoS attacks from low-work chains.
3440 // If our tip is behind, a peer could try to send us
3441 // low-work blocks on a fake chain that we would never
3442 // request; don't process these.
3443 if (pindex->nChainWork < nMinimumChainWork) return true;
3444 }
3445
3446 if (!CheckBlock(block, state, m_params.GetConsensus()) ||
3447 !ContextualCheckBlock(block, state, m_params.GetConsensus(), pindex->pprev)) {
3448 if (state.IsInvalid() && state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
3449 pindex->nStatus |= BLOCK_FAILED_VALID;
3450 setDirtyBlockIndex.insert(pindex);
3451 }
3452 return error("%s: %s", __func__, state.ToString());
3453 }
3454
3455 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3456 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3457 if (!IsInitialBlockDownload() && m_chain.Tip() == pindex->pprev)
3458 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3459
3460 // Write block to history file
3461 if (fNewBlock) *fNewBlock = true;
3462 try {
3463 FlatFilePos blockPos = SaveBlockToDisk(block, pindex->nHeight, m_chain, m_params, dbp);
3464 if (blockPos.IsNull()) {
3465 state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
3466 return false;
3467 }
3468 ReceivedBlockTransactions(block, pindex, blockPos);
3469 } catch (const std::runtime_error& e) {
3470 return AbortNode(state, std::string("System error: ") + e.what());
3471 }
3472
3473 FlushStateToDisk(state, FlushStateMode::NONE);
3474
3475 CheckBlockIndex();
3476
3477 return true;
3478 }
3479
ProcessNewBlock(const CChainParams & chainparams,const std::shared_ptr<const CBlock> & block,bool force_processing,bool * new_block)3480 bool ChainstateManager::ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock>& block, bool force_processing, bool* new_block)
3481 {
3482 AssertLockNotHeld(cs_main);
3483
3484 {
3485 CBlockIndex *pindex = nullptr;
3486 if (new_block) *new_block = false;
3487 BlockValidationState state;
3488
3489 // CheckBlock() does not support multi-threaded block validation because CBlock::fChecked can cause data race.
3490 // Therefore, the following critical section must include the CheckBlock() call as well.
3491 LOCK(cs_main);
3492
3493 // Skipping AcceptBlock() for CheckBlock() failures means that we will never mark a block as invalid if
3494 // CheckBlock() fails. This is protective against consensus failure if there are any unknown forms of block
3495 // malleability that cause CheckBlock() to fail; see e.g. CVE-2012-2459 and
3496 // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-February/016697.html. Because CheckBlock() is
3497 // not very expensive, the anti-DoS benefits of caching failure (of a definitely-invalid block) are not substantial.
3498 bool ret = CheckBlock(*block, state, chainparams.GetConsensus());
3499 if (ret) {
3500 // Store to disk
3501 ret = ActiveChainstate().AcceptBlock(block, state, &pindex, force_processing, nullptr, new_block);
3502 }
3503 if (!ret) {
3504 GetMainSignals().BlockChecked(*block, state);
3505 return error("%s: AcceptBlock FAILED (%s)", __func__, state.ToString());
3506 }
3507 }
3508
3509 NotifyHeaderTip(ActiveChainstate());
3510
3511 BlockValidationState state; // Only used to report errors, not invalidity - ignore it
3512 if (!ActiveChainstate().ActivateBestChain(state, block)) {
3513 return error("%s: ActivateBestChain failed (%s)", __func__, state.ToString());
3514 }
3515
3516 return true;
3517 }
3518
TestBlockValidity(BlockValidationState & state,const CChainParams & chainparams,CChainState & chainstate,const CBlock & block,CBlockIndex * pindexPrev,bool fCheckPOW,bool fCheckMerkleRoot)3519 bool TestBlockValidity(BlockValidationState& state,
3520 const CChainParams& chainparams,
3521 CChainState& chainstate,
3522 const CBlock& block,
3523 CBlockIndex* pindexPrev,
3524 bool fCheckPOW,
3525 bool fCheckMerkleRoot)
3526 {
3527 AssertLockHeld(cs_main);
3528 assert(pindexPrev && pindexPrev == chainstate.m_chain.Tip());
3529 CCoinsViewCache viewNew(&chainstate.CoinsTip());
3530 uint256 block_hash(block.GetHash());
3531 CBlockIndex indexDummy(block);
3532 indexDummy.pprev = pindexPrev;
3533 indexDummy.nHeight = pindexPrev->nHeight + 1;
3534 indexDummy.phashBlock = &block_hash;
3535
3536 // NOTE: CheckBlockHeader is called by CheckBlock
3537 if (!ContextualCheckBlockHeader(block, state, chainstate.m_blockman, chainparams, pindexPrev, GetAdjustedTime()))
3538 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, state.ToString());
3539 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3540 return error("%s: Consensus::CheckBlock: %s", __func__, state.ToString());
3541 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3542 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, state.ToString());
3543 if (!chainstate.ConnectBlock(block, state, &indexDummy, viewNew, true)) {
3544 return false;
3545 }
3546 assert(state.IsValid());
3547
3548 return true;
3549 }
3550
3551 /**
3552 * BLOCK PRUNING CODE
3553 */
3554
PruneOneBlockFile(const int fileNumber)3555 void BlockManager::PruneOneBlockFile(const int fileNumber)
3556 {
3557 AssertLockHeld(cs_main);
3558 LOCK(cs_LastBlockFile);
3559
3560 for (const auto& entry : m_block_index) {
3561 CBlockIndex* pindex = entry.second;
3562 if (pindex->nFile == fileNumber) {
3563 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3564 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3565 pindex->nFile = 0;
3566 pindex->nDataPos = 0;
3567 pindex->nUndoPos = 0;
3568 setDirtyBlockIndex.insert(pindex);
3569
3570 // Prune from m_blocks_unlinked -- any block we prune would have
3571 // to be downloaded again in order to consider its chain, at which
3572 // point it would be considered as a candidate for
3573 // m_blocks_unlinked or setBlockIndexCandidates.
3574 auto range = m_blocks_unlinked.equal_range(pindex->pprev);
3575 while (range.first != range.second) {
3576 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3577 range.first++;
3578 if (_it->second == pindex) {
3579 m_blocks_unlinked.erase(_it);
3580 }
3581 }
3582 }
3583 }
3584
3585 vinfoBlockFile[fileNumber].SetNull();
3586 setDirtyFileInfo.insert(fileNumber);
3587 }
3588
FindFilesToPruneManual(std::set<int> & setFilesToPrune,int nManualPruneHeight,int chain_tip_height)3589 void BlockManager::FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
3590 {
3591 assert(fPruneMode && nManualPruneHeight > 0);
3592
3593 LOCK2(cs_main, cs_LastBlockFile);
3594 if (chain_tip_height < 0) {
3595 return;
3596 }
3597
3598 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3599 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chain_tip_height - MIN_BLOCKS_TO_KEEP);
3600 int count = 0;
3601 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3602 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) {
3603 continue;
3604 }
3605 PruneOneBlockFile(fileNumber);
3606 setFilesToPrune.insert(fileNumber);
3607 count++;
3608 }
3609 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3610 }
3611
3612 /* This function is called from the RPC code for pruneblockchain */
PruneBlockFilesManual(CChainState & active_chainstate,int nManualPruneHeight)3613 void PruneBlockFilesManual(CChainState& active_chainstate, int nManualPruneHeight)
3614 {
3615 BlockValidationState state;
3616 if (!active_chainstate.FlushStateToDisk(
3617 state, FlushStateMode::NONE, nManualPruneHeight)) {
3618 LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
3619 }
3620 }
3621
FindFilesToPrune(std::set<int> & setFilesToPrune,uint64_t nPruneAfterHeight,int chain_tip_height,int prune_height,bool is_ibd)3622 void BlockManager::FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, int prune_height, bool is_ibd)
3623 {
3624 LOCK2(cs_main, cs_LastBlockFile);
3625 if (chain_tip_height < 0 || nPruneTarget == 0) {
3626 return;
3627 }
3628 if ((uint64_t)chain_tip_height <= nPruneAfterHeight) {
3629 return;
3630 }
3631
3632 unsigned int nLastBlockWeCanPrune = std::min(prune_height, chain_tip_height - static_cast<int>(MIN_BLOCKS_TO_KEEP));
3633 uint64_t nCurrentUsage = CalculateCurrentUsage();
3634 // We don't check to prune until after we've allocated new space for files
3635 // So we should leave a buffer under our target to account for another allocation
3636 // before the next pruning.
3637 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3638 uint64_t nBytesToPrune;
3639 int count = 0;
3640
3641 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3642 // On a prune event, the chainstate DB is flushed.
3643 // To avoid excessive prune events negating the benefit of high dbcache
3644 // values, we should not prune too rapidly.
3645 // So when pruning in IBD, increase the buffer a bit to avoid a re-prune too soon.
3646 if (is_ibd) {
3647 // Since this is only relevant during IBD, we use a fixed 10%
3648 nBuffer += nPruneTarget / 10;
3649 }
3650
3651 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3652 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3653
3654 if (vinfoBlockFile[fileNumber].nSize == 0) {
3655 continue;
3656 }
3657
3658 if (nCurrentUsage + nBuffer < nPruneTarget) { // are we below our target?
3659 break;
3660 }
3661
3662 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3663 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) {
3664 continue;
3665 }
3666
3667 PruneOneBlockFile(fileNumber);
3668 // Queue up the files for removal
3669 setFilesToPrune.insert(fileNumber);
3670 nCurrentUsage -= nBytesToPrune;
3671 count++;
3672 }
3673 }
3674
3675 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3676 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3677 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3678 nLastBlockWeCanPrune, count);
3679 }
3680
InsertBlockIndex(const uint256 & hash)3681 CBlockIndex * BlockManager::InsertBlockIndex(const uint256& hash)
3682 {
3683 AssertLockHeld(cs_main);
3684
3685 if (hash.IsNull())
3686 return nullptr;
3687
3688 // Return existing
3689 BlockMap::iterator mi = m_block_index.find(hash);
3690 if (mi != m_block_index.end())
3691 return (*mi).second;
3692
3693 // Create new
3694 CBlockIndex* pindexNew = new CBlockIndex();
3695 mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
3696 pindexNew->phashBlock = &((*mi).first);
3697
3698 return pindexNew;
3699 }
3700
LoadBlockIndex(const Consensus::Params & consensus_params,CBlockTreeDB & blocktree,std::set<CBlockIndex *,CBlockIndexWorkComparator> & block_index_candidates)3701 bool BlockManager::LoadBlockIndex(
3702 const Consensus::Params& consensus_params,
3703 CBlockTreeDB& blocktree,
3704 std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
3705 {
3706 if (!blocktree.LoadBlockIndexGuts(consensus_params, [this](const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return this->InsertBlockIndex(hash); }))
3707 return false;
3708
3709 // Calculate nChainWork
3710 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3711 vSortedByHeight.reserve(m_block_index.size());
3712 for (const std::pair<const uint256, CBlockIndex*>& item : m_block_index)
3713 {
3714 CBlockIndex* pindex = item.second;
3715 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3716 }
3717 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3718 for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
3719 {
3720 if (ShutdownRequested()) return false;
3721 CBlockIndex* pindex = item.second;
3722 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3723 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3724 // We can link the chain of blocks for which we've received transactions at some point.
3725 // Pruned nodes may have deleted the block.
3726 if (pindex->nTx > 0) {
3727 if (pindex->pprev) {
3728 if (pindex->pprev->HaveTxsDownloaded()) {
3729 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3730 } else {
3731 pindex->nChainTx = 0;
3732 m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
3733 }
3734 } else {
3735 pindex->nChainTx = pindex->nTx;
3736 }
3737 }
3738 if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
3739 pindex->nStatus |= BLOCK_FAILED_CHILD;
3740 setDirtyBlockIndex.insert(pindex);
3741 }
3742 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->HaveTxsDownloaded() || pindex->pprev == nullptr)) {
3743 block_index_candidates.insert(pindex);
3744 }
3745 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3746 pindexBestInvalid = pindex;
3747 if (pindex->pprev)
3748 pindex->BuildSkip();
3749 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3750 pindexBestHeader = pindex;
3751 }
3752
3753 return true;
3754 }
3755
Unload()3756 void BlockManager::Unload() {
3757 m_failed_blocks.clear();
3758 m_blocks_unlinked.clear();
3759
3760 for (const BlockMap::value_type& entry : m_block_index) {
3761 delete entry.second;
3762 }
3763
3764 m_block_index.clear();
3765 }
3766
LoadBlockIndexDB()3767 bool CChainState::LoadBlockIndexDB()
3768 {
3769 if (!m_blockman.LoadBlockIndex(
3770 m_params.GetConsensus(), *pblocktree,
3771 setBlockIndexCandidates)) {
3772 return false;
3773 }
3774
3775 // Load block file info
3776 pblocktree->ReadLastBlockFile(nLastBlockFile);
3777 vinfoBlockFile.resize(nLastBlockFile + 1);
3778 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3779 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3780 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3781 }
3782 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3783 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3784 CBlockFileInfo info;
3785 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3786 vinfoBlockFile.push_back(info);
3787 } else {
3788 break;
3789 }
3790 }
3791
3792 // Check presence of blk files
3793 LogPrintf("Checking all blk files are present...\n");
3794 std::set<int> setBlkDataFiles;
3795 for (const std::pair<const uint256, CBlockIndex*>& item : m_blockman.m_block_index) {
3796 CBlockIndex* pindex = item.second;
3797 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3798 setBlkDataFiles.insert(pindex->nFile);
3799 }
3800 }
3801 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3802 {
3803 FlatFilePos pos(*it, 0);
3804 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3805 return false;
3806 }
3807 }
3808
3809 // Check whether we have ever pruned block & undo files
3810 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3811 if (fHavePruned)
3812 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3813
3814 // Check whether we need to continue reindexing
3815 bool fReindexing = false;
3816 pblocktree->ReadReindexing(fReindexing);
3817 if(fReindexing) fReindex = true;
3818
3819 return true;
3820 }
3821
LoadMempool(const ArgsManager & args)3822 void CChainState::LoadMempool(const ArgsManager& args)
3823 {
3824 if (!m_mempool) return;
3825 if (args.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
3826 ::LoadMempool(*m_mempool, *this);
3827 }
3828 m_mempool->SetIsLoaded(!ShutdownRequested());
3829 }
3830
LoadChainTip()3831 bool CChainState::LoadChainTip()
3832 {
3833 AssertLockHeld(cs_main);
3834 const CCoinsViewCache& coins_cache = CoinsTip();
3835 assert(!coins_cache.GetBestBlock().IsNull()); // Never called when the coins view is empty
3836 const CBlockIndex* tip = m_chain.Tip();
3837
3838 if (tip && tip->GetBlockHash() == coins_cache.GetBestBlock()) {
3839 return true;
3840 }
3841
3842 // Load pointer to end of best chain
3843 CBlockIndex* pindex = m_blockman.LookupBlockIndex(coins_cache.GetBestBlock());
3844 if (!pindex) {
3845 return false;
3846 }
3847 m_chain.SetTip(pindex);
3848 PruneBlockIndexCandidates();
3849
3850 tip = m_chain.Tip();
3851 LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
3852 tip->GetBlockHash().ToString(),
3853 m_chain.Height(),
3854 FormatISO8601DateTime(tip->GetBlockTime()),
3855 GuessVerificationProgress(m_params.TxData(), tip));
3856 return true;
3857 }
3858
CVerifyDB()3859 CVerifyDB::CVerifyDB()
3860 {
3861 uiInterface.ShowProgress(_("Verifying blocks…").translated, 0, false);
3862 }
3863
~CVerifyDB()3864 CVerifyDB::~CVerifyDB()
3865 {
3866 uiInterface.ShowProgress("", 100, false);
3867 }
3868
VerifyDB(CChainState & chainstate,const CChainParams & chainparams,CCoinsView & coinsview,int nCheckLevel,int nCheckDepth)3869 bool CVerifyDB::VerifyDB(
3870 CChainState& chainstate,
3871 const CChainParams& chainparams,
3872 CCoinsView& coinsview,
3873 int nCheckLevel, int nCheckDepth)
3874 {
3875 AssertLockHeld(cs_main);
3876
3877 if (chainstate.m_chain.Tip() == nullptr || chainstate.m_chain.Tip()->pprev == nullptr)
3878 return true;
3879
3880 // Verify blocks in the best chain
3881 if (nCheckDepth <= 0 || nCheckDepth > chainstate.m_chain.Height())
3882 nCheckDepth = chainstate.m_chain.Height();
3883 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3884 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3885 CCoinsViewCache coins(&coinsview);
3886 CBlockIndex* pindex;
3887 CBlockIndex* pindexFailure = nullptr;
3888 int nGoodTransactions = 0;
3889 BlockValidationState state;
3890 int reportDone = 0;
3891 LogPrintf("[0%%]..."); /* Continued */
3892
3893 const bool is_snapshot_cs{!chainstate.m_from_snapshot_blockhash};
3894
3895 for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
3896 const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3897 if (reportDone < percentageDone/10) {
3898 // report every 10% step
3899 LogPrintf("[%d%%]...", percentageDone); /* Continued */
3900 reportDone = percentageDone/10;
3901 }
3902 uiInterface.ShowProgress(_("Verifying blocks…").translated, percentageDone, false);
3903 if (pindex->nHeight <= chainstate.m_chain.Height()-nCheckDepth)
3904 break;
3905 if ((fPruneMode || is_snapshot_cs) && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3906 // If pruning or running under an assumeutxo snapshot, only go
3907 // back as far as we have data.
3908 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3909 break;
3910 }
3911 CBlock block;
3912 // check level 0: read from disk
3913 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3914 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3915 // check level 1: verify block validity
3916 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3917 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3918 pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
3919 // check level 2: verify undo validity
3920 if (nCheckLevel >= 2 && pindex) {
3921 CBlockUndo undo;
3922 if (!pindex->GetUndoPos().IsNull()) {
3923 if (!UndoReadFromDisk(undo, pindex)) {
3924 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3925 }
3926 }
3927 }
3928 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3929 size_t curr_coins_usage = coins.DynamicMemoryUsage() + chainstate.CoinsTip().DynamicMemoryUsage();
3930
3931 if (nCheckLevel >= 3 && curr_coins_usage <= chainstate.m_coinstip_cache_size_bytes) {
3932 assert(coins.GetBestBlock() == pindex->GetBlockHash());
3933 DisconnectResult res = chainstate.DisconnectBlock(block, pindex, coins);
3934 if (res == DISCONNECT_FAILED) {
3935 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3936 }
3937 if (res == DISCONNECT_UNCLEAN) {
3938 nGoodTransactions = 0;
3939 pindexFailure = pindex;
3940 } else {
3941 nGoodTransactions += block.vtx.size();
3942 }
3943 }
3944 if (ShutdownRequested()) return true;
3945 }
3946 if (pindexFailure)
3947 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainstate.m_chain.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3948
3949 // store block count as we move pindex at check level >= 4
3950 int block_count = chainstate.m_chain.Height() - pindex->nHeight;
3951
3952 // check level 4: try reconnecting blocks
3953 if (nCheckLevel >= 4) {
3954 while (pindex != chainstate.m_chain.Tip()) {
3955 const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
3956 if (reportDone < percentageDone/10) {
3957 // report every 10% step
3958 LogPrintf("[%d%%]...", percentageDone); /* Continued */
3959 reportDone = percentageDone/10;
3960 }
3961 uiInterface.ShowProgress(_("Verifying blocks…").translated, percentageDone, false);
3962 pindex = chainstate.m_chain.Next(pindex);
3963 CBlock block;
3964 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3965 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3966 if (!chainstate.ConnectBlock(block, state, pindex, coins)) {
3967 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s (%s)", pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
3968 }
3969 if (ShutdownRequested()) return true;
3970 }
3971 }
3972
3973 LogPrintf("[DONE].\n");
3974 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", block_count, nGoodTransactions);
3975
3976 return true;
3977 }
3978
3979 /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
RollforwardBlock(const CBlockIndex * pindex,CCoinsViewCache & inputs)3980 bool CChainState::RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs)
3981 {
3982 // TODO: merge with ConnectBlock
3983 CBlock block;
3984 if (!ReadBlockFromDisk(block, pindex, m_params.GetConsensus())) {
3985 return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3986 }
3987
3988 for (const CTransactionRef& tx : block.vtx) {
3989 if (!tx->IsCoinBase()) {
3990 for (const CTxIn &txin : tx->vin) {
3991 inputs.SpendCoin(txin.prevout);
3992 }
3993 }
3994 // Pass check = true as every addition may be an overwrite.
3995 AddCoins(inputs, *tx, pindex->nHeight, true);
3996 }
3997 return true;
3998 }
3999
ReplayBlocks()4000 bool CChainState::ReplayBlocks()
4001 {
4002 LOCK(cs_main);
4003
4004 CCoinsView& db = this->CoinsDB();
4005 CCoinsViewCache cache(&db);
4006
4007 std::vector<uint256> hashHeads = db.GetHeadBlocks();
4008 if (hashHeads.empty()) return true; // We're already in a consistent state.
4009 if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
4010
4011 uiInterface.ShowProgress(_("Replaying blocks…").translated, 0, false);
4012 LogPrintf("Replaying blocks\n");
4013
4014 const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
4015 const CBlockIndex* pindexNew; // New tip during the interrupted flush.
4016 const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
4017
4018 if (m_blockman.m_block_index.count(hashHeads[0]) == 0) {
4019 return error("ReplayBlocks(): reorganization to unknown block requested");
4020 }
4021 pindexNew = m_blockman.m_block_index[hashHeads[0]];
4022
4023 if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
4024 if (m_blockman.m_block_index.count(hashHeads[1]) == 0) {
4025 return error("ReplayBlocks(): reorganization from unknown block requested");
4026 }
4027 pindexOld = m_blockman.m_block_index[hashHeads[1]];
4028 pindexFork = LastCommonAncestor(pindexOld, pindexNew);
4029 assert(pindexFork != nullptr);
4030 }
4031
4032 // Rollback along the old branch.
4033 while (pindexOld != pindexFork) {
4034 if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
4035 CBlock block;
4036 if (!ReadBlockFromDisk(block, pindexOld, m_params.GetConsensus())) {
4037 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4038 }
4039 LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
4040 DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
4041 if (res == DISCONNECT_FAILED) {
4042 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4043 }
4044 // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
4045 // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
4046 // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
4047 // the result is still a version of the UTXO set with the effects of that block undone.
4048 }
4049 pindexOld = pindexOld->pprev;
4050 }
4051
4052 // Roll forward from the forking point to the new tip.
4053 int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
4054 for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
4055 const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
4056 LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
4057 uiInterface.ShowProgress(_("Replaying blocks…").translated, (int) ((nHeight - nForkHeight) * 100.0 / (pindexNew->nHeight - nForkHeight)) , false);
4058 if (!RollforwardBlock(pindex, cache)) return false;
4059 }
4060
4061 cache.SetBestBlock(pindexNew->GetBlockHash());
4062 cache.Flush();
4063 uiInterface.ShowProgress("", 100, false);
4064 return true;
4065 }
4066
NeedsRedownload() const4067 bool CChainState::NeedsRedownload() const
4068 {
4069 AssertLockHeld(cs_main);
4070
4071 // At and above m_params.SegwitHeight, segwit consensus rules must be validated
4072 CBlockIndex* block{m_chain.Tip()};
4073
4074 while (block != nullptr && DeploymentActiveAt(*block, m_params.GetConsensus(), Consensus::DEPLOYMENT_SEGWIT)) {
4075 if (!(block->nStatus & BLOCK_OPT_WITNESS)) {
4076 // block is insufficiently validated for a segwit client
4077 return true;
4078 }
4079 block = block->pprev;
4080 }
4081
4082 return false;
4083 }
4084
UnloadBlockIndex()4085 void CChainState::UnloadBlockIndex() {
4086 nBlockSequenceId = 1;
4087 setBlockIndexCandidates.clear();
4088 }
4089
4090 // May NOT be used after any connections are up as much
4091 // of the peer-processing logic assumes a consistent
4092 // block index state
UnloadBlockIndex(CTxMemPool * mempool,ChainstateManager & chainman)4093 void UnloadBlockIndex(CTxMemPool* mempool, ChainstateManager& chainman)
4094 {
4095 LOCK(cs_main);
4096 chainman.Unload();
4097 pindexBestInvalid = nullptr;
4098 pindexBestHeader = nullptr;
4099 if (mempool) mempool->clear();
4100 vinfoBlockFile.clear();
4101 nLastBlockFile = 0;
4102 setDirtyBlockIndex.clear();
4103 setDirtyFileInfo.clear();
4104 g_versionbitscache.Clear();
4105 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
4106 warningcache[b].clear();
4107 }
4108 fHavePruned = false;
4109 }
4110
LoadBlockIndex()4111 bool ChainstateManager::LoadBlockIndex()
4112 {
4113 AssertLockHeld(cs_main);
4114 // Load block index from databases
4115 bool needs_init = fReindex;
4116 if (!fReindex) {
4117 bool ret = ActiveChainstate().LoadBlockIndexDB();
4118 if (!ret) return false;
4119 needs_init = m_blockman.m_block_index.empty();
4120 }
4121
4122 if (needs_init) {
4123 // Everything here is for *new* reindex/DBs. Thus, though
4124 // LoadBlockIndexDB may have set fReindex if we shut down
4125 // mid-reindex previously, we don't check fReindex and
4126 // instead only check it prior to LoadBlockIndexDB to set
4127 // needs_init.
4128
4129 LogPrintf("Initializing databases...\n");
4130 }
4131 return true;
4132 }
4133
LoadGenesisBlock()4134 bool CChainState::LoadGenesisBlock()
4135 {
4136 LOCK(cs_main);
4137
4138 // Check whether we're already initialized by checking for genesis in
4139 // m_blockman.m_block_index. Note that we can't use m_chain here, since it is
4140 // set based on the coins db, not the block index db, which is the only
4141 // thing loaded at this point.
4142 if (m_blockman.m_block_index.count(m_params.GenesisBlock().GetHash()))
4143 return true;
4144
4145 try {
4146 const CBlock& block = m_params.GenesisBlock();
4147 FlatFilePos blockPos = SaveBlockToDisk(block, 0, m_chain, m_params, nullptr);
4148 if (blockPos.IsNull())
4149 return error("%s: writing genesis block to disk failed", __func__);
4150 CBlockIndex *pindex = m_blockman.AddToBlockIndex(block);
4151 ReceivedBlockTransactions(block, pindex, blockPos);
4152 } catch (const std::runtime_error& e) {
4153 return error("%s: failed to write genesis block: %s", __func__, e.what());
4154 }
4155
4156 return true;
4157 }
4158
LoadExternalBlockFile(FILE * fileIn,FlatFilePos * dbp)4159 void CChainState::LoadExternalBlockFile(FILE* fileIn, FlatFilePos* dbp)
4160 {
4161 // Map of disk positions for blocks with unknown parent (only used for reindex)
4162 static std::multimap<uint256, FlatFilePos> mapBlocksUnknownParent;
4163 int64_t nStart = GetTimeMillis();
4164
4165 int nLoaded = 0;
4166 try {
4167 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4168 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
4169 uint64_t nRewind = blkdat.GetPos();
4170 while (!blkdat.eof()) {
4171 if (ShutdownRequested()) return;
4172
4173 blkdat.SetPos(nRewind);
4174 nRewind++; // start one byte further next time, in case of failure
4175 blkdat.SetLimit(); // remove former limit
4176 unsigned int nSize = 0;
4177 try {
4178 // locate a header
4179 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
4180 blkdat.FindByte(m_params.MessageStart()[0]);
4181 nRewind = blkdat.GetPos()+1;
4182 blkdat >> buf;
4183 if (memcmp(buf, m_params.MessageStart(), CMessageHeader::MESSAGE_START_SIZE)) {
4184 continue;
4185 }
4186 // read size
4187 blkdat >> nSize;
4188 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
4189 continue;
4190 } catch (const std::exception&) {
4191 // no valid block header found; don't complain
4192 break;
4193 }
4194 try {
4195 // read block
4196 uint64_t nBlockPos = blkdat.GetPos();
4197 if (dbp)
4198 dbp->nPos = nBlockPos;
4199 blkdat.SetLimit(nBlockPos + nSize);
4200 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4201 CBlock& block = *pblock;
4202 blkdat >> block;
4203 nRewind = blkdat.GetPos();
4204
4205 uint256 hash = block.GetHash();
4206 {
4207 LOCK(cs_main);
4208 // detect out of order blocks, and store them for later
4209 if (hash != m_params.GetConsensus().hashGenesisBlock && !m_blockman.LookupBlockIndex(block.hashPrevBlock)) {
4210 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4211 block.hashPrevBlock.ToString());
4212 if (dbp)
4213 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4214 continue;
4215 }
4216
4217 // process in case the block isn't known yet
4218 CBlockIndex* pindex = m_blockman.LookupBlockIndex(hash);
4219 if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) {
4220 BlockValidationState state;
4221 if (AcceptBlock(pblock, state, nullptr, true, dbp, nullptr)) {
4222 nLoaded++;
4223 }
4224 if (state.IsError()) {
4225 break;
4226 }
4227 } else if (hash != m_params.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
4228 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
4229 }
4230 }
4231
4232 // Activate the genesis block so normal node progress can continue
4233 if (hash == m_params.GetConsensus().hashGenesisBlock) {
4234 BlockValidationState state;
4235 if (!ActivateBestChain(state, nullptr)) {
4236 break;
4237 }
4238 }
4239
4240 NotifyHeaderTip(*this);
4241
4242 // Recursively process earlier encountered successors of this block
4243 std::deque<uint256> queue;
4244 queue.push_back(hash);
4245 while (!queue.empty()) {
4246 uint256 head = queue.front();
4247 queue.pop_front();
4248 std::pair<std::multimap<uint256, FlatFilePos>::iterator, std::multimap<uint256, FlatFilePos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4249 while (range.first != range.second) {
4250 std::multimap<uint256, FlatFilePos>::iterator it = range.first;
4251 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4252 if (ReadBlockFromDisk(*pblockrecursive, it->second, m_params.GetConsensus())) {
4253 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4254 head.ToString());
4255 LOCK(cs_main);
4256 BlockValidationState dummy;
4257 if (AcceptBlock(pblockrecursive, dummy, nullptr, true, &it->second, nullptr)) {
4258 nLoaded++;
4259 queue.push_back(pblockrecursive->GetHash());
4260 }
4261 }
4262 range.first++;
4263 mapBlocksUnknownParent.erase(it);
4264 NotifyHeaderTip(*this);
4265 }
4266 }
4267 } catch (const std::exception& e) {
4268 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4269 }
4270 }
4271 } catch (const std::runtime_error& e) {
4272 AbortNode(std::string("System error: ") + e.what());
4273 }
4274 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4275 }
4276
CheckBlockIndex()4277 void CChainState::CheckBlockIndex()
4278 {
4279 if (!fCheckBlockIndex) {
4280 return;
4281 }
4282
4283 LOCK(cs_main);
4284
4285 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4286 // so we have the genesis block in m_blockman.m_block_index but no active chain. (A few of the
4287 // tests when iterating the block tree require that m_chain has been initialized.)
4288 if (m_chain.Height() < 0) {
4289 assert(m_blockman.m_block_index.size() <= 1);
4290 return;
4291 }
4292
4293 // Build forward-pointing map of the entire block tree.
4294 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4295 for (const std::pair<const uint256, CBlockIndex*>& entry : m_blockman.m_block_index) {
4296 forward.insert(std::make_pair(entry.second->pprev, entry.second));
4297 }
4298
4299 assert(forward.size() == m_blockman.m_block_index.size());
4300
4301 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4302 CBlockIndex *pindex = rangeGenesis.first->second;
4303 rangeGenesis.first++;
4304 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4305
4306 // Iterate over the entire block tree, using depth-first search.
4307 // Along the way, remember whether there are blocks on the path from genesis
4308 // block being explored which are the first to have certain properties.
4309 size_t nNodes = 0;
4310 int nHeight = 0;
4311 CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4312 CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4313 CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4314 CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4315 CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4316 CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4317 CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4318 while (pindex != nullptr) {
4319 nNodes++;
4320 if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4321 if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4322 if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4323 if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4324 if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4325 if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4326 if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4327
4328 // Begin: actual consistency checks.
4329 if (pindex->pprev == nullptr) {
4330 // Genesis block checks.
4331 assert(pindex->GetBlockHash() == m_params.GetConsensus().hashGenesisBlock); // Genesis block's hash must match.
4332 assert(pindex == m_chain.Genesis()); // The current active chain's genesis block must be this block.
4333 }
4334 if (!pindex->HaveTxsDownloaded()) assert(pindex->nSequenceId <= 0); // nSequenceId can't be set positive for blocks that aren't linked (negative is used for preciousblock)
4335 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4336 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4337 if (!fHavePruned) {
4338 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4339 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4340 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4341 } else {
4342 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4343 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4344 }
4345 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4346 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4347 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to HaveTxsDownloaded().
4348 assert((pindexFirstNeverProcessed == nullptr) == pindex->HaveTxsDownloaded());
4349 assert((pindexFirstNotTransactionsValid == nullptr) == pindex->HaveTxsDownloaded());
4350 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4351 assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
4352 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4353 assert(pindexFirstNotTreeValid == nullptr); // All m_blockman.m_block_index entries must at least be TREE valid
4354 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4355 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4356 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4357 if (pindexFirstInvalid == nullptr) {
4358 // Checks for not-invalid blocks.
4359 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4360 }
4361 if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && pindexFirstNeverProcessed == nullptr) {
4362 if (pindexFirstInvalid == nullptr) {
4363 // If this block sorts at least as good as the current tip and
4364 // is valid and we have all data for its parents, it must be in
4365 // setBlockIndexCandidates. m_chain.Tip() must also be there
4366 // even if some data has been pruned.
4367 if (pindexFirstMissing == nullptr || pindex == m_chain.Tip()) {
4368 assert(setBlockIndexCandidates.count(pindex));
4369 }
4370 // If some parent is missing, then it could be that this block was in
4371 // setBlockIndexCandidates but had to be removed because of the missing data.
4372 // In this case it must be in m_blocks_unlinked -- see test below.
4373 }
4374 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4375 assert(setBlockIndexCandidates.count(pindex) == 0);
4376 }
4377 // Check whether this block is in m_blocks_unlinked.
4378 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = m_blockman.m_blocks_unlinked.equal_range(pindex->pprev);
4379 bool foundInUnlinked = false;
4380 while (rangeUnlinked.first != rangeUnlinked.second) {
4381 assert(rangeUnlinked.first->first == pindex->pprev);
4382 if (rangeUnlinked.first->second == pindex) {
4383 foundInUnlinked = true;
4384 break;
4385 }
4386 rangeUnlinked.first++;
4387 }
4388 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4389 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in m_blocks_unlinked.
4390 assert(foundInUnlinked);
4391 }
4392 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in m_blocks_unlinked if we don't HAVE_DATA
4393 if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in m_blocks_unlinked.
4394 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4395 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4396 assert(fHavePruned); // We must have pruned.
4397 // This block may have entered m_blocks_unlinked if:
4398 // - it has a descendant that at some point had more work than the
4399 // tip, and
4400 // - we tried switching to that descendant but were missing
4401 // data for some intermediate block between m_chain and the
4402 // tip.
4403 // So if this block is itself better than m_chain.Tip() and it wasn't in
4404 // setBlockIndexCandidates, then it must be in m_blocks_unlinked.
4405 if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4406 if (pindexFirstInvalid == nullptr) {
4407 assert(foundInUnlinked);
4408 }
4409 }
4410 }
4411 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4412 // End: actual consistency checks.
4413
4414 // Try descending into the first subnode.
4415 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4416 if (range.first != range.second) {
4417 // A subnode was found.
4418 pindex = range.first->second;
4419 nHeight++;
4420 continue;
4421 }
4422 // This is a leaf node.
4423 // Move upwards until we reach a node of which we have not yet visited the last child.
4424 while (pindex) {
4425 // We are going to either move to a parent or a sibling of pindex.
4426 // If pindex was the first with a certain property, unset the corresponding variable.
4427 if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4428 if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4429 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4430 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4431 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4432 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4433 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4434 // Find our parent.
4435 CBlockIndex* pindexPar = pindex->pprev;
4436 // Find which child we just visited.
4437 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4438 while (rangePar.first->second != pindex) {
4439 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4440 rangePar.first++;
4441 }
4442 // Proceed to the next one.
4443 rangePar.first++;
4444 if (rangePar.first != rangePar.second) {
4445 // Move to the sibling.
4446 pindex = rangePar.first->second;
4447 break;
4448 } else {
4449 // Move up further.
4450 pindex = pindexPar;
4451 nHeight--;
4452 continue;
4453 }
4454 }
4455 }
4456
4457 // Check that we actually traversed the entire map.
4458 assert(nNodes == forward.size());
4459 }
4460
ToString()4461 std::string CChainState::ToString()
4462 {
4463 CBlockIndex* tip = m_chain.Tip();
4464 return strprintf("Chainstate [%s] @ height %d (%s)",
4465 m_from_snapshot_blockhash ? "snapshot" : "ibd",
4466 tip ? tip->nHeight : -1, tip ? tip->GetBlockHash().ToString() : "null");
4467 }
4468
ResizeCoinsCaches(size_t coinstip_size,size_t coinsdb_size)4469 bool CChainState::ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
4470 {
4471 if (coinstip_size == m_coinstip_cache_size_bytes &&
4472 coinsdb_size == m_coinsdb_cache_size_bytes) {
4473 // Cache sizes are unchanged, no need to continue.
4474 return true;
4475 }
4476 size_t old_coinstip_size = m_coinstip_cache_size_bytes;
4477 m_coinstip_cache_size_bytes = coinstip_size;
4478 m_coinsdb_cache_size_bytes = coinsdb_size;
4479 CoinsDB().ResizeCache(coinsdb_size);
4480
4481 LogPrintf("[%s] resized coinsdb cache to %.1f MiB\n",
4482 this->ToString(), coinsdb_size * (1.0 / 1024 / 1024));
4483 LogPrintf("[%s] resized coinstip cache to %.1f MiB\n",
4484 this->ToString(), coinstip_size * (1.0 / 1024 / 1024));
4485
4486 BlockValidationState state;
4487 bool ret;
4488
4489 if (coinstip_size > old_coinstip_size) {
4490 // Likely no need to flush if cache sizes have grown.
4491 ret = FlushStateToDisk(state, FlushStateMode::IF_NEEDED);
4492 } else {
4493 // Otherwise, flush state to disk and deallocate the in-memory coins map.
4494 ret = FlushStateToDisk(state, FlushStateMode::ALWAYS);
4495 CoinsTip().ReallocateCache();
4496 }
4497 return ret;
4498 }
4499
4500 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4501
LoadMempool(CTxMemPool & pool,CChainState & active_chainstate,FopenFn mockable_fopen_function)4502 bool LoadMempool(CTxMemPool& pool, CChainState& active_chainstate, FopenFn mockable_fopen_function)
4503 {
4504 const CChainParams& chainparams = Params();
4505 int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4506 FILE* filestr{mockable_fopen_function(gArgs.GetDataDirNet() / "mempool.dat", "rb")};
4507 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4508 if (file.IsNull()) {
4509 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4510 return false;
4511 }
4512
4513 int64_t count = 0;
4514 int64_t expired = 0;
4515 int64_t failed = 0;
4516 int64_t already_there = 0;
4517 int64_t unbroadcast = 0;
4518 int64_t nNow = GetTime();
4519
4520 try {
4521 uint64_t version;
4522 file >> version;
4523 if (version != MEMPOOL_DUMP_VERSION) {
4524 return false;
4525 }
4526 uint64_t num;
4527 file >> num;
4528 while (num--) {
4529 CTransactionRef tx;
4530 int64_t nTime;
4531 int64_t nFeeDelta;
4532 file >> tx;
4533 file >> nTime;
4534 file >> nFeeDelta;
4535
4536 CAmount amountdelta = nFeeDelta;
4537 if (amountdelta) {
4538 pool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4539 }
4540 if (nTime > nNow - nExpiryTimeout) {
4541 LOCK(cs_main);
4542 if (AcceptToMemoryPoolWithTime(chainparams, pool, active_chainstate, tx, nTime, false /* bypass_limits */,
4543 false /* test_accept */).m_result_type == MempoolAcceptResult::ResultType::VALID) {
4544 ++count;
4545 } else {
4546 // mempool may contain the transaction already, e.g. from
4547 // wallet(s) having loaded it while we were processing
4548 // mempool transactions; consider these as valid, instead of
4549 // failed, but mark them as 'already there'
4550 if (pool.exists(tx->GetHash())) {
4551 ++already_there;
4552 } else {
4553 ++failed;
4554 }
4555 }
4556 } else {
4557 ++expired;
4558 }
4559 if (ShutdownRequested())
4560 return false;
4561 }
4562 std::map<uint256, CAmount> mapDeltas;
4563 file >> mapDeltas;
4564
4565 for (const auto& i : mapDeltas) {
4566 pool.PrioritiseTransaction(i.first, i.second);
4567 }
4568
4569 std::set<uint256> unbroadcast_txids;
4570 file >> unbroadcast_txids;
4571 unbroadcast = unbroadcast_txids.size();
4572 for (const auto& txid : unbroadcast_txids) {
4573 // Ensure transactions were accepted to mempool then add to
4574 // unbroadcast set.
4575 if (pool.get(txid) != nullptr) pool.AddUnbroadcastTx(txid);
4576 }
4577 } catch (const std::exception& e) {
4578 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4579 return false;
4580 }
4581
4582 LogPrintf("Imported mempool transactions from disk: %i succeeded, %i failed, %i expired, %i already there, %i waiting for initial broadcast\n", count, failed, expired, already_there, unbroadcast);
4583 return true;
4584 }
4585
DumpMempool(const CTxMemPool & pool,FopenFn mockable_fopen_function,bool skip_file_commit)4586 bool DumpMempool(const CTxMemPool& pool, FopenFn mockable_fopen_function, bool skip_file_commit)
4587 {
4588 int64_t start = GetTimeMicros();
4589
4590 std::map<uint256, CAmount> mapDeltas;
4591 std::vector<TxMempoolInfo> vinfo;
4592 std::set<uint256> unbroadcast_txids;
4593
4594 static Mutex dump_mutex;
4595 LOCK(dump_mutex);
4596
4597 {
4598 LOCK(pool.cs);
4599 for (const auto &i : pool.mapDeltas) {
4600 mapDeltas[i.first] = i.second;
4601 }
4602 vinfo = pool.infoAll();
4603 unbroadcast_txids = pool.GetUnbroadcastTxs();
4604 }
4605
4606 int64_t mid = GetTimeMicros();
4607
4608 try {
4609 FILE* filestr{mockable_fopen_function(gArgs.GetDataDirNet() / "mempool.dat.new", "wb")};
4610 if (!filestr) {
4611 return false;
4612 }
4613
4614 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4615
4616 uint64_t version = MEMPOOL_DUMP_VERSION;
4617 file << version;
4618
4619 file << (uint64_t)vinfo.size();
4620 for (const auto& i : vinfo) {
4621 file << *(i.tx);
4622 file << int64_t{count_seconds(i.m_time)};
4623 file << int64_t{i.nFeeDelta};
4624 mapDeltas.erase(i.tx->GetHash());
4625 }
4626
4627 file << mapDeltas;
4628
4629 LogPrintf("Writing %d unbroadcast transactions to disk.\n", unbroadcast_txids.size());
4630 file << unbroadcast_txids;
4631
4632 if (!skip_file_commit && !FileCommit(file.Get()))
4633 throw std::runtime_error("FileCommit failed");
4634 file.fclose();
4635 if (!RenameOver(gArgs.GetDataDirNet() / "mempool.dat.new", gArgs.GetDataDirNet() / "mempool.dat")) {
4636 throw std::runtime_error("Rename failed");
4637 }
4638 int64_t last = GetTimeMicros();
4639 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
4640 } catch (const std::exception& e) {
4641 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4642 return false;
4643 }
4644 return true;
4645 }
4646
4647 //! Guess how far we are in the verification process at the given block index
4648 //! require cs_main if pindex has not been validated yet (because nChainTx might be unset)
GuessVerificationProgress(const ChainTxData & data,const CBlockIndex * pindex)4649 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex *pindex) {
4650 if (pindex == nullptr)
4651 return 0.0;
4652
4653 int64_t nNow = time(nullptr);
4654
4655 double fTxTotal;
4656
4657 if (pindex->nChainTx <= data.nTxCount) {
4658 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4659 } else {
4660 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4661 }
4662
4663 return std::min<double>(pindex->nChainTx / fTxTotal, 1.0);
4664 }
4665
SnapshotBlockhash() const4666 std::optional<uint256> ChainstateManager::SnapshotBlockhash() const
4667 {
4668 LOCK(::cs_main);
4669 if (m_active_chainstate && m_active_chainstate->m_from_snapshot_blockhash) {
4670 // If a snapshot chainstate exists, it will always be our active.
4671 return m_active_chainstate->m_from_snapshot_blockhash;
4672 }
4673 return std::nullopt;
4674 }
4675
GetAll()4676 std::vector<CChainState*> ChainstateManager::GetAll()
4677 {
4678 LOCK(::cs_main);
4679 std::vector<CChainState*> out;
4680
4681 if (!IsSnapshotValidated() && m_ibd_chainstate) {
4682 out.push_back(m_ibd_chainstate.get());
4683 }
4684
4685 if (m_snapshot_chainstate) {
4686 out.push_back(m_snapshot_chainstate.get());
4687 }
4688
4689 return out;
4690 }
4691
InitializeChainstate(CTxMemPool * mempool,const std::optional<uint256> & snapshot_blockhash)4692 CChainState& ChainstateManager::InitializeChainstate(
4693 CTxMemPool* mempool, const std::optional<uint256>& snapshot_blockhash)
4694 {
4695 bool is_snapshot = snapshot_blockhash.has_value();
4696 std::unique_ptr<CChainState>& to_modify =
4697 is_snapshot ? m_snapshot_chainstate : m_ibd_chainstate;
4698
4699 if (to_modify) {
4700 throw std::logic_error("should not be overwriting a chainstate");
4701 }
4702 to_modify.reset(new CChainState(mempool, m_blockman, snapshot_blockhash));
4703
4704 // Snapshot chainstates and initial IBD chaintates always become active.
4705 if (is_snapshot || (!is_snapshot && !m_active_chainstate)) {
4706 LogPrintf("Switching active chainstate to %s\n", to_modify->ToString());
4707 m_active_chainstate = to_modify.get();
4708 } else {
4709 throw std::logic_error("unexpected chainstate activation");
4710 }
4711
4712 return *to_modify;
4713 }
4714
ExpectedAssumeutxo(const int height,const CChainParams & chainparams)4715 const AssumeutxoData* ExpectedAssumeutxo(
4716 const int height, const CChainParams& chainparams)
4717 {
4718 const MapAssumeutxo& valid_assumeutxos_map = chainparams.Assumeutxo();
4719 const auto assumeutxo_found = valid_assumeutxos_map.find(height);
4720
4721 if (assumeutxo_found != valid_assumeutxos_map.end()) {
4722 return &assumeutxo_found->second;
4723 }
4724 return nullptr;
4725 }
4726
ActivateSnapshot(CAutoFile & coins_file,const SnapshotMetadata & metadata,bool in_memory)4727 bool ChainstateManager::ActivateSnapshot(
4728 CAutoFile& coins_file,
4729 const SnapshotMetadata& metadata,
4730 bool in_memory)
4731 {
4732 uint256 base_blockhash = metadata.m_base_blockhash;
4733
4734 if (this->SnapshotBlockhash()) {
4735 LogPrintf("[snapshot] can't activate a snapshot-based chainstate more than once\n");
4736 return false;
4737 }
4738
4739 int64_t current_coinsdb_cache_size{0};
4740 int64_t current_coinstip_cache_size{0};
4741
4742 // Cache percentages to allocate to each chainstate.
4743 //
4744 // These particular percentages don't matter so much since they will only be
4745 // relevant during snapshot activation; caches are rebalanced at the conclusion of
4746 // this function. We want to give (essentially) all available cache capacity to the
4747 // snapshot to aid the bulk load later in this function.
4748 static constexpr double IBD_CACHE_PERC = 0.01;
4749 static constexpr double SNAPSHOT_CACHE_PERC = 0.99;
4750
4751 {
4752 LOCK(::cs_main);
4753 // Resize the coins caches to ensure we're not exceeding memory limits.
4754 //
4755 // Allocate the majority of the cache to the incoming snapshot chainstate, since
4756 // (optimistically) getting to its tip will be the top priority. We'll need to call
4757 // `MaybeRebalanceCaches()` once we're done with this function to ensure
4758 // the right allocation (including the possibility that no snapshot was activated
4759 // and that we should restore the active chainstate caches to their original size).
4760 //
4761 current_coinsdb_cache_size = this->ActiveChainstate().m_coinsdb_cache_size_bytes;
4762 current_coinstip_cache_size = this->ActiveChainstate().m_coinstip_cache_size_bytes;
4763
4764 // Temporarily resize the active coins cache to make room for the newly-created
4765 // snapshot chain.
4766 this->ActiveChainstate().ResizeCoinsCaches(
4767 static_cast<size_t>(current_coinstip_cache_size * IBD_CACHE_PERC),
4768 static_cast<size_t>(current_coinsdb_cache_size * IBD_CACHE_PERC));
4769 }
4770
4771 auto snapshot_chainstate = WITH_LOCK(::cs_main, return std::make_unique<CChainState>(
4772 /* mempool */ nullptr, m_blockman, base_blockhash));
4773
4774 {
4775 LOCK(::cs_main);
4776 snapshot_chainstate->InitCoinsDB(
4777 static_cast<size_t>(current_coinsdb_cache_size * SNAPSHOT_CACHE_PERC),
4778 in_memory, false, "chainstate");
4779 snapshot_chainstate->InitCoinsCache(
4780 static_cast<size_t>(current_coinstip_cache_size * SNAPSHOT_CACHE_PERC));
4781 }
4782
4783 const bool snapshot_ok = this->PopulateAndValidateSnapshot(
4784 *snapshot_chainstate, coins_file, metadata);
4785
4786 if (!snapshot_ok) {
4787 WITH_LOCK(::cs_main, this->MaybeRebalanceCaches());
4788 return false;
4789 }
4790
4791 {
4792 LOCK(::cs_main);
4793 assert(!m_snapshot_chainstate);
4794 m_snapshot_chainstate.swap(snapshot_chainstate);
4795 const bool chaintip_loaded = m_snapshot_chainstate->LoadChainTip();
4796 assert(chaintip_loaded);
4797
4798 m_active_chainstate = m_snapshot_chainstate.get();
4799
4800 LogPrintf("[snapshot] successfully activated snapshot %s\n", base_blockhash.ToString());
4801 LogPrintf("[snapshot] (%.2f MB)\n",
4802 m_snapshot_chainstate->CoinsTip().DynamicMemoryUsage() / (1000 * 1000));
4803
4804 this->MaybeRebalanceCaches();
4805 }
4806 return true;
4807 }
4808
PopulateAndValidateSnapshot(CChainState & snapshot_chainstate,CAutoFile & coins_file,const SnapshotMetadata & metadata)4809 bool ChainstateManager::PopulateAndValidateSnapshot(
4810 CChainState& snapshot_chainstate,
4811 CAutoFile& coins_file,
4812 const SnapshotMetadata& metadata)
4813 {
4814 // It's okay to release cs_main before we're done using `coins_cache` because we know
4815 // that nothing else will be referencing the newly created snapshot_chainstate yet.
4816 CCoinsViewCache& coins_cache = *WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsTip());
4817
4818 uint256 base_blockhash = metadata.m_base_blockhash;
4819
4820 CBlockIndex* snapshot_start_block = WITH_LOCK(::cs_main, return m_blockman.LookupBlockIndex(base_blockhash));
4821
4822 if (!snapshot_start_block) {
4823 // Needed for GetUTXOStats and ExpectedAssumeutxo to determine the height and to avoid a crash when base_blockhash.IsNull()
4824 LogPrintf("[snapshot] Did not find snapshot start blockheader %s\n",
4825 base_blockhash.ToString());
4826 return false;
4827 }
4828
4829 int base_height = snapshot_start_block->nHeight;
4830 auto maybe_au_data = ExpectedAssumeutxo(base_height, ::Params());
4831
4832 if (!maybe_au_data) {
4833 LogPrintf("[snapshot] assumeutxo height in snapshot metadata not recognized " /* Continued */
4834 "(%d) - refusing to load snapshot\n", base_height);
4835 return false;
4836 }
4837
4838 const AssumeutxoData& au_data = *maybe_au_data;
4839
4840 COutPoint outpoint;
4841 Coin coin;
4842 const uint64_t coins_count = metadata.m_coins_count;
4843 uint64_t coins_left = metadata.m_coins_count;
4844
4845 LogPrintf("[snapshot] loading coins from snapshot %s\n", base_blockhash.ToString());
4846 int64_t flush_now{0};
4847 int64_t coins_processed{0};
4848
4849 while (coins_left > 0) {
4850 try {
4851 coins_file >> outpoint;
4852 coins_file >> coin;
4853 } catch (const std::ios_base::failure&) {
4854 LogPrintf("[snapshot] bad snapshot format or truncated snapshot after deserializing %d coins\n",
4855 coins_count - coins_left);
4856 return false;
4857 }
4858 if (coin.nHeight > base_height ||
4859 outpoint.n >= std::numeric_limits<decltype(outpoint.n)>::max() // Avoid integer wrap-around in coinstats.cpp:ApplyHash
4860 ) {
4861 LogPrintf("[snapshot] bad snapshot data after deserializing %d coins\n",
4862 coins_count - coins_left);
4863 return false;
4864 }
4865
4866 coins_cache.EmplaceCoinInternalDANGER(std::move(outpoint), std::move(coin));
4867
4868 --coins_left;
4869 ++coins_processed;
4870
4871 if (coins_processed % 1000000 == 0) {
4872 LogPrintf("[snapshot] %d coins loaded (%.2f%%, %.2f MB)\n",
4873 coins_processed,
4874 static_cast<float>(coins_processed) * 100 / static_cast<float>(coins_count),
4875 coins_cache.DynamicMemoryUsage() / (1000 * 1000));
4876 }
4877
4878 // Batch write and flush (if we need to) every so often.
4879 //
4880 // If our average Coin size is roughly 41 bytes, checking every 120,000 coins
4881 // means <5MB of memory imprecision.
4882 if (coins_processed % 120000 == 0) {
4883 if (ShutdownRequested()) {
4884 return false;
4885 }
4886
4887 const auto snapshot_cache_state = WITH_LOCK(::cs_main,
4888 return snapshot_chainstate.GetCoinsCacheSizeState());
4889
4890 if (snapshot_cache_state >=
4891 CoinsCacheSizeState::CRITICAL) {
4892 LogPrintf("[snapshot] flushing coins cache (%.2f MB)... ", /* Continued */
4893 coins_cache.DynamicMemoryUsage() / (1000 * 1000));
4894 flush_now = GetTimeMillis();
4895
4896 // This is a hack - we don't know what the actual best block is, but that
4897 // doesn't matter for the purposes of flushing the cache here. We'll set this
4898 // to its correct value (`base_blockhash`) below after the coins are loaded.
4899 coins_cache.SetBestBlock(GetRandHash());
4900
4901 coins_cache.Flush();
4902 LogPrintf("done (%.2fms)\n", GetTimeMillis() - flush_now);
4903 }
4904 }
4905 }
4906
4907 // Important that we set this. This and the coins_cache accesses above are
4908 // sort of a layer violation, but either we reach into the innards of
4909 // CCoinsViewCache here or we have to invert some of the CChainState to
4910 // embed them in a snapshot-activation-specific CCoinsViewCache bulk load
4911 // method.
4912 coins_cache.SetBestBlock(base_blockhash);
4913
4914 bool out_of_coins{false};
4915 try {
4916 coins_file >> outpoint;
4917 } catch (const std::ios_base::failure&) {
4918 // We expect an exception since we should be out of coins.
4919 out_of_coins = true;
4920 }
4921 if (!out_of_coins) {
4922 LogPrintf("[snapshot] bad snapshot - coins left over after deserializing %d coins\n",
4923 coins_count);
4924 return false;
4925 }
4926
4927 LogPrintf("[snapshot] loaded %d (%.2f MB) coins from snapshot %s\n",
4928 coins_count,
4929 coins_cache.DynamicMemoryUsage() / (1000 * 1000),
4930 base_blockhash.ToString());
4931
4932 LogPrintf("[snapshot] flushing snapshot chainstate to disk\n");
4933 // No need to acquire cs_main since this chainstate isn't being used yet.
4934 coins_cache.Flush(); // TODO: if #17487 is merged, add erase=false here for better performance.
4935
4936 assert(coins_cache.GetBestBlock() == base_blockhash);
4937
4938 CCoinsStats stats{CoinStatsHashType::HASH_SERIALIZED};
4939 auto breakpoint_fnc = [] { /* TODO insert breakpoint here? */ };
4940
4941 // As above, okay to immediately release cs_main here since no other context knows
4942 // about the snapshot_chainstate.
4943 CCoinsViewDB* snapshot_coinsdb = WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsDB());
4944
4945 if (!GetUTXOStats(snapshot_coinsdb, WITH_LOCK(::cs_main, return std::ref(m_blockman)), stats, breakpoint_fnc)) {
4946 LogPrintf("[snapshot] failed to generate coins stats\n");
4947 return false;
4948 }
4949
4950 // Assert that the deserialized chainstate contents match the expected assumeutxo value.
4951 if (AssumeutxoHash{stats.hashSerialized} != au_data.hash_serialized) {
4952 LogPrintf("[snapshot] bad snapshot content hash: expected %s, got %s\n",
4953 au_data.hash_serialized.ToString(), stats.hashSerialized.ToString());
4954 return false;
4955 }
4956
4957 snapshot_chainstate.m_chain.SetTip(snapshot_start_block);
4958
4959 // The remainder of this function requires modifying data protected by cs_main.
4960 LOCK(::cs_main);
4961
4962 // Fake various pieces of CBlockIndex state:
4963 CBlockIndex* index = nullptr;
4964 for (int i = 0; i <= snapshot_chainstate.m_chain.Height(); ++i) {
4965 index = snapshot_chainstate.m_chain[i];
4966
4967 // Fake nTx so that LoadBlockIndex() loads assumed-valid CBlockIndex
4968 // entries (among other things)
4969 if (!index->nTx) {
4970 index->nTx = 1;
4971 }
4972 // Fake nChainTx so that GuessVerificationProgress reports accurately
4973 index->nChainTx = index->pprev ? index->pprev->nChainTx + index->nTx : 1;
4974
4975 // Fake BLOCK_OPT_WITNESS so that CChainState::NeedsRedownload()
4976 // won't ask to rewind the entire assumed-valid chain on startup.
4977 if (index->pprev && DeploymentActiveAt(*index, ::Params().GetConsensus(), Consensus::DEPLOYMENT_SEGWIT)) {
4978 index->nStatus |= BLOCK_OPT_WITNESS;
4979 }
4980 }
4981
4982 assert(index);
4983 index->nChainTx = au_data.nChainTx;
4984 snapshot_chainstate.setBlockIndexCandidates.insert(snapshot_start_block);
4985
4986 LogPrintf("[snapshot] validated snapshot (%.2f MB)\n",
4987 coins_cache.DynamicMemoryUsage() / (1000 * 1000));
4988 return true;
4989 }
4990
ActiveChainstate() const4991 CChainState& ChainstateManager::ActiveChainstate() const
4992 {
4993 LOCK(::cs_main);
4994 assert(m_active_chainstate);
4995 return *m_active_chainstate;
4996 }
4997
IsSnapshotActive() const4998 bool ChainstateManager::IsSnapshotActive() const
4999 {
5000 LOCK(::cs_main);
5001 return m_snapshot_chainstate && m_active_chainstate == m_snapshot_chainstate.get();
5002 }
5003
ValidatedChainstate() const5004 CChainState& ChainstateManager::ValidatedChainstate() const
5005 {
5006 LOCK(::cs_main);
5007 if (m_snapshot_chainstate && IsSnapshotValidated()) {
5008 return *m_snapshot_chainstate.get();
5009 }
5010 assert(m_ibd_chainstate);
5011 return *m_ibd_chainstate.get();
5012 }
5013
IsBackgroundIBD(CChainState * chainstate) const5014 bool ChainstateManager::IsBackgroundIBD(CChainState* chainstate) const
5015 {
5016 LOCK(::cs_main);
5017 return (m_snapshot_chainstate && chainstate == m_ibd_chainstate.get());
5018 }
5019
Unload()5020 void ChainstateManager::Unload()
5021 {
5022 for (CChainState* chainstate : this->GetAll()) {
5023 chainstate->m_chain.SetTip(nullptr);
5024 chainstate->UnloadBlockIndex();
5025 }
5026
5027 m_blockman.Unload();
5028 }
5029
Reset()5030 void ChainstateManager::Reset()
5031 {
5032 LOCK(::cs_main);
5033 m_ibd_chainstate.reset();
5034 m_snapshot_chainstate.reset();
5035 m_active_chainstate = nullptr;
5036 m_snapshot_validated = false;
5037 }
5038
MaybeRebalanceCaches()5039 void ChainstateManager::MaybeRebalanceCaches()
5040 {
5041 if (m_ibd_chainstate && !m_snapshot_chainstate) {
5042 LogPrintf("[snapshot] allocating all cache to the IBD chainstate\n");
5043 // Allocate everything to the IBD chainstate.
5044 m_ibd_chainstate->ResizeCoinsCaches(m_total_coinstip_cache, m_total_coinsdb_cache);
5045 }
5046 else if (m_snapshot_chainstate && !m_ibd_chainstate) {
5047 LogPrintf("[snapshot] allocating all cache to the snapshot chainstate\n");
5048 // Allocate everything to the snapshot chainstate.
5049 m_snapshot_chainstate->ResizeCoinsCaches(m_total_coinstip_cache, m_total_coinsdb_cache);
5050 }
5051 else if (m_ibd_chainstate && m_snapshot_chainstate) {
5052 // If both chainstates exist, determine who needs more cache based on IBD status.
5053 //
5054 // Note: shrink caches first so that we don't inadvertently overwhelm available memory.
5055 if (m_snapshot_chainstate->IsInitialBlockDownload()) {
5056 m_ibd_chainstate->ResizeCoinsCaches(
5057 m_total_coinstip_cache * 0.05, m_total_coinsdb_cache * 0.05);
5058 m_snapshot_chainstate->ResizeCoinsCaches(
5059 m_total_coinstip_cache * 0.95, m_total_coinsdb_cache * 0.95);
5060 } else {
5061 m_snapshot_chainstate->ResizeCoinsCaches(
5062 m_total_coinstip_cache * 0.05, m_total_coinsdb_cache * 0.05);
5063 m_ibd_chainstate->ResizeCoinsCaches(
5064 m_total_coinstip_cache * 0.95, m_total_coinsdb_cache * 0.95);
5065 }
5066 }
5067 }
5068