Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present 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 <bitcoin-build-config.h>
7 : :
8 : : #include <validation.h>
9 : :
10 : : #include <arith_uint256.h>
11 : : #include <chain.h>
12 : : #include <checkqueue.h>
13 : : #include <clientversion.h>
14 : : #include <consensus/amount.h>
15 : : #include <consensus/consensus.h>
16 : : #include <consensus/merkle.h>
17 : : #include <consensus/tx_check.h>
18 : : #include <consensus/tx_verify.h>
19 : : #include <consensus/validation.h>
20 : : #include <cuckoocache.h>
21 : : #include <flatfile.h>
22 : : #include <hash.h>
23 : : #include <kernel/chainparams.h>
24 : : #include <kernel/coinstats.h>
25 : : #include <kernel/disconnected_transactions.h>
26 : : #include <kernel/mempool_entry.h>
27 : : #include <kernel/messagestartchars.h>
28 : : #include <kernel/notifications_interface.h>
29 : : #include <kernel/types.h>
30 : : #include <kernel/warning.h>
31 : : #include <logging/timer.h>
32 : : #include <node/blockstorage.h>
33 : : #include <node/utxo_snapshot.h>
34 : : #include <policy/ephemeral_policy.h>
35 : : #include <policy/policy.h>
36 : : #include <policy/rbf.h>
37 : : #include <policy/settings.h>
38 : : #include <policy/truc_policy.h>
39 : : #include <pow.h>
40 : : #include <primitives/block.h>
41 : : #include <primitives/transaction.h>
42 : : #include <random.h>
43 : : #include <script/script.h>
44 : : #include <script/sigcache.h>
45 : : #include <signet.h>
46 : : #include <tinyformat.h>
47 : : #include <txdb.h>
48 : : #include <txmempool.h>
49 : : #include <uint256.h>
50 : : #include <undo.h>
51 : : #include <util/byte_units.h>
52 : : #include <util/check.h>
53 : : #include <util/fs.h>
54 : : #include <util/fs_helpers.h>
55 : : #include <util/hasher.h>
56 : : #include <util/log.h>
57 : : #include <util/moneystr.h>
58 : : #include <util/rbf.h>
59 : : #include <util/result.h>
60 : : #include <util/signalinterrupt.h>
61 : : #include <util/strencodings.h>
62 : : #include <util/string.h>
63 : : #include <util/threadpool.h>
64 : : #include <util/time.h>
65 : : #include <util/trace.h>
66 : : #include <util/translation.h>
67 : : #include <validationinterface.h>
68 : :
69 : : #include <algorithm>
70 : : #include <cassert>
71 : : #include <chrono>
72 : : #include <deque>
73 : : #include <numeric>
74 : : #include <optional>
75 : : #include <ranges>
76 : : #include <span>
77 : : #include <string>
78 : : #include <tuple>
79 : : #include <utility>
80 : :
81 : : using kernel::CCoinsStats;
82 : : using kernel::ChainstateRole;
83 : : using kernel::CoinStatsHashType;
84 : : using kernel::ComputeUTXOStats;
85 : : using kernel::Notifications;
86 : :
87 : : using fsbridge::FopenFn;
88 : : using node::BlockManager;
89 : : using node::BlockMap;
90 : : using node::CBlockIndexHeightOnlyComparator;
91 : : using node::CBlockIndexWorkComparator;
92 : : using node::SnapshotMetadata;
93 : :
94 : : /** Time window to wait between writing blocks/block index and chainstate to disk.
95 : : * Randomize writing time inside the window to prevent a situation where the
96 : : * network over time settles into a few cohorts of synchronized writers.
97 : : */
98 : : static constexpr auto DATABASE_WRITE_INTERVAL_MIN{50min};
99 : : static constexpr auto DATABASE_WRITE_INTERVAL_MAX{70min};
100 : : /** Maximum age of our tip for us to be considered current for fee estimation */
101 : : static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE{3};
102 : : const std::vector<std::string> CHECKLEVEL_DOC {
103 : : "level 0 reads the blocks from disk",
104 : : "level 1 verifies block validity",
105 : : "level 2 verifies undo data",
106 : : "level 3 checks disconnection of tip blocks",
107 : : "level 4 tries to reconnect the blocks",
108 : : "each level includes the checks of the previous levels",
109 : : };
110 : : /** The number of blocks to keep below the deepest prune lock.
111 : : * There is nothing special about this number. It is higher than what we
112 : : * expect to see in regular mainnet reorgs, but not so high that it would
113 : : * noticeably interfere with the pruning mechanism.
114 : : * */
115 : : static constexpr int PRUNE_LOCK_BUFFER{10};
116 : :
117 : : // Return whether the completed full flush should compact chainstate
118 : 1495 : static bool ShouldCompactChainstate(bool in_ibd)
119 : : {
120 : 1495 : static constexpr uint32_t flush_ratio{320}; // Roughly every 2 weeks with hourly flushes
121 [ + + + + ]: 2845 : return !in_ibd && FastRandomContext().randrange(flush_ratio) == 0;
122 : : }
123 : :
124 : : TRACEPOINT_SEMAPHORE(validation, block_connected);
125 : : TRACEPOINT_SEMAPHORE(utxocache, flush);
126 : : TRACEPOINT_SEMAPHORE(mempool, replaced);
127 : : TRACEPOINT_SEMAPHORE(mempool, rejected);
128 : :
129 : 2243 : const CBlockIndex* Chainstate::FindForkInGlobalIndex(const CBlockLocator& locator) const
130 : : {
131 : 2243 : AssertLockHeld(cs_main);
132 : :
133 : : // Find the latest block common to locator and chain - we expect that
134 : : // locator.vHave is sorted descending by height.
135 [ + + ]: 5926 : for (const uint256& hash : locator.vHave) {
136 : 5923 : const CBlockIndex* pindex{m_blockman.LookupBlockIndex(hash)};
137 [ + + ]: 5923 : if (pindex) {
138 [ + + ]: 4459 : if (m_chain.Contains(*pindex)) {
139 : : return pindex;
140 : : }
141 [ - + - + : 4456 : if (pindex->GetAncestor(m_chain.Height()) == m_chain.Tip()) {
+ + ]
142 : 2243 : return m_chain.Tip();
143 : : }
144 : : }
145 : : }
146 [ - + ]: 3 : return m_chain.Genesis();
147 : : }
148 : :
149 : 52872 : bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx)
150 : : {
151 : 52872 : AssertLockHeld(cs_main);
152 : :
153 : : // CheckFinalTxAtTip() uses active_chain_tip.Height()+1 to evaluate
154 : : // nLockTime because when IsFinalTx() is called within
155 : : // AcceptBlock(), the height of the block *being*
156 : : // evaluated is what is used. Thus if we want to know if a
157 : : // transaction can be part of the *next* block, we need to call
158 : : // IsFinalTx() with one more than active_chain_tip.Height().
159 : 52872 : const int nBlockHeight = active_chain_tip.nHeight + 1;
160 : :
161 : : // BIP113 requires that time-locked transactions have nLockTime set to
162 : : // less than the median time of the previous block they're contained in.
163 : : // When the next block is created its previous block will be the current
164 : : // chain tip, so we use that to calculate the median time passed to
165 : : // IsFinalTx().
166 : 52872 : const int64_t nBlockTime{active_chain_tip.GetMedianTimePast()};
167 : :
168 : 52872 : return IsFinalTx(tx, nBlockHeight, nBlockTime);
169 : : }
170 : :
171 : : namespace {
172 : : /**
173 : : * A helper which calculates heights of inputs of a given transaction.
174 : : *
175 : : * @param[in] tip The current chain tip. If an input belongs to a mempool
176 : : * transaction, we assume it will be confirmed in the next block.
177 : : * @param[in] coins Any CCoinsView that provides access to the relevant coins.
178 : : * @param[in] tx The transaction being evaluated.
179 : : *
180 : : * @returns A vector of input heights or nullopt, in case of an error.
181 : : */
182 : 50202 : std::optional<std::vector<int>> CalculatePrevHeights(
183 : : const CBlockIndex& tip,
184 : : const CCoinsView& coins,
185 : : const CTransaction& tx)
186 : : {
187 : 50202 : std::vector<int> prev_heights;
188 [ - + + - ]: 50202 : prev_heights.resize(tx.vin.size());
189 [ - + + + ]: 123666 : for (size_t i = 0; i < tx.vin.size(); ++i) {
190 [ + - + - ]: 73464 : if (auto coin{coins.GetCoin(tx.vin[i].prevout)}) {
191 [ + + ]: 146928 : prev_heights[i] = coin->nHeight == MEMPOOL_HEIGHT
192 [ + + ]: 73464 : ? tip.nHeight + 1 // Assume all mempool transaction confirm in the next block.
193 : 63867 : : coin->nHeight;
194 : : } else {
195 [ # # # # ]: 0 : LogWarning("%s: Missing input %d in transaction \'%s\'", __func__, i, tx.GetHash().GetHex());
196 : 0 : return std::nullopt;
197 : 73464 : }
198 : : }
199 : 50202 : return prev_heights;
200 : 50202 : }
201 : : } // namespace
202 : :
203 : 50202 : std::optional<LockPoints> CalculateLockPointsAtTip(
204 : : CBlockIndex* tip,
205 : : const CCoinsView& coins_view,
206 : : const CTransaction& tx)
207 : : {
208 [ - + ]: 50202 : assert(tip);
209 : :
210 : 50202 : auto prev_heights{CalculatePrevHeights(*tip, coins_view, tx)};
211 [ - + ]: 50202 : if (!prev_heights.has_value()) return std::nullopt;
212 : :
213 : 50202 : CBlockIndex next_tip;
214 : 50202 : next_tip.pprev = tip;
215 : : // When SequenceLocks() is called within ConnectBlock(), the height
216 : : // of the block *being* evaluated is what is used.
217 : : // Thus if we want to know if a transaction can be part of the
218 : : // *next* block, we need to use one more than active_chainstate.m_chain.Height()
219 : 50202 : next_tip.nHeight = tip->nHeight + 1;
220 [ + - + - ]: 50202 : const auto [min_height, min_time] = CalculateSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, prev_heights.value(), next_tip);
221 : :
222 : : // Also store the hash of the block with the highest height of
223 : : // all the blocks which have sequence locked prevouts.
224 : : // This hash needs to still be on the chain
225 : : // for these LockPoint calculations to be valid
226 : : // Note: It is impossible to correctly calculate a maxInputBlock
227 : : // if any of the sequence locked inputs depend on unconfirmed txs,
228 : : // except in the special case where the relative lock time/height
229 : : // is 0, which is equivalent to no sequence lock. Since we assume
230 : : // input height of tip+1 for mempool txs and test the resulting
231 : : // min_height and min_time from CalculateSequenceLocks against tip+1.
232 : 50202 : int max_input_height{0};
233 [ + - + + ]: 123666 : for (const int height : prev_heights.value()) {
234 : : // Can ignore mempool inputs since we'll fail if they had non-zero locks
235 [ + + ]: 73464 : if (height != next_tip.nHeight) {
236 [ + + ]: 89946 : max_input_height = std::max(max_input_height, height);
237 : : }
238 : : }
239 : :
240 : : // tip->GetAncestor(max_input_height) should never return a nullptr
241 : : // because max_input_height is always less than the tip height.
242 : : // It would, however, be a bad bug to continue execution, since a
243 : : // LockPoints object with the maxInputBlock member set to nullptr
244 : : // signifies no relative lock time.
245 [ + - + - ]: 50202 : return LockPoints{min_height, min_time, Assert(tip->GetAncestor(max_input_height))};
246 : 50202 : }
247 : :
248 : 51736 : bool CheckSequenceLocksAtTip(CBlockIndex* tip,
249 : : const LockPoints& lock_points)
250 : : {
251 [ - + ]: 51736 : assert(tip != nullptr);
252 : :
253 : 51736 : CBlockIndex index;
254 : 51736 : index.pprev = tip;
255 : : // CheckSequenceLocksAtTip() uses active_chainstate.m_chain.Height()+1 to evaluate
256 : : // height based locks because when SequenceLocks() is called within
257 : : // ConnectBlock(), the height of the block *being*
258 : : // evaluated is what is used.
259 : : // Thus if we want to know if a transaction can be part of the
260 : : // *next* block, we need to use one more than active_chainstate.m_chain.Height()
261 : 51736 : index.nHeight = tip->nHeight + 1;
262 : :
263 : 51736 : return EvaluateSequenceLocks(index, {lock_points.height, lock_points.time});
264 : : }
265 : :
266 : 30492 : static void LimitMempoolSize(CTxMemPool& pool, CCoinsViewCache& coins_cache)
267 : : EXCLUSIVE_LOCKS_REQUIRED(::cs_main, pool.cs)
268 : : {
269 : 30492 : AssertLockHeld(::cs_main);
270 : 30492 : AssertLockHeld(pool.cs);
271 : 30492 : int expired = pool.Expire(GetTime<std::chrono::seconds>() - pool.m_opts.expiry);
272 [ + + ]: 30492 : if (expired != 0) {
273 [ + - ]: 12 : LogDebug(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
274 : : }
275 : :
276 : 30492 : std::vector<COutPoint> vNoSpendsRemaining;
277 [ + - ]: 30492 : pool.TrimToSize(pool.m_opts.max_size_bytes, &vNoSpendsRemaining);
278 [ + + ]: 30532 : for (const COutPoint& removed : vNoSpendsRemaining)
279 [ + - ]: 40 : coins_cache.Uncache(removed);
280 : 30492 : }
281 : :
282 : 28488 : static bool IsCurrentForFeeEstimation(Chainstate& active_chainstate) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
283 : : {
284 : 28488 : AssertLockHeld(cs_main);
285 [ + + ]: 28488 : if (active_chainstate.m_chainman.IsInitialBlockDownload()) {
286 : : return false;
287 : : }
288 [ - + + + ]: 56828 : if (active_chainstate.m_chain.Tip()->GetBlockTime() < count_seconds(GetTime<std::chrono::seconds>() - MAX_FEE_ESTIMATION_TIP_AGE))
289 : : return false;
290 [ - + + + ]: 28189 : if (active_chainstate.m_chain.Height() < active_chainstate.m_chainman.m_best_header->nHeight - 1) {
291 : 44 : return false;
292 : : }
293 : : return true;
294 : : }
295 : :
296 : 2914 : void Chainstate::MaybeUpdateMempoolForReorg(
297 : : DisconnectedBlockTransactions& disconnectpool,
298 : : bool fAddToMempool)
299 : : {
300 [ + + ]: 2914 : if (!m_mempool) return;
301 : :
302 : 2913 : AssertLockHeld(cs_main);
303 : 2913 : AssertLockHeld(m_mempool->cs);
304 : 2913 : std::vector<Txid> vHashUpdate;
305 : 2913 : {
306 : : // disconnectpool is ordered so that the front is the most recently-confirmed
307 : : // transaction (the last tx of the block at the tip) in the disconnected chain.
308 : : // Iterate disconnectpool in reverse, so that we add transactions
309 : : // back to the mempool starting with the earliest transaction that had
310 : : // been previously seen in a block.
311 [ + - ]: 2913 : const auto queuedTx = disconnectpool.take();
312 : 2913 : auto it = queuedTx.rbegin();
313 [ + + ]: 14248 : while (it != queuedTx.rend()) {
314 : : // ignore validation errors in resurrected transactions
315 [ + + + + : 15907 : if (!fAddToMempool || (*it)->IsCoinBase() ||
+ + ]
316 [ + - + - ]: 9144 : AcceptToMemoryPool(*this, *it, GetTime(),
317 [ + + ]: 4572 : /*bypass_limits=*/true, /*test_accept=*/false).m_result_type !=
318 : : MempoolAcceptResult::ResultType::VALID) {
319 : : // If the transaction doesn't make it in to the mempool, remove any
320 : : // transactions that depend on it (which would now be orphans).
321 [ + - ]: 10542 : m_mempool->removeRecursive(**it, MemPoolRemovalReason::REORG);
322 [ + - + - ]: 793 : } else if (m_mempool->exists((*it)->GetHash())) {
323 [ + - ]: 793 : vHashUpdate.push_back((*it)->GetHash());
324 : : }
325 : 11335 : ++it;
326 : : }
327 : 0 : }
328 : :
329 : : // AcceptToMemoryPool/addNewTransaction all assume that new mempool entries have
330 : : // no in-mempool children, which is generally not true when adding
331 : : // previously-confirmed transactions back to the mempool.
332 : : // UpdateTransactionsFromBlock finds descendants of any transactions in
333 : : // the disconnectpool that were added back and cleans up the mempool state.
334 [ + - ]: 2913 : m_mempool->UpdateTransactionsFromBlock(vHashUpdate);
335 : :
336 : : // Predicate to use for filtering transactions in removeForReorg.
337 : : // Checks whether the transaction is still final and, if it spends a coinbase output, mature.
338 : : // Also updates valid entries' cached LockPoints if needed.
339 : : // If false, the tx is still valid and its lockpoints are updated.
340 : : // If true, the tx would be invalid in the next block; remove this entry and all of its descendants.
341 : : // Note that TRUC rules are not applied here, so reorgs may cause violations of TRUC inheritance or
342 : : // topology restrictions.
343 : 4677 : const auto filter_final_and_mature = [&](CTxMemPool::txiter it)
344 : : EXCLUSIVE_LOCKS_REQUIRED(m_mempool->cs, ::cs_main) {
345 : 1764 : AssertLockHeld(m_mempool->cs);
346 : 1764 : AssertLockHeld(::cs_main);
347 [ - + ]: 1764 : const CTransaction& tx = it->GetTx();
348 : :
349 : : // The transaction must be final.
350 [ - + + + ]: 3528 : if (!CheckFinalTxAtTip(*Assert(m_chain.Tip()), tx)) return true;
351 : :
352 : 1762 : const LockPoints& lp = it->GetLockPoints();
353 : : // CheckSequenceLocksAtTip checks if the transaction will be final in the next block to be
354 : : // created on top of the new chain.
355 [ + + ]: 1762 : if (TestLockPointValidity(m_chain, lp)) {
356 [ - + + + ]: 3068 : if (!CheckSequenceLocksAtTip(m_chain.Tip(), lp)) {
357 : : return true;
358 : : }
359 : : } else {
360 : 454 : const CCoinsViewMemPool view_mempool{&CoinsTip(), *m_mempool};
361 [ - + + - ]: 456 : const std::optional<LockPoints> new_lock_points{CalculateLockPointsAtTip(m_chain.Tip(), view_mempool, tx)};
362 [ + - - + : 456 : if (new_lock_points.has_value() && CheckSequenceLocksAtTip(m_chain.Tip(), *new_lock_points)) {
+ - + + ]
363 : : // Now update the mempool entry lockpoints as well.
364 : 226 : it->UpdateLockPoints(*new_lock_points);
365 : : } else {
366 : 2 : return true;
367 : : }
368 : 228 : }
369 : :
370 : : // If the transaction spends any coinbase outputs, it must be mature.
371 [ + + ]: 1758 : if (it->GetSpendsCoinbase()) {
372 [ + + ]: 818 : for (const CTxIn& txin : tx.vin) {
373 [ + + ]: 418 : if (m_mempool->exists(txin.prevout.hash)) continue;
374 : 417 : const Coin& coin{CoinsTip().AccessCoin(txin.prevout)};
375 [ - + ]: 417 : assert(!coin.IsSpent());
376 [ - + ]: 417 : const auto mempool_spend_height{m_chain.Tip()->nHeight + 1};
377 [ + + + + ]: 417 : if (coin.IsCoinBase() && mempool_spend_height - coin.nHeight < COINBASE_MATURITY) {
378 : : return true;
379 : : }
380 : : }
381 : : }
382 : : // Transaction is still valid and cached LockPoints are updated.
383 : : return false;
384 : 2913 : };
385 : :
386 : : // We also need to remove any now-immature transactions
387 [ + - ]: 2913 : m_mempool->removeForReorg(m_chain, filter_final_and_mature);
388 : : // Re-limit mempool size, in case we added any transactions
389 [ + - + - ]: 2913 : LimitMempoolSize(*m_mempool, this->CoinsTip());
390 : 2913 : }
391 : :
392 : : /**
393 : : * Checks to avoid mempool polluting consensus critical paths since cached
394 : : * signature and script validity results will be reused if we validate this
395 : : * transaction again during block validation.
396 : : * */
397 : 46320 : static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, TxValidationState& state,
398 : : const CCoinsViewCache& view, const CTxMemPool& pool,
399 : : script_verify_flags flags, PrecomputedTransactionData& txdata, CCoinsViewCache& coins_tip,
400 : : ValidationCache& validation_cache)
401 : : EXCLUSIVE_LOCKS_REQUIRED(cs_main, pool.cs)
402 : : {
403 : 46320 : AssertLockHeld(cs_main);
404 : 46320 : AssertLockHeld(pool.cs);
405 : :
406 [ - + ]: 46320 : assert(!tx.IsCoinBase());
407 [ + + ]: 109159 : for (const CTxIn& txin : tx.vin) {
408 : 62839 : const Coin& coin = view.AccessCoin(txin.prevout);
409 : :
410 : : // This coin was checked in PreChecks and MemPoolAccept
411 : : // has been holding cs_main since then.
412 [ + - ]: 62839 : Assume(!coin.IsSpent());
413 [ + - ]: 62839 : if (coin.IsSpent()) return false;
414 : :
415 : : // If the Coin is available, there are 2 possibilities:
416 : : // it is available in our current ChainstateActive UTXO set,
417 : : // or it's a UTXO provided by a transaction in our mempool.
418 : : // Ensure the scriptPubKeys in Coins from CoinsView are correct.
419 : 62839 : const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
420 [ + + ]: 62839 : if (txFrom) {
421 [ + - ]: 7394 : assert(txFrom->GetHash() == txin.prevout.hash);
422 [ - + - + ]: 7394 : assert(txFrom->vout.size() > txin.prevout.n);
423 [ - + ]: 7394 : assert(txFrom->vout[txin.prevout.n] == coin.out);
424 : : } else {
425 [ + - ]: 55445 : const Coin& coinFromUTXOSet = coins_tip.AccessCoin(txin.prevout);
426 [ - + ]: 55445 : assert(!coinFromUTXOSet.IsSpent());
427 [ - + ]: 55445 : assert(coinFromUTXOSet.out == coin.out);
428 : : }
429 : 62839 : }
430 : :
431 : : // Call CheckInputScripts() to cache signature and script validity against current tip consensus rules.
432 : 46320 : return CheckInputScripts(tx, state, view, flags, CheckInputScriptsFor::Mempool, /* cacheSigStore= */ true, /* cacheFullScriptStore= */ true, txdata, validation_cache);
433 : : }
434 : :
435 : : namespace {
436 : :
437 : : class MemPoolAccept
438 : : {
439 : : public:
440 : 55813 : explicit MemPoolAccept(CTxMemPool& mempool, Chainstate& active_chainstate) :
441 : 55813 : m_pool(mempool),
442 : 55813 : m_view(&CoinsViewEmpty::Get()),
443 [ + - + - ]: 55813 : m_viewmempool(&active_chainstate.CoinsTip(), m_pool),
444 : 55813 : m_active_chainstate(active_chainstate)
445 : : {
446 : 55813 : }
447 : :
448 : : // We put the arguments we're handed into a struct, so we can pass them
449 : : // around easier.
450 : : struct ATMPArgs {
451 : : const int64_t m_accept_time;
452 : : const bool m_bypass_limits;
453 : : /*
454 : : * Return any outpoints which were not previously present in the coins
455 : : * cache, but were added as a result of validating the tx for mempool
456 : : * acceptance. This allows the caller to optionally remove the cache
457 : : * additions if the associated transaction ends up being rejected by
458 : : * the mempool.
459 : : */
460 : : std::vector<COutPoint>& m_coins_to_uncache;
461 : : /** When true, the transaction or package will not be submitted to the mempool. */
462 : : const bool m_test_accept;
463 : : /** Whether we allow transactions to replace mempool transactions. If false,
464 : : * any transaction spending the same inputs as a transaction in the mempool is considered
465 : : * a conflict. */
466 : : const bool m_allow_replacement;
467 : : /** When true, allow sibling eviction. This only occurs in single transaction package settings. */
468 : : const bool m_allow_sibling_eviction;
469 : : /** Used to skip the LimitMempoolSize() call within AcceptSingleTransaction(). This should be used when multiple
470 : : * AcceptSubPackage calls are expected and the mempool will be trimmed at the end of AcceptPackage(). */
471 : : const bool m_package_submission;
472 : : /** When true, use package feerates instead of individual transaction feerates for fee-based
473 : : * policies such as mempool min fee and min relay fee.
474 : : */
475 : : const bool m_package_feerates;
476 : : /** Used for local submission of transactions to catch "absurd" fees
477 : : * due to fee miscalculation by wallets. std:nullopt implies unset, allowing any feerates.
478 : : * Any individual transaction failing this check causes immediate failure.
479 : : */
480 : : const std::optional<CFeeRate> m_client_maxfeerate;
481 : :
482 : : /** Parameters for single transaction mempool validation. */
483 : 55562 : static ATMPArgs SingleAccept(int64_t accept_time,
484 : : bool bypass_limits, std::vector<COutPoint>& coins_to_uncache,
485 : : bool test_accept) {
486 : 55562 : return ATMPArgs{/*accept_time=*/ accept_time,
487 : : /*bypass_limits=*/ bypass_limits,
488 : : /*coins_to_uncache=*/ coins_to_uncache,
489 : : /*test_accept=*/ test_accept,
490 : : /*allow_replacement=*/ true,
491 : : /*allow_sibling_eviction=*/ true,
492 : : /*package_submission=*/ false,
493 : : /*package_feerates=*/ false,
494 : : /*client_maxfeerate=*/ {}, // checked by caller
495 : 55562 : };
496 : : }
497 : :
498 : : /** Parameters for test package mempool validation through testmempoolaccept. */
499 : 78 : static ATMPArgs PackageTestAccept(int64_t accept_time,
500 : : std::vector<COutPoint>& coins_to_uncache) {
501 : 78 : return ATMPArgs{/*accept_time=*/ accept_time,
502 : : /*bypass_limits=*/ false,
503 : : /*coins_to_uncache=*/ coins_to_uncache,
504 : : /*test_accept=*/ true,
505 : : /*allow_replacement=*/ false,
506 : : /*allow_sibling_eviction=*/ false,
507 : : /*package_submission=*/ false, // not submitting to mempool
508 : : /*package_feerates=*/ false,
509 : : /*client_maxfeerate=*/ {}, // checked by caller
510 : 78 : };
511 : : }
512 : :
513 : : /** Parameters for child-with-parents package validation. */
514 : 173 : static ATMPArgs PackageChildWithParents(int64_t accept_time,
515 : : std::vector<COutPoint>& coins_to_uncache, const std::optional<CFeeRate>& client_maxfeerate) {
516 : 173 : return ATMPArgs{/*accept_time=*/ accept_time,
517 : : /*bypass_limits=*/ false,
518 : : /*coins_to_uncache=*/ coins_to_uncache,
519 : : /*test_accept=*/ false,
520 : : /*allow_replacement=*/ true,
521 : : /*allow_sibling_eviction=*/ false,
522 : : /*package_submission=*/ true,
523 : : /*package_feerates=*/ true,
524 : : /*client_maxfeerate=*/ client_maxfeerate,
525 : 173 : };
526 : : }
527 : :
528 : : /** Parameters for a single transaction within a package. */
529 : 380 : static ATMPArgs SingleInPackageAccept(const ATMPArgs& package_args) {
530 : 380 : return ATMPArgs{/*accept_time=*/ package_args.m_accept_time,
531 : : /*bypass_limits=*/ false,
532 : : /*coins_to_uncache=*/ package_args.m_coins_to_uncache,
533 : 380 : /*test_accept=*/ package_args.m_test_accept,
534 : : /*allow_replacement=*/ true,
535 : : /*allow_sibling_eviction=*/ true,
536 : : /*package_submission=*/ true, // trim at the end of AcceptPackage()
537 : : /*package_feerates=*/ false, // only 1 transaction
538 : : /*client_maxfeerate=*/ package_args.m_client_maxfeerate,
539 : 380 : };
540 : : }
541 : :
542 : : private:
543 : : // Private ctor to avoid exposing details to clients and allowing the possibility of
544 : : // mixing up the order of the arguments. Use static functions above instead.
545 : 56193 : ATMPArgs(int64_t accept_time,
546 : : bool bypass_limits,
547 : : std::vector<COutPoint>& coins_to_uncache,
548 : : bool test_accept,
549 : : bool allow_replacement,
550 : : bool allow_sibling_eviction,
551 : : bool package_submission,
552 : : bool package_feerates,
553 : : std::optional<CFeeRate> client_maxfeerate)
554 : 56193 : : m_accept_time{accept_time},
555 : 56193 : m_bypass_limits{bypass_limits},
556 : 56193 : m_coins_to_uncache{coins_to_uncache},
557 : 56193 : m_test_accept{test_accept},
558 : 56193 : m_allow_replacement{allow_replacement},
559 : 56193 : m_allow_sibling_eviction{allow_sibling_eviction},
560 : 56193 : m_package_submission{package_submission},
561 : 56193 : m_package_feerates{package_feerates},
562 : 56193 : m_client_maxfeerate{client_maxfeerate}
563 : : {
564 : : // If we are using package feerates, we must be doing package submission.
565 : : // It also means sibling eviction is not permitted.
566 [ + + ]: 56193 : if (m_package_feerates) {
567 : 173 : Assume(m_package_submission);
568 : 173 : Assume(!m_allow_sibling_eviction);
569 : : }
570 [ + + ]: 56193 : if (m_allow_sibling_eviction) Assume(m_allow_replacement);
571 : 56193 : }
572 : : };
573 : :
574 : : /** Clean up all non-chainstate coins from m_view and m_viewmempool. */
575 : : void CleanupTemporaryCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
576 : :
577 : : // Single transaction acceptance
578 : 55562 : MempoolAcceptResult AcceptSingleTransactionAndCleanup(const CTransactionRef& ptx, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
579 : 55562 : LOCK(m_pool.cs);
580 [ + - ]: 55562 : MempoolAcceptResult result = AcceptSingleTransactionInternal(ptx, args);
581 [ + - ]: 55562 : ClearSubPackageState();
582 [ + - ]: 55562 : return result;
583 : 55562 : }
584 : : MempoolAcceptResult AcceptSingleTransactionInternal(const CTransactionRef& ptx, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
585 : :
586 : : /**
587 : : * Multiple transaction acceptance. Transactions may or may not be interdependent, but must not
588 : : * conflict with each other, and the transactions cannot already be in the mempool. Parents must
589 : : * come before children if any dependencies exist.
590 : : */
591 : 78 : PackageMempoolAcceptResult AcceptMultipleTransactionsAndCleanup(const std::vector<CTransactionRef>& txns, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
592 : 78 : LOCK(m_pool.cs);
593 [ + - ]: 78 : PackageMempoolAcceptResult result = AcceptMultipleTransactionsInternal(txns, args);
594 [ + - ]: 78 : ClearSubPackageState();
595 [ + - ]: 78 : return result;
596 : 78 : }
597 : : PackageMempoolAcceptResult AcceptMultipleTransactionsInternal(const std::vector<CTransactionRef>& txns, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
598 : :
599 : : /**
600 : : * Submission of a subpackage.
601 : : * If subpackage size == 1, calls AcceptSingleTransaction() with adjusted ATMPArgs to
602 : : * enable sibling eviction and creates a PackageMempoolAcceptResult
603 : : * wrapping the result.
604 : : *
605 : : * If subpackage size > 1, calls AcceptMultipleTransactions() with the provided ATMPArgs.
606 : : *
607 : : * Also cleans up all non-chainstate coins from m_view at the end.
608 : : */
609 : : PackageMempoolAcceptResult AcceptSubPackage(const std::vector<CTransactionRef>& subpackage, ATMPArgs& args)
610 : : EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
611 : :
612 : : /**
613 : : * Package (more specific than just multiple transactions) acceptance. Package must be a child
614 : : * with all of its unconfirmed parents, and topologically sorted.
615 : : */
616 : : PackageMempoolAcceptResult AcceptPackage(const Package& package, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
617 : :
618 : : private:
619 : : // All the intermediate state that gets passed between the various levels
620 : : // of checking a given transaction.
621 : : struct Workspace {
622 : 56770 : explicit Workspace(const CTransactionRef& ptx) : m_ptx(ptx), m_hash(ptx->GetHash()) {}
623 : : /** Txids of mempool transactions that this transaction directly conflicts with or may
624 : : * replace via sibling eviction. */
625 : : std::set<Txid> m_conflicts;
626 : : /** Iterators to mempool entries that this transaction directly conflicts with or may
627 : : * replace via sibling eviction. */
628 : : CTxMemPool::setEntries m_iters_conflicting;
629 : : /** All mempool parents of this transaction. */
630 : : std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> m_parents;
631 : : /* Handle to the tx in the changeset */
632 : : CTxMemPool::ChangeSet::TxHandle m_tx_handle;
633 : : /** Whether RBF-related data structures (m_conflicts, m_iters_conflicting,
634 : : * m_replaced_transactions) include a sibling in addition to txns with conflicting inputs. */
635 : : bool m_sibling_eviction{false};
636 : :
637 : : /** Virtual size of the transaction as used by the mempool, calculated using serialized size
638 : : * of the transaction and sigops. */
639 : : int64_t m_vsize;
640 : : /** Fees paid by this transaction: total input amounts subtracted by total output amounts. */
641 : : CAmount m_base_fees;
642 : : /** Base fees + any fee delta set by the user with prioritisetransaction. */
643 : : CAmount m_modified_fees;
644 : :
645 : : /** If we're doing package validation (i.e. m_package_feerates=true), the "effective"
646 : : * package feerate of this transaction is the total fees divided by the total size of
647 : : * transactions (which may include its ancestors and/or descendants). */
648 : : CFeeRate m_package_feerate{0};
649 : :
650 : : const CTransactionRef& m_ptx;
651 : : /** Txid. */
652 : : const Txid& m_hash;
653 : : TxValidationState m_state;
654 : : /** A temporary cache containing serialized transaction data for signature verification.
655 : : * Reused across PolicyScriptChecks and ConsensusScriptChecks. */
656 : : PrecomputedTransactionData m_precomputed_txdata;
657 : : };
658 : :
659 : : // Run the policy checks on a given transaction, excluding any script checks.
660 : : // Looks up inputs, calculates feerate, considers replacement, evaluates
661 : : // package limits, etc. As this function can be invoked for "free" by a peer,
662 : : // only tests that are fast should be done here (to avoid CPU DoS).
663 : : bool PreChecks(ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
664 : :
665 : : // Run checks for mempool replace-by-fee, only used in AcceptSingleTransaction.
666 : : bool ReplacementChecks(Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
667 : :
668 : : bool PackageRBFChecks(const std::vector<CTransactionRef>& txns,
669 : : std::vector<Workspace>& workspaces,
670 : : PackageValidationState& package_state) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
671 : :
672 : : // Run the script checks using our policy flags. As this can be slow, we should
673 : : // only invoke this on transactions that have otherwise passed policy checks.
674 : : bool PolicyScriptChecks(Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
675 : :
676 : : // Re-run the script checks, using consensus flags, and try to cache the
677 : : // result in the scriptcache. This should be done after
678 : : // PolicyScriptChecks(). This requires that all inputs either be in our
679 : : // utxo set or in the mempool.
680 : : bool ConsensusScriptChecks(Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
681 : :
682 : : // Try to add the transaction to the mempool, removing any conflicts first.
683 : : void FinalizeSubpackage(const ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
684 : :
685 : : // Submit all transactions to the mempool and call ConsensusScriptChecks to add to the script
686 : : // cache - should only be called after successful validation of all transactions in the package.
687 : : // Does not call LimitMempoolSize(), so mempool max_size_bytes may be temporarily exceeded.
688 : : bool SubmitPackage(const ATMPArgs& args, std::vector<Workspace>& workspaces, PackageValidationState& package_state,
689 : : std::map<Wtxid, MempoolAcceptResult>& results)
690 : : EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
691 : :
692 : : // Compare a package's feerate against minimum allowed.
693 : 48140 : bool CheckFeeRate(size_t package_size, CAmount package_fee, TxValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_pool.cs)
694 : : {
695 : 48140 : AssertLockHeld(::cs_main);
696 : 48140 : AssertLockHeld(m_pool.cs);
697 : 48140 : CAmount mempoolRejectFee = m_pool.GetMinFee().GetFee(package_size);
698 [ + + + + ]: 48140 : if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) {
699 [ + - + - ]: 50 : return state.Invalid(TxValidationResult::TX_RECONSIDERABLE, "mempool min fee not met", strprintf("%d < %d", package_fee, mempoolRejectFee));
700 : : }
701 : :
702 [ + + ]: 48090 : if (package_fee < m_pool.m_opts.min_relay_feerate.GetFee(package_size)) {
703 [ + - + - ]: 110 : return state.Invalid(TxValidationResult::TX_RECONSIDERABLE, "min relay fee not met",
704 : 220 : strprintf("%d < %d", package_fee, m_pool.m_opts.min_relay_feerate.GetFee(package_size)));
705 : : }
706 : : return true;
707 : : }
708 : :
709 : 94910 : ValidationCache& GetValidationCache()
710 : : {
711 : 94910 : return m_active_chainstate.m_chainman.m_validation_cache;
712 : : }
713 : :
714 : : private:
715 : : CTxMemPool& m_pool;
716 : :
717 : : /** Holds a cached view of available coins from the UTXO set, mempool, and artificial temporary coins (to enable package validation).
718 : : * The view doesn't track whether a coin previously existed but has now been spent. We detect conflicts in other ways:
719 : : * - conflicts within a transaction are checked in CheckTransaction (bad-txns-inputs-duplicate)
720 : : * - conflicts within a package are checked in IsWellFormedPackage (conflict-in-package)
721 : : * - conflicts with an existing mempool transaction are found in CTxMemPool::GetConflictTx and replacements are allowed
722 : : * The temporary coins should persist between individual transaction checks so that package validation is possible,
723 : : * but must be cleaned up when we finish validating a subpackage, whether accepted or rejected. The cache must also
724 : : * be cleared when mempool contents change (when a changeset is applied or when the mempool trims itself) because it
725 : : * can return cached coins that no longer exist in the backend. Use CleanupTemporaryCoins() anytime you are finished
726 : : * with a SubPackageState or call LimitMempoolSize().
727 : : */
728 : : CCoinsViewCache m_view;
729 : :
730 : : // These are the two possible backends for m_view.
731 : : /** When m_view is connected to m_viewmempool as its backend, it can pull coins from the mempool and from the UTXO
732 : : * set. This is also where temporary coins are stored. */
733 : : CCoinsViewMemPool m_viewmempool;
734 : :
735 : : Chainstate& m_active_chainstate;
736 : :
737 : : // Fields below are per *sub*package state and must be reset prior to subsequent
738 : : // AcceptSingleTransaction and AcceptMultipleTransactions invocations
739 : 112101 : struct SubPackageState {
740 : : /** Aggregated modified fees of all transactions, used to calculate package feerate. */
741 : : CAmount m_total_modified_fees{0};
742 : : /** Aggregated virtual size of all transactions, used to calculate package feerate. */
743 : : int64_t m_total_vsize{0};
744 : :
745 : : // RBF-related members
746 : : /** Whether the transaction(s) would replace any mempool transactions and/or evict any siblings.
747 : : * If so, RBF rules apply. */
748 : : bool m_rbf{false};
749 : : /** Mempool transactions that were replaced. */
750 : : std::list<CTransactionRef> m_replaced_transactions;
751 : : /* Changeset representing adding transactions and removing their conflicts. */
752 : : std::unique_ptr<CTxMemPool::ChangeSet> m_changeset;
753 : :
754 : : /** Total modified fees of mempool transactions being replaced. */
755 : : CAmount m_conflicting_fees{0};
756 : : /** Total size (in virtual bytes) of mempool transactions being replaced. */
757 : : size_t m_conflicting_size{0};
758 : : };
759 : :
760 : : struct SubPackageState m_subpackage;
761 : :
762 : : /** Re-set sub-package state to not leak between evaluations */
763 : 56288 : void ClearSubPackageState() EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs)
764 : : {
765 : 56288 : m_subpackage = SubPackageState{};
766 : :
767 : : // And clean coins while at it
768 : 56288 : CleanupTemporaryCoins();
769 : 56288 : }
770 : : };
771 : :
772 : 56738 : bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
773 : : {
774 : 56738 : AssertLockHeld(cs_main);
775 : 56738 : AssertLockHeld(m_pool.cs);
776 : 56738 : const CTransactionRef& ptx = ws.m_ptx;
777 : 56738 : const CTransaction& tx = *ws.m_ptx;
778 : 56738 : const Txid& hash = ws.m_hash;
779 : :
780 : : // Copy/alias what we need out of args
781 : 56738 : const int64_t nAcceptTime = args.m_accept_time;
782 : 56738 : const bool bypass_limits = args.m_bypass_limits;
783 : 56738 : std::vector<COutPoint>& coins_to_uncache = args.m_coins_to_uncache;
784 : :
785 : : // Alias what we need out of ws
786 : 56738 : TxValidationState& state = ws.m_state;
787 : :
788 [ + + ]: 56738 : if (!CheckTransaction(tx, state)) {
789 : : return false; // state filled in by CheckTransaction
790 : : }
791 : :
792 : : // Coinbase is only valid in a block, not as a loose transaction
793 [ + + ]: 56703 : if (tx.IsCoinBase())
794 [ + - + - ]: 2 : return state.Invalid(TxValidationResult::TX_CONSENSUS, "coinbase");
795 : :
796 : : // Rather not work on nonstandard transactions (unless -testnet/-regtest)
797 [ + + ]: 56701 : std::string reason;
798 [ + + + - : 56701 : if (m_pool.m_opts.require_standard && !IsStandardTx(tx, m_pool.m_opts.max_datacarrier_bytes, m_pool.m_opts.permit_bare_multisig, m_pool.m_opts.dust_relay_feerate, reason)) {
+ + ]
799 [ + - + - ]: 5590 : return state.Invalid(TxValidationResult::TX_NOT_STANDARD, reason);
800 : : }
801 : :
802 : : // Transactions smaller than 65 non-witness bytes are not relayed to mitigate CVE-2017-12842.
803 [ + + ]: 51111 : if (::GetSerializeSize(TX_NO_WITNESS(tx)) < MIN_STANDARD_TX_NONWITNESS_SIZE)
804 [ + - + - : 8 : return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "tx-size-small");
+ - ]
805 : :
806 : : // Only accept nLockTime-using transactions that can be mined in the next
807 : : // block; we don't want our mempool filled up with transactions that can't
808 : : // be mined yet.
809 [ - + + - : 102206 : if (!CheckFinalTxAtTip(*Assert(m_active_chainstate.m_chain.Tip()), tx)) {
+ - + + ]
810 [ + - + - : 27 : return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-final");
+ - ]
811 : : }
812 : :
813 [ + - + + ]: 51076 : if (m_pool.exists(tx.GetWitnessHash())) {
814 : : // Exact transaction already exists in the mempool.
815 [ + - + - : 52 : return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-in-mempool");
+ - ]
816 [ + - + + ]: 51024 : } else if (m_pool.exists(tx.GetHash())) {
817 : : // Transaction with the same non-witness data but different witness (same txid, different
818 : : // wtxid) already exists in the mempool.
819 [ + - + - : 5 : return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-same-nonwitness-data-in-mempool");
+ - ]
820 : : }
821 : :
822 : : // Check for conflicts with in-memory transactions
823 [ + + ]: 124599 : for (const CTxIn &txin : tx.vin)
824 : : {
825 [ + - ]: 73582 : const CTransaction* ptxConflicting = m_pool.GetConflictTx(txin.prevout);
826 [ + + ]: 73582 : if (ptxConflicting) {
827 [ + + ]: 2519 : if (!args.m_allow_replacement) {
828 : : // Transaction conflicts with a mempool tx, but we're not allowing replacements in this context.
829 [ + - + - : 2 : return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "bip125-replacement-disallowed");
+ - ]
830 : : }
831 [ + - ]: 2517 : ws.m_conflicts.insert(ptxConflicting->GetHash());
832 : : }
833 : : }
834 : :
835 [ + - ]: 51017 : m_view.SetBackend(m_viewmempool);
836 : :
837 [ + - ]: 51017 : const CCoinsViewCache& coins_cache = m_active_chainstate.CoinsTip();
838 : : // do all inputs exist?
839 [ + + ]: 123480 : for (const CTxIn& txin : tx.vin) {
840 [ + - + + ]: 73514 : if (!coins_cache.HaveCoinInCache(txin.prevout)) {
841 [ + - ]: 15782 : coins_to_uncache.push_back(txin.prevout);
842 : : }
843 : :
844 : : // Note: this call may add txin.prevout to the coins cache
845 : : // (coins_cache.cacheCoins) by way of FetchCoin(). It should be removed
846 : : // later (via coins_to_uncache) if this tx turns out to be invalid.
847 [ + - + + ]: 73514 : if (!m_view.HaveCoin(txin.prevout)) {
848 : : // Are inputs missing because we already have the tx?
849 [ - + + + ]: 2379 : for (size_t out = 0; out < tx.vout.size(); out++) {
850 : : // Optimistically just do efficient check of cache for outputs
851 [ + - + + ]: 1341 : if (coins_cache.HaveCoinInCache(COutPoint(hash, out))) {
852 [ + - + - : 13 : return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-known");
+ - ]
853 : : }
854 : : }
855 : : // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
856 [ + - + - : 1038 : return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent");
+ - ]
857 : : }
858 : : }
859 : :
860 : : // This is const, but calls into `CCoinsViewCache::GetBestBlock()` to refresh
861 : : // the cached best block through `m_viewmempool` after caching inputs.
862 [ + - ]: 49966 : (void)m_view.GetBestBlock();
863 : :
864 : : // All required inputs are cached now, so switch m_view to the empty backend.
865 : : // This keeps already-fetched cache entries for later checks and prevents new
866 : : // backend lookups (which would avoid coins_to_uncache tracking).
867 [ + - + - ]: 49966 : m_view.SetBackend(CoinsViewEmpty::Get());
868 : :
869 [ + - + - : 99932 : assert(m_active_chainstate.m_blockman.LookupBlockIndex(m_view.GetBestBlock()) == m_active_chainstate.m_chain.Tip());
- + - + ]
870 : :
871 : : // Only accept BIP68 sequence locked transactions that can be mined in the next
872 : : // block; we don't want our mempool filled up with transactions that can't
873 : : // be mined yet.
874 : : // Pass in m_view which has all of the relevant inputs cached. Note that, since m_view's
875 : : // backend was removed, it no longer pulls coins from the mempool.
876 [ + - ]: 49966 : const std::optional<LockPoints> lock_points{CalculateLockPointsAtTip(m_active_chainstate.m_chain.Tip(), m_view, tx)};
877 [ + - - + : 99932 : if (!lock_points.has_value() || !CheckSequenceLocksAtTip(m_active_chainstate.m_chain.Tip(), *lock_points)) {
+ - + + ]
878 [ + - + - : 380 : return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-BIP68-final");
+ - ]
879 : : }
880 : :
881 : : // The mempool holds txs for the next block, so pass height+1 to CheckTxInputs
882 [ - + + - : 49586 : if (!Consensus::CheckTxInputs(tx, state, m_view, m_active_chainstate.m_chain.Height() + 1, ws.m_base_fees)) {
+ + ]
883 : : return false; // state filled in by CheckTxInputs
884 : : }
885 : :
886 [ + + ]: 49578 : if (m_pool.m_opts.require_standard) {
887 [ + - ]: 97888 : state = ValidateInputsStandardness(tx, m_view);
888 [ + + ]: 48944 : if (state.IsInvalid()) {
889 : : return false;
890 : : }
891 : : }
892 : :
893 : : // Check for non-standard witnesses.
894 [ + + + + : 49392 : if (tx.HasWitness() && m_pool.m_opts.require_standard && !IsWitnessStandard(tx, m_view)) {
+ - + + ]
895 [ + - + - : 234 : return state.Invalid(TxValidationResult::TX_WITNESS_MUTATED, "bad-witness-nonstandard");
+ - ]
896 : : }
897 : :
898 [ + - ]: 49158 : int64_t nSigOpsCost = GetTransactionSigOpCost(tx, m_view, STANDARD_SCRIPT_VERIFY_FLAGS);
899 : :
900 : : // Keep track of transactions that spend a coinbase, which we re-scan
901 : : // during reorgs to ensure COINBASE_MATURITY is still met.
902 : 49158 : bool fSpendsCoinbase = false;
903 [ + + ]: 107978 : for (const CTxIn &txin : tx.vin) {
904 [ + - ]: 65489 : const Coin &coin = m_view.AccessCoin(txin.prevout);
905 [ + + ]: 65489 : if (coin.IsCoinBase()) {
906 : : fSpendsCoinbase = true;
907 : : break;
908 : : }
909 : : }
910 : :
911 : : // Set entry_sequence to 0 when bypass_limits is used; this allows txs from a block
912 : : // reorg to be marked earlier than any child txs that were already in the mempool.
913 [ + + ]: 49158 : const uint64_t entry_sequence = bypass_limits ? 0 : m_pool.GetSequence();
914 [ + + ]: 49158 : if (!m_subpackage.m_changeset) {
915 [ + - ]: 48536 : m_subpackage.m_changeset = m_pool.GetChangeSet();
916 : : }
917 [ + - - + : 49158 : ws.m_tx_handle = m_subpackage.m_changeset->StageAddition(ptx, ws.m_base_fees, nAcceptTime, m_active_chainstate.m_chain.Height(), entry_sequence, fSpendsCoinbase, nSigOpsCost, lock_points.value());
+ - ]
918 : :
919 : : // ws.m_modified_fees includes any fee deltas from PrioritiseTransaction
920 [ + - ]: 49158 : ws.m_modified_fees = ws.m_tx_handle->GetModifiedFee();
921 : :
922 [ + - ]: 49158 : ws.m_vsize = ws.m_tx_handle->GetTxSize();
923 : :
924 : : // Enforces 0-fee for dust transactions, no incentive to be mined alone
925 [ + + ]: 49158 : if (m_pool.m_opts.require_standard) {
926 [ + - + + ]: 48524 : if (!PreCheckEphemeralTx(*ptx, m_pool.m_opts.dust_relay_feerate, ws.m_base_fees, ws.m_modified_fees, state)) {
927 : : return false; // state filled in by PreCheckEphemeralTx
928 : : }
929 : : }
930 : :
931 [ + + ]: 49071 : if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
932 [ + - + - ]: 5 : return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "bad-txns-too-many-sigops",
933 [ + - ]: 10 : strprintf("%d", nSigOpsCost));
934 : :
935 : : // No individual transactions are allowed below the mempool min feerate except from disconnected
936 : : // blocks and transactions in a package. Package transactions will be checked using package
937 : : // feerate later.
938 [ + + + + : 49066 : if (!bypass_limits && !args.m_package_feerates && !CheckFeeRate(ws.m_vsize, ws.m_modified_fees, state)) return false;
+ - + + ]
939 : :
940 [ + - ]: 48918 : ws.m_iters_conflicting = m_pool.GetIterSet(ws.m_conflicts);
941 : :
942 [ + - ]: 48918 : ws.m_parents = m_pool.GetParents(*ws.m_tx_handle);
943 : :
944 [ + + ]: 48918 : if (!args.m_bypass_limits) {
945 : : // Perform the TRUC checks, using the in-mempool parents.
946 [ + - + + ]: 48097 : if (const auto err{SingleTRUCChecks(m_pool, ws.m_ptx, ws.m_parents, ws.m_conflicts, ws.m_vsize)}) {
947 : : // Single transaction contexts only.
948 [ + + + + ]: 25 : if (args.m_allow_sibling_eviction && err->second != nullptr) {
949 : : // We should only be considering where replacement is considered valid as well.
950 [ + - ]: 14 : Assume(args.m_allow_replacement);
951 : : // Potential sibling eviction. Add the sibling to our list of mempool conflicts to be
952 : : // included in RBF checks.
953 [ + - ]: 14 : ws.m_conflicts.insert(err->second->GetHash());
954 : : // Adding the sibling to m_iters_conflicting here means that it doesn't count towards
955 : : // RBF Carve Out above. This is correct, since removing to-be-replaced transactions from
956 : : // the descendant count is done separately in SingleTRUCChecks for TRUC transactions.
957 [ + - + - ]: 28 : ws.m_iters_conflicting.insert(m_pool.GetIter(err->second->GetHash()).value());
958 : 14 : ws.m_sibling_eviction = true;
959 : : // The sibling will be treated as part of the to-be-replaced set in ReplacementChecks.
960 : : // Note that we are not checking whether it opts in to replaceability via BIP125 or TRUC
961 : : // (which is normally done in PreChecks). However, the only way a TRUC transaction can
962 : : // have a non-TRUC and non-BIP125 descendant is due to a reorg.
963 : : } else {
964 [ + - + - ]: 11 : return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "TRUC-violation", err->first);
965 : : }
966 : 48097 : }
967 : : }
968 : :
969 : : // We want to detect conflicts in any tx in a package to trigger package RBF logic
970 : 48907 : m_subpackage.m_rbf |= !ws.m_conflicts.empty();
971 : 48907 : return true;
972 : 56701 : }
973 : :
974 : 1376 : bool MemPoolAccept::ReplacementChecks(Workspace& ws)
975 : : {
976 : 1376 : AssertLockHeld(cs_main);
977 : 1376 : AssertLockHeld(m_pool.cs);
978 : :
979 [ + - ]: 1376 : const CTransaction& tx = *ws.m_ptx;
980 : 1376 : const Txid& hash = ws.m_hash;
981 : 1376 : TxValidationState& state = ws.m_state;
982 : :
983 [ + - ]: 1376 : CTxMemPool::setEntries all_conflicts;
984 : :
985 : : // Calculate all conflicting entries and enforce Rule #5.
986 [ + - + + ]: 1376 : if (const auto err_string{GetEntriesForConflicts(tx, m_pool, ws.m_iters_conflicting, all_conflicts)}) {
987 [ + - + - ]: 8 : return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY,
988 [ + - + - ]: 12 : strprintf("too many potential replacements%s", ws.m_sibling_eviction ? " (including sibling eviction)" : ""), *err_string);
989 : 4 : }
990 : :
991 : : // Check if it's economically rational to mine this transaction rather than the ones it
992 : : // replaces and pays for its own relay fees. Enforce Rules #3 and #4.
993 [ + + ]: 4005 : for (CTxMemPool::txiter it : all_conflicts) {
994 [ + - ]: 2633 : m_subpackage.m_conflicting_fees += it->GetModifiedFee();
995 [ + - ]: 2633 : m_subpackage.m_conflicting_size += it->GetTxSize();
996 : : }
997 : :
998 : 2744 : if (const auto err_string{PaysForRBF(m_subpackage.m_conflicting_fees, ws.m_modified_fees, ws.m_vsize,
999 [ + - + + ]: 1372 : m_pool.m_opts.incremental_relay_feerate, hash)}) {
1000 : : // Result may change in a package context
1001 [ + + + - ]: 92 : return state.Invalid(TxValidationResult::TX_RECONSIDERABLE,
1002 [ + + + - ]: 136 : strprintf("insufficient fee%s", ws.m_sibling_eviction ? " (including sibling eviction)" : ""), *err_string);
1003 : 46 : }
1004 : :
1005 : : // Add all the to-be-removed transactions to the changeset.
1006 [ + + ]: 3096 : for (auto it : all_conflicts) {
1007 [ + - ]: 1770 : m_subpackage.m_changeset->StageRemoval(it);
1008 : : }
1009 : :
1010 : : // Run cluster size limit checks and fail if we exceed them.
1011 [ + - + + ]: 1326 : if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1012 [ + - + - : 10 : return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too-large-cluster", "");
+ - ]
1013 : : }
1014 : :
1015 [ + - + + ]: 1316 : if (const auto err_string{ImprovesFeerateDiagram(*m_subpackage.m_changeset)}) {
1016 : : // We checked above for the cluster size limits being respected, so a
1017 : : // failure here can only be due to an insufficient fee.
1018 [ + - ]: 4 : Assume(err_string->first == DiagramCheckError::FAILURE);
1019 [ + - + - ]: 4 : return state.Invalid(TxValidationResult::TX_RECONSIDERABLE, "replacement-failed", err_string->second);
1020 : 4 : }
1021 : :
1022 : 1312 : return true;
1023 : 1376 : }
1024 : :
1025 : 18 : bool MemPoolAccept::PackageRBFChecks(const std::vector<CTransactionRef>& txns,
1026 : : std::vector<Workspace>& workspaces,
1027 : : PackageValidationState& package_state)
1028 : : {
1029 : 18 : AssertLockHeld(cs_main);
1030 : 18 : AssertLockHeld(m_pool.cs);
1031 : :
1032 [ - + ]: 55 : assert(std::all_of(txns.cbegin(), txns.cend(), [this](const auto& tx)
1033 : : { return !m_pool.exists(tx->GetHash());}));
1034 : :
1035 [ - + - + : 18 : assert(txns.size() == workspaces.size());
- + ]
1036 : :
1037 : : // We're in package RBF context; replacement proposal must be size 2
1038 [ + + - + ]: 18 : if (workspaces.size() != 2 || !Assume(IsChildWithParents(txns))) {
1039 [ + - + - ]: 1 : return package_state.Invalid(PackageValidationResult::PCKG_POLICY, "package RBF failed: package must be 1-parent-1-child");
1040 : : }
1041 : :
1042 : : // If the package has in-mempool parents, we won't consider a package RBF
1043 : : // since it would result in a cluster larger than 2.
1044 : : // N.B. To relax this constraint we will need to revisit how CCoinsViewMemPool::PackageAddTransaction
1045 : : // is being used inside AcceptMultipleTransactions to track available inputs while processing a package.
1046 : : // Specifically we would need to check that the ancestors of the new
1047 : : // transactions don't intersect with the set of transactions to be removed
1048 : : // due to RBF, which is not checked at all in the package acceptance
1049 : : // context.
1050 [ + + ]: 48 : for (const auto& ws : workspaces) {
1051 [ + + ]: 33 : if (!ws.m_parents.empty()) {
1052 [ + - + - ]: 2 : return package_state.Invalid(PackageValidationResult::PCKG_POLICY, "package RBF failed: new transaction cannot have mempool ancestors");
1053 : : }
1054 : : }
1055 : :
1056 : : // Aggregate all conflicts into one set.
1057 : 15 : CTxMemPool::setEntries direct_conflict_iters;
1058 [ + + ]: 45 : for (Workspace& ws : workspaces) {
1059 : : // Aggregate all conflicts into one set.
1060 : 30 : direct_conflict_iters.merge(ws.m_iters_conflicting);
1061 : : }
1062 : :
1063 [ + - ]: 15 : const auto& parent_ws = workspaces[0];
1064 : 15 : const auto& child_ws = workspaces[1];
1065 : :
1066 : : // Don't consider replacements that would cause us to remove a large number of mempool entries.
1067 : : // This limit is not increased in a package RBF. Use the aggregate number of transactions.
1068 [ + - ]: 15 : CTxMemPool::setEntries all_conflicts;
1069 : 30 : if (const auto err_string{GetEntriesForConflicts(*child_ws.m_ptx, m_pool, direct_conflict_iters,
1070 [ + - - + ]: 15 : all_conflicts)}) {
1071 [ # # # # ]: 0 : return package_state.Invalid(PackageValidationResult::PCKG_POLICY,
1072 [ # # ]: 0 : "package RBF failed: too many potential replacements", *err_string);
1073 : 0 : }
1074 : :
1075 [ + + ]: 404 : for (CTxMemPool::txiter it : all_conflicts) {
1076 [ + - ]: 389 : m_subpackage.m_changeset->StageRemoval(it);
1077 [ + - ]: 389 : m_subpackage.m_conflicting_fees += it->GetModifiedFee();
1078 [ + - ]: 389 : m_subpackage.m_conflicting_size += it->GetTxSize();
1079 : : }
1080 : :
1081 : : // Use the child as the transaction for attributing errors to.
1082 [ + - ]: 15 : const Txid& child_hash = child_ws.m_ptx->GetHash();
1083 : 30 : if (const auto err_string{PaysForRBF(/*original_fees=*/m_subpackage.m_conflicting_fees,
1084 : : /*replacement_fees=*/m_subpackage.m_total_modified_fees,
1085 : 15 : /*replacement_vsize=*/m_subpackage.m_total_vsize,
1086 [ + - + + ]: 15 : m_pool.m_opts.incremental_relay_feerate, child_hash)}) {
1087 [ + - + - ]: 3 : return package_state.Invalid(PackageValidationResult::PCKG_POLICY,
1088 [ + - ]: 6 : "package RBF failed: insufficient anti-DoS fees", *err_string);
1089 : 3 : }
1090 : :
1091 : : // Ensure this two transaction package is a "chunk" on its own; we don't want the child
1092 : : // to be only paying anti-DoS fees
1093 [ + - ]: 12 : const CFeeRate parent_feerate(parent_ws.m_modified_fees, parent_ws.m_vsize);
1094 [ + - ]: 12 : const CFeeRate package_feerate(m_subpackage.m_total_modified_fees, m_subpackage.m_total_vsize);
1095 [ + + ]: 12 : if (package_feerate <= parent_feerate) {
1096 [ + - ]: 1 : return package_state.Invalid(PackageValidationResult::PCKG_POLICY,
1097 [ + - ]: 2 : "package RBF failed: package feerate is less than or equal to parent feerate",
1098 [ + - + - : 2 : strprintf("package feerate %s <= parent feerate is %s", package_feerate.ToString(), parent_feerate.ToString()));
+ - ]
1099 : : }
1100 : :
1101 : : // Run cluster size limit checks and fail if we exceed them.
1102 [ + - - + ]: 11 : if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1103 [ # # # # : 0 : return package_state.Invalid(PackageValidationResult::PCKG_POLICY, "too-large-cluster", "");
# # ]
1104 : : }
1105 : :
1106 : : // Check if it's economically rational to mine this package rather than the ones it replaces.
1107 [ + - + + ]: 11 : if (const auto err_tup{ImprovesFeerateDiagram(*m_subpackage.m_changeset)}) {
1108 [ + - ]: 1 : Assume(err_tup->first == DiagramCheckError::FAILURE);
1109 [ + - ]: 1 : return package_state.Invalid(PackageValidationResult::PCKG_POLICY,
1110 [ + - + - ]: 3 : "package RBF failed: " + err_tup.value().second, "");
1111 : 1 : }
1112 : :
1113 [ + - + - : 10 : LogDebug(BCLog::TXPACKAGES, "package RBF checks passed: parent %s (wtxid=%s), child %s (wtxid=%s), package hash (%s)\n",
+ - + - +
- + - + -
+ - + - ]
1114 : : txns.front()->GetHash().ToString(), txns.front()->GetWitnessHash().ToString(),
1115 : : txns.back()->GetHash().ToString(), txns.back()->GetWitnessHash().ToString(),
1116 : : GetPackageHash(txns).ToString());
1117 : :
1118 : :
1119 : : return true;
1120 : 15 : }
1121 : :
1122 : 48590 : bool MemPoolAccept::PolicyScriptChecks(Workspace& ws)
1123 : : {
1124 : 48590 : AssertLockHeld(cs_main);
1125 : 48590 : AssertLockHeld(m_pool.cs);
1126 [ + + ]: 48590 : const CTransaction& tx = *ws.m_ptx;
1127 : 48590 : TxValidationState& state = ws.m_state;
1128 : :
1129 [ + + ]: 48590 : const script_verify_flags scriptVerifyFlags = (m_pool.m_opts.require_standard ? STANDARD_SCRIPT_VERIFY_FLAGS : m_active_chainstate.m_chainman.m_all_consensus_script_flags);
1130 : :
1131 : : // Check input scripts and signatures.
1132 : : // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1133 [ + + ]: 48590 : if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, CheckInputScriptsFor::Mempool, true, false, ws.m_precomputed_txdata, GetValidationCache())) {
1134 : : // Detect a failure due to a missing witness so that p2p code can handle rejection caching appropriately.
1135 [ + + + + ]: 1750 : if (!tx.HasWitness() && SpendsNonAnchorWitnessProg(tx, m_view)) {
1136 : 44 : state.Invalid(TxValidationResult::TX_WITNESS_STRIPPED,
1137 [ - + - + : 88 : state.GetRejectReason(), state.GetDebugMessage());
+ - ]
1138 : : }
1139 : 1750 : return false; // state filled in by CheckInputScripts
1140 : : }
1141 : :
1142 : : return true;
1143 : : }
1144 : :
1145 : 46320 : bool MemPoolAccept::ConsensusScriptChecks(Workspace& ws)
1146 : : {
1147 : 46320 : AssertLockHeld(cs_main);
1148 : 46320 : AssertLockHeld(m_pool.cs);
1149 [ - + ]: 46320 : const CTransaction& tx = *ws.m_ptx;
1150 : 46320 : const Txid& hash = ws.m_hash;
1151 : 46320 : TxValidationState& state = ws.m_state;
1152 : :
1153 : : // Check again against the current block tip's script verification
1154 : : // flags to cache our script execution flags. This is, of course,
1155 : : // useless if the next block has different script flags from the
1156 : : // previous one, but because the cache tracks script flags for us it
1157 : : // will auto-invalidate and we'll just have a few blocks of extra
1158 : : // misses on soft-fork activation.
1159 : : //
1160 : : // This is also useful in case of bugs in the standard flags that cause
1161 : : // transactions to pass as valid when they're actually invalid. For
1162 : : // instance the STRICTENC flag was incorrectly allowing certain
1163 : : // CHECKSIG NOT scripts to pass, even though they were invalid.
1164 : : //
1165 : : // There is a similar check in CreateNewBlock() to prevent creating
1166 : : // invalid blocks (using TestBlockValidity), however allowing such
1167 : : // transactions into the mempool can be exploited as a DoS attack.
1168 [ - + ]: 92640 : script_verify_flags currentBlockScriptVerifyFlags{GetBlockScriptFlags(*m_active_chainstate.m_chain.Tip(), m_active_chainstate.m_chainman)};
1169 : :
1170 [ - + ]: 92640 : if (!CheckInputsFromMempoolAndCache(tx, state, m_view, m_pool, currentBlockScriptVerifyFlags,
1171 : 46320 : ws.m_precomputed_txdata, m_active_chainstate.CoinsTip(), GetValidationCache())) {
1172 [ # # # # ]: 0 : LogError("BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not mempool flags %s, %s", hash.ToString(), state.ToString());
1173 : 0 : return Assume(false);
1174 : : }
1175 : :
1176 : : return true;
1177 : : }
1178 : :
1179 : 28419 : void MemPoolAccept::FinalizeSubpackage(const ATMPArgs& args)
1180 : : {
1181 : 28419 : AssertLockHeld(cs_main);
1182 : 28419 : AssertLockHeld(m_pool.cs);
1183 : :
1184 [ + + ]: 28419 : if (!m_subpackage.m_changeset->GetRemovals().empty()) Assume(args.m_allow_replacement);
1185 : : // Remove conflicting transactions from the mempool
1186 [ + + ]: 29998 : for (CTxMemPool::txiter it : m_subpackage.m_changeset->GetRemovals())
1187 : : {
1188 : 1579 : std::string log_string = strprintf("replacing mempool tx %s (wtxid=%s, fees=%s, vsize=%s). ",
1189 [ + - ]: 3158 : it->GetTx().GetHash().ToString(),
1190 [ + - ]: 1579 : it->GetTx().GetWitnessHash().ToString(),
1191 : 1579 : it->GetFee(),
1192 [ + - ]: 3158 : it->GetTxSize());
1193 [ - + ]: 1579 : FeeFrac feerate{m_subpackage.m_total_modified_fees, int32_t(m_subpackage.m_total_vsize)};
1194 : 1579 : uint256 tx_or_package_hash{};
1195 [ - + ]: 1579 : const bool replaced_with_tx{m_subpackage.m_changeset->GetTxCount() == 1};
1196 [ + + ]: 1579 : if (replaced_with_tx) {
1197 [ + - ]: 1200 : const CTransaction& tx = m_subpackage.m_changeset->GetAddedTxn(0);
1198 : 1200 : tx_or_package_hash = tx.GetHash().ToUint256();
1199 : 1200 : log_string += strprintf("New tx %s (wtxid=%s, fees=%s, vsize=%s)",
1200 [ + - ]: 2400 : tx.GetHash().ToString(),
1201 [ + - + - ]: 2400 : tx.GetWitnessHash().ToString(),
1202 : : feerate.fee,
1203 : 1200 : feerate.size);
1204 : : } else {
1205 [ + - + - ]: 379 : tx_or_package_hash = GetPackageHash(m_subpackage.m_changeset->GetAddedTxns());
1206 [ + - ]: 758 : log_string += strprintf("New package %s with %lu txs, fees=%s, vsize=%s",
1207 : 379 : tx_or_package_hash.ToString(),
1208 [ - + + - ]: 379 : m_subpackage.m_changeset->GetTxCount(),
1209 : : feerate.fee,
1210 : 379 : feerate.size);
1211 : :
1212 : : }
1213 [ + - + - : 1579 : LogDebug(BCLog::MEMPOOL, "%s\n", log_string);
+ - ]
1214 : : TRACEPOINT(mempool, replaced,
1215 : : it->GetTx().GetHash().data(),
1216 : : it->GetTxSize(),
1217 : : it->GetFee(),
1218 : : std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count(),
1219 : : tx_or_package_hash.data(),
1220 : : feerate.size,
1221 : : feerate.fee,
1222 : : replaced_with_tx
1223 : 1579 : );
1224 [ + - + - ]: 4737 : m_subpackage.m_replaced_transactions.push_back(it->GetSharedTx());
1225 : 1579 : }
1226 : 28419 : m_subpackage.m_changeset->Apply();
1227 [ + - ]: 28419 : m_subpackage.m_changeset.reset();
1228 : 28419 : }
1229 : :
1230 : 69 : bool MemPoolAccept::SubmitPackage(const ATMPArgs& args, std::vector<Workspace>& workspaces,
1231 : : PackageValidationState& package_state,
1232 : : std::map<Wtxid, MempoolAcceptResult>& results)
1233 : : {
1234 : 69 : AssertLockHeld(cs_main);
1235 : 69 : AssertLockHeld(m_pool.cs);
1236 : : // Sanity check: none of the transactions should be in the mempool, and none of the transactions
1237 : : // should have a same-txid-different-witness equivalent in the mempool.
1238 [ - + ]: 207 : assert(std::all_of(workspaces.cbegin(), workspaces.cend(), [this](const auto& ws) { return !m_pool.exists(ws.m_ptx->GetHash()); }));
1239 : :
1240 : 69 : bool all_submitted = true;
1241 : 69 : FinalizeSubpackage(args);
1242 : : // ConsensusScriptChecks adds to the script cache and is therefore consensus-critical;
1243 : : // CheckInputsFromMempoolAndCache asserts that transactions only spend coins available from the
1244 : : // mempool or UTXO set. Submit each transaction to the mempool immediately after calling
1245 : : // ConsensusScriptChecks to make the outputs available for subsequent transactions.
1246 [ + + ]: 207 : for (Workspace& ws : workspaces) {
1247 [ - + ]: 138 : if (!ConsensusScriptChecks(ws)) {
1248 [ # # # # ]: 0 : results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1249 : : // Since PolicyScriptChecks() passed, this should never fail.
1250 : 0 : Assume(false);
1251 : 0 : all_submitted = false;
1252 [ # # ]: 0 : package_state.Invalid(PackageValidationResult::PCKG_MEMPOOL_ERROR,
1253 : 0 : strprintf("BUG! PolicyScriptChecks succeeded but ConsensusScriptChecks failed: %s",
1254 [ # # # # ]: 0 : ws.m_ptx->GetHash().ToString()));
1255 : : }
1256 : : // Remove first failing tx and all subsequent in package
1257 [ - + ]: 138 : if (!all_submitted) {
1258 [ # # ]: 0 : if (!m_subpackage.m_changeset) m_subpackage.m_changeset = m_pool.GetChangeSet();
1259 [ # # ]: 0 : m_subpackage.m_changeset->StageRemoval(m_pool.GetIter(ws.m_ptx->GetHash()).value());
1260 : : }
1261 : : }
1262 [ - + ]: 69 : if (!all_submitted) {
1263 : 0 : Assume(m_subpackage.m_changeset);
1264 : : // This code should be unreachable; it's here as belt-and-suspenders
1265 : : // to try to ensure we have no consensus-invalid transactions in the
1266 : : // mempool.
1267 : 0 : m_subpackage.m_changeset->Apply();
1268 [ # # ]: 0 : m_subpackage.m_changeset.reset();
1269 : 0 : return false;
1270 : : }
1271 : :
1272 : 69 : std::vector<Wtxid> all_package_wtxids;
1273 [ - + + - ]: 69 : all_package_wtxids.reserve(workspaces.size());
1274 [ + - ]: 69 : std::transform(workspaces.cbegin(), workspaces.cend(), std::back_inserter(all_package_wtxids),
1275 : 138 : [](const auto& ws) { return ws.m_ptx->GetWitnessHash(); });
1276 : :
1277 [ + + ]: 69 : if (!m_subpackage.m_replaced_transactions.empty()) {
1278 [ + - + - : 10 : LogDebug(BCLog::MEMPOOL, "replaced %u mempool transactions with %u new one(s) for %s additional fees, %d delta bytes\n",
- + + - ]
1279 : : m_subpackage.m_replaced_transactions.size(), workspaces.size(),
1280 : : m_subpackage.m_total_modified_fees - m_subpackage.m_conflicting_fees,
1281 : : m_subpackage.m_total_vsize - static_cast<int>(m_subpackage.m_conflicting_size));
1282 : : }
1283 : :
1284 : : // Add successful results. The returned results may change later if LimitMempoolSize() evicts them.
1285 [ + + ]: 207 : for (Workspace& ws : workspaces) {
1286 [ + - ]: 138 : auto iter = m_pool.GetIter(ws.m_ptx->GetHash());
1287 [ + - ]: 138 : Assume(iter.has_value());
1288 [ + - ]: 138 : const auto effective_feerate = args.m_package_feerates ? ws.m_package_feerate :
1289 [ - - ]: 138 : CFeeRate{ws.m_modified_fees, static_cast<int32_t>(ws.m_vsize)};
1290 [ + - ]: 138 : const auto effective_feerate_wtxids = args.m_package_feerates ? all_package_wtxids :
1291 [ + - - - ]: 138 : std::vector<Wtxid>{ws.m_ptx->GetWitnessHash()};
1292 : 276 : results.emplace(ws.m_ptx->GetWitnessHash(),
1293 [ + - + - ]: 138 : MempoolAcceptResult::Success(std::move(m_subpackage.m_replaced_transactions), ws.m_vsize,
1294 : : ws.m_base_fees, effective_feerate, effective_feerate_wtxids));
1295 [ - + ]: 138 : if (!m_pool.m_opts.signals) continue;
1296 [ + - ]: 138 : const CTransaction& tx = *ws.m_ptx;
1297 [ + - ]: 138 : const auto tx_info = NewMempoolTransactionInfo(ws.m_ptx, ws.m_base_fees,
1298 [ + - ]: 138 : ws.m_vsize, (*iter)->GetHeight(),
1299 : 138 : args.m_bypass_limits, args.m_package_submission,
1300 : 138 : IsCurrentForFeeEstimation(m_active_chainstate),
1301 [ + - + - ]: 276 : m_pool.HasNoInputsOf(tx));
1302 [ + - ]: 138 : m_pool.m_opts.signals->TransactionAddedToMempool(tx_info, m_pool.GetAndIncrementSequence());
1303 : 138 : }
1304 : 69 : return all_submitted;
1305 : 69 : }
1306 : :
1307 : 55942 : MempoolAcceptResult MemPoolAccept::AcceptSingleTransactionInternal(const CTransactionRef& ptx, ATMPArgs& args)
1308 : : {
1309 : 55942 : AssertLockHeld(cs_main);
1310 : 55942 : AssertLockHeld(m_pool.cs);
1311 : :
1312 : 55942 : Workspace ws(ptx);
1313 [ + - ]: 55942 : const std::vector<Wtxid> single_wtxid{ws.m_ptx->GetWitnessHash()};
1314 : :
1315 [ + - + + ]: 55942 : if (!PreChecks(args, ws)) {
1316 [ + + ]: 7819 : if (ws.m_state.GetResult() == TxValidationResult::TX_RECONSIDERABLE) {
1317 : : // Failed for fee reasons. Provide the effective feerate and which tx was included.
1318 [ + - + - ]: 441 : return MempoolAcceptResult::FeeFailure(ws.m_state, CFeeRate(ws.m_modified_fees, ws.m_vsize), single_wtxid);
1319 : : }
1320 [ + - + - ]: 15344 : return MempoolAcceptResult::Failure(ws.m_state);
1321 : : }
1322 : :
1323 [ + + + - : 48123 : if (m_subpackage.m_rbf && !ReplacementChecks(ws)) {
+ + ]
1324 [ + + ]: 64 : if (ws.m_state.GetResult() == TxValidationResult::TX_RECONSIDERABLE) {
1325 : : // Failed for incentives-based fee reasons. Provide the effective feerate and which tx was included.
1326 [ + - + - ]: 150 : return MempoolAcceptResult::FeeFailure(ws.m_state, CFeeRate(ws.m_modified_fees, ws.m_vsize), single_wtxid);
1327 : : }
1328 [ + - + - ]: 28 : return MempoolAcceptResult::Failure(ws.m_state);
1329 : : }
1330 : :
1331 : : // Check if the transaction would exceed the cluster size limit.
1332 [ + - + + ]: 48059 : if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1333 [ + - + - : 238 : ws.m_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too-large-cluster", "");
+ - ]
1334 [ + - + - ]: 238 : return MempoolAcceptResult::Failure(ws.m_state);
1335 : : }
1336 : :
1337 : : // Now that we've verified the cluster limit is respected, we can perform
1338 : : // calculations involving the full ancestors of the tx.
1339 [ + + ]: 47940 : if (ws.m_conflicts.size()) {
1340 [ + - ]: 1312 : auto ancestors = m_subpackage.m_changeset->CalculateMemPoolAncestors(ws.m_tx_handle);
1341 : :
1342 : : // A transaction that spends outputs that would be replaced by it is invalid. Now
1343 : : // that we have the set of all ancestors we can detect this
1344 : : // pathological case by making sure ws.m_conflicts and this tx's ancestors don't
1345 : : // intersect.
1346 [ + - + + ]: 1312 : if (const auto err_string{EntriesAndTxidsDisjoint(ancestors, ws.m_conflicts, ptx->GetHash())}) {
1347 : : // We classify this as a consensus error because a transaction depending on something it
1348 : : // conflicts with would be inconsistent.
1349 [ + - + - ]: 5 : ws.m_state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-spends-conflicting-tx", *err_string);
1350 [ + - + - ]: 10 : return MempoolAcceptResult::Failure(ws.m_state);
1351 : 1312 : }
1352 : 1312 : }
1353 : :
1354 : 47935 : m_subpackage.m_total_vsize = ws.m_vsize;
1355 : 47935 : m_subpackage.m_total_modified_fees = ws.m_modified_fees;
1356 : :
1357 : : // Individual modified feerate exceeded caller-defined max; abort
1358 [ + + + - : 47935 : if (args.m_client_maxfeerate && CFeeRate(ws.m_modified_fees, ws.m_vsize) > args.m_client_maxfeerate.value()) {
+ + ]
1359 [ + - + - : 2 : ws.m_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "max feerate exceeded", "");
+ - ]
1360 [ + - + - ]: 2 : return MempoolAcceptResult::Failure(ws.m_state);
1361 : : }
1362 : :
1363 [ + + + + ]: 47934 : if (!args.m_bypass_limits && m_pool.m_opts.require_standard) {
1364 [ + - ]: 46516 : Wtxid dummy_wtxid;
1365 [ + - + + : 93032 : if (!CheckEphemeralSpends(/*package=*/{ptx}, m_pool.m_opts.dust_relay_feerate, m_pool, ws.m_state, dummy_wtxid)) {
+ - + + -
- - - ]
1366 [ + - + - ]: 8 : return MempoolAcceptResult::Failure(ws.m_state);
1367 : : }
1368 : : }
1369 : :
1370 : : // Perform the inexpensive checks first and avoid hashing and signature verification unless
1371 : : // those checks pass, to mitigate CPU exhaustion denial-of-service attacks.
1372 [ + - + + : 49678 : if (!PolicyScriptChecks(ws)) return MempoolAcceptResult::Failure(ws.m_state);
+ - + - ]
1373 : :
1374 [ + - - + : 46182 : if (!ConsensusScriptChecks(ws)) return MempoolAcceptResult::Failure(ws.m_state);
- - - - ]
1375 : :
1376 [ + - ]: 46182 : const CFeeRate effective_feerate{ws.m_modified_fees, static_cast<int32_t>(ws.m_vsize)};
1377 : : // Tx was accepted, but not added
1378 [ + + ]: 46182 : if (args.m_test_accept) {
1379 : 17832 : return MempoolAcceptResult::Success(std::move(m_subpackage.m_replaced_transactions), ws.m_vsize,
1380 [ + - ]: 17832 : ws.m_base_fees, effective_feerate, single_wtxid);
1381 : : }
1382 : :
1383 [ + - ]: 28350 : FinalizeSubpackage(args);
1384 : :
1385 : : // Limit the mempool, if appropriate.
1386 [ + + + + ]: 28350 : if (!args.m_package_submission && !args.m_bypass_limits) {
1387 [ + - + - ]: 27410 : LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip());
1388 : : // If mempool contents change, then the m_view cache is dirty. Given this isn't a package
1389 : : // submission, we won't be using the cache anymore, but clear it anyway for clarity.
1390 [ + - ]: 27410 : CleanupTemporaryCoins();
1391 : :
1392 [ + - - + ]: 27410 : if (!m_pool.exists(ws.m_hash)) {
1393 : : // The tx no longer meets our (new) mempool minimum feerate but could be reconsidered in a package.
1394 [ # # # # : 0 : ws.m_state.Invalid(TxValidationResult::TX_RECONSIDERABLE, "mempool full");
# # ]
1395 [ # # # # : 0 : return MempoolAcceptResult::FeeFailure(ws.m_state, CFeeRate(ws.m_modified_fees, ws.m_vsize), {ws.m_ptx->GetWitnessHash()});
# # ]
1396 : : }
1397 : : }
1398 : :
1399 [ + - ]: 28350 : if (m_pool.m_opts.signals) {
1400 [ + - ]: 28350 : const CTransaction& tx = *ws.m_ptx;
1401 [ + - ]: 28350 : auto iter = m_pool.GetIter(tx.GetHash());
1402 [ + - ]: 28350 : Assume(iter.has_value());
1403 : 28350 : const auto tx_info = NewMempoolTransactionInfo(ws.m_ptx, ws.m_base_fees,
1404 [ + - ]: 28350 : ws.m_vsize, (*iter)->GetHeight(),
1405 : 28350 : args.m_bypass_limits, args.m_package_submission,
1406 : 28350 : IsCurrentForFeeEstimation(m_active_chainstate),
1407 [ + - + - ]: 56700 : m_pool.HasNoInputsOf(tx));
1408 [ + - ]: 28350 : m_pool.m_opts.signals->TransactionAddedToMempool(tx_info, m_pool.GetAndIncrementSequence());
1409 : 28350 : }
1410 : :
1411 [ + + ]: 28350 : if (!m_subpackage.m_replaced_transactions.empty()) {
1412 [ + - + - : 923 : LogDebug(BCLog::MEMPOOL, "replaced %u mempool transactions with 1 new transaction for %s additional fees, %d delta bytes\n",
+ - ]
1413 : : m_subpackage.m_replaced_transactions.size(),
1414 : : ws.m_modified_fees - m_subpackage.m_conflicting_fees,
1415 : : ws.m_vsize - static_cast<int>(m_subpackage.m_conflicting_size));
1416 : : }
1417 : :
1418 : 28350 : return MempoolAcceptResult::Success(std::move(m_subpackage.m_replaced_transactions), ws.m_vsize, ws.m_base_fees,
1419 [ + - ]: 55942 : effective_feerate, single_wtxid);
1420 [ + - + - ]: 148974 : }
1421 : :
1422 : 177 : PackageMempoolAcceptResult MemPoolAccept::AcceptMultipleTransactionsInternal(const std::vector<CTransactionRef>& txns, ATMPArgs& args)
1423 : : {
1424 : 177 : AssertLockHeld(cs_main);
1425 : 177 : AssertLockHeld(m_pool.cs);
1426 : :
1427 : : // These context-free package limits can be done before taking the mempool lock.
1428 [ + - ]: 177 : PackageValidationState package_state;
1429 [ + - + + : 189 : if (!IsWellFormedPackage(txns, package_state)) return PackageMempoolAcceptResult(package_state, {});
+ - + - ]
1430 : :
1431 : 171 : std::vector<Workspace> workspaces{};
1432 [ - + + - ]: 171 : workspaces.reserve(txns.size());
1433 [ + - ]: 171 : std::transform(txns.cbegin(), txns.cend(), std::back_inserter(workspaces),
1434 : 828 : [](const auto& tx) { return Workspace(tx); });
1435 : 171 : std::map<Wtxid, MempoolAcceptResult> results;
1436 : :
1437 : : // Do all PreChecks first and fail fast to avoid running expensive script checks when unnecessary.
1438 [ + + ]: 954 : for (Workspace& ws : workspaces) {
1439 [ + - + + ]: 796 : if (!PreChecks(args, ws)) {
1440 [ + - + - : 24 : package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
+ - ]
1441 : : // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
1442 [ + - + - : 12 : results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
+ - ]
1443 [ + - + - ]: 36 : return PackageMempoolAcceptResult(package_state, std::move(results));
1444 : : }
1445 : :
1446 : : // Individual modified feerate exceeded caller-defined max; abort
1447 : : // N.B. this doesn't take into account CPFPs. Chunk-aware validation may be more robust.
1448 [ + + + - : 784 : if (args.m_client_maxfeerate && CFeeRate(ws.m_modified_fees, ws.m_vsize) > args.m_client_maxfeerate.value()) {
+ + ]
1449 : : // Need to set failure here both individually and at package level
1450 [ + - + - : 2 : ws.m_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "max feerate exceeded", "");
+ - ]
1451 [ + - + - : 2 : package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
+ - ]
1452 : : // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
1453 [ + - + - : 1 : results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
+ - ]
1454 [ + - + - ]: 3 : return PackageMempoolAcceptResult(package_state, std::move(results));
1455 : : }
1456 : :
1457 : : // Make the coins created by this transaction available for subsequent transactions in the
1458 : : // package to spend. If there are no conflicts within the package, no transaction can spend a coin
1459 : : // needed by another transaction in the package. We also need to make sure that no package
1460 : : // tx replaces (or replaces the ancestor of) the parent of another package tx. As long as we
1461 : : // check these two things, we don't need to track the coins spent.
1462 : : // If a package tx conflicts with a mempool tx, PackageRBFChecks() ensures later that any package RBF attempt
1463 : : // has *no* in-mempool ancestors, so we don't have to worry about subsequent transactions in
1464 : : // same package spending the same in-mempool outpoints. This needs to be revisited for general
1465 : : // package RBF.
1466 [ + - ]: 783 : m_viewmempool.PackageAddTransaction(ws.m_ptx);
1467 : : }
1468 : :
1469 : : // At this point we have all in-mempool parents, and we know every transaction's vsize.
1470 : : // Run the TRUC checks on the package.
1471 [ + + ]: 917 : for (Workspace& ws : workspaces) {
1472 [ + - + + ]: 769 : if (auto err{PackageTRUCChecks(m_pool, ws.m_ptx, ws.m_vsize, txns, ws.m_parents)}) {
1473 [ + - + - ]: 10 : package_state.Invalid(PackageValidationResult::PCKG_POLICY, "TRUC-violation", err.value());
1474 [ + - + - ]: 30 : return PackageMempoolAcceptResult(package_state, {});
1475 : 769 : }
1476 : : }
1477 : :
1478 : : // Transactions must meet two minimum feerates: the mempool minimum fee and min relay fee.
1479 : : // For transactions consisting of exactly one child and its parents, it suffices to use the
1480 : : // package feerate (total modified fees / total virtual size) to check this requirement.
1481 : : // Note that this is an aggregate feerate; this function has not checked that there are transactions
1482 : : // too low feerate to pay for themselves, or that the child transactions are higher feerate than
1483 : : // their parents. Using aggregate feerate may allow "parents pay for child" behavior and permit
1484 : : // a child that is below mempool minimum feerate. To avoid these behaviors, callers of
1485 : : // AcceptMultipleTransactions need to restrict txns topology (e.g. to ancestor sets) and check
1486 : : // the feerates of individuals and subsets.
1487 : 148 : m_subpackage.m_total_vsize = std::accumulate(workspaces.cbegin(), workspaces.cend(), int64_t{0},
1488 : 750 : [](int64_t sum, auto& ws) { return sum + ws.m_vsize; });
1489 : 148 : m_subpackage.m_total_modified_fees = std::accumulate(workspaces.cbegin(), workspaces.cend(), CAmount{0},
1490 : 750 : [](CAmount sum, auto& ws) { return sum + ws.m_modified_fees; });
1491 [ + - ]: 148 : const CFeeRate package_feerate(m_subpackage.m_total_modified_fees, m_subpackage.m_total_vsize);
1492 : 148 : std::vector<Wtxid> all_package_wtxids;
1493 [ - + + - ]: 148 : all_package_wtxids.reserve(workspaces.size());
1494 [ + - ]: 148 : std::transform(workspaces.cbegin(), workspaces.cend(), std::back_inserter(all_package_wtxids),
1495 : 750 : [](const auto& ws) { return ws.m_ptx->GetWitnessHash(); });
1496 [ + + ]: 148 : TxValidationState placeholder_state;
1497 [ + + + + ]: 239 : if (args.m_package_feerates &&
1498 [ + - ]: 91 : !CheckFeeRate(m_subpackage.m_total_vsize, m_subpackage.m_total_modified_fees, placeholder_state)) {
1499 [ + - + - : 24 : package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
+ - ]
1500 [ + - ]: 12 : return PackageMempoolAcceptResult(package_state, {{workspaces.back().m_ptx->GetWitnessHash(),
1501 [ + - + - : 84 : MempoolAcceptResult::FeeFailure(placeholder_state, CFeeRate(m_subpackage.m_total_modified_fees, m_subpackage.m_total_vsize), all_package_wtxids)}});
+ - + + -
- ]
1502 : : }
1503 : :
1504 : : // Apply package mempool RBF checks.
1505 [ + + + - : 136 : if (m_subpackage.m_rbf && !PackageRBFChecks(txns, workspaces, package_state)) {
+ + ]
1506 [ + - + - ]: 24 : return PackageMempoolAcceptResult(package_state, std::move(results));
1507 : : }
1508 : :
1509 : : // Check if the transactions would exceed the cluster size limit.
1510 [ + - + + ]: 128 : if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1511 [ + - + - : 14 : package_state.Invalid(PackageValidationResult::PCKG_POLICY, "too-large-cluster", "");
+ - ]
1512 [ + - + - ]: 21 : return PackageMempoolAcceptResult(package_state, std::move(results));
1513 : : }
1514 : :
1515 : : // Now that we've bounded the resulting possible ancestry count, check package for dust spends
1516 [ + - ]: 121 : if (m_pool.m_opts.require_standard) {
1517 [ + - ]: 121 : TxValidationState child_state;
1518 [ + - ]: 121 : Wtxid child_wtxid;
1519 [ + - + + ]: 121 : if (!CheckEphemeralSpends(txns, m_pool.m_opts.dust_relay_feerate, m_pool, child_state, child_wtxid)) {
1520 [ + - + - : 2 : package_state.Invalid(PackageValidationResult::PCKG_TX, "unspent-dust");
+ - ]
1521 [ + - + - : 1 : results.emplace(child_wtxid, MempoolAcceptResult::Failure(child_state));
+ - ]
1522 [ + - + - ]: 3 : return PackageMempoolAcceptResult(package_state, std::move(results));
1523 : : }
1524 : 121 : }
1525 : :
1526 [ + + ]: 778 : for (Workspace& ws : workspaces) {
1527 : 660 : ws.m_package_feerate = package_feerate;
1528 [ + - + + ]: 660 : if (!PolicyScriptChecks(ws)) {
1529 : : // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
1530 [ + - + - : 4 : package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
+ - ]
1531 [ + - + - : 2 : results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
+ - ]
1532 [ + - + - ]: 6 : return PackageMempoolAcceptResult(package_state, std::move(results));
1533 : : }
1534 [ + + ]: 658 : if (args.m_test_accept) {
1535 [ - + ]: 519 : const auto effective_feerate = args.m_package_feerates ? ws.m_package_feerate :
1536 [ + - ]: 519 : CFeeRate{ws.m_modified_fees, static_cast<int32_t>(ws.m_vsize)};
1537 [ - + ]: 519 : const auto effective_feerate_wtxids = args.m_package_feerates ? all_package_wtxids :
1538 [ - - + - ]: 519 : std::vector<Wtxid>{ws.m_ptx->GetWitnessHash()};
1539 : 1038 : results.emplace(ws.m_ptx->GetWitnessHash(),
1540 [ + - + - ]: 519 : MempoolAcceptResult::Success(std::move(m_subpackage.m_replaced_transactions),
1541 : : ws.m_vsize, ws.m_base_fees, effective_feerate,
1542 : : effective_feerate_wtxids));
1543 : 519 : }
1544 : : }
1545 : :
1546 [ + + + - : 216 : if (args.m_test_accept) return PackageMempoolAcceptResult(package_state, std::move(results));
+ - ]
1547 : :
1548 [ + - - + ]: 69 : if (!SubmitPackage(args, workspaces, package_state, results)) {
1549 : : // PackageValidationState filled in by SubmitPackage().
1550 [ # # # # ]: 0 : return PackageMempoolAcceptResult(package_state, std::move(results));
1551 : : }
1552 : :
1553 [ + - + - ]: 207 : return PackageMempoolAcceptResult(package_state, std::move(results));
1554 [ + - ]: 508 : }
1555 : :
1556 : 83698 : void MemPoolAccept::CleanupTemporaryCoins()
1557 : : {
1558 : : // There are 3 kinds of coins in m_view:
1559 : : // (1) Temporary coins from the transactions in subpackage, constructed by m_viewmempool.
1560 : : // (2) Mempool coins from transactions in the mempool, constructed by m_viewmempool.
1561 : : // (3) Confirmed coins fetched from our current UTXO set.
1562 : : //
1563 : : // (1) Temporary coins need to be removed, regardless of whether the transaction was submitted.
1564 : : // If the transaction was submitted to the mempool, m_viewmempool will be able to fetch them from
1565 : : // there. If it wasn't submitted to mempool, it is incorrect to keep them - future calls may try
1566 : : // to spend those coins that don't actually exist.
1567 : : // (2) Mempool coins also need to be removed. If the mempool contents have changed as a result
1568 : : // of submitting or replacing transactions, coins previously fetched from mempool may now be
1569 : : // spent or nonexistent. Those coins need to be deleted from m_view.
1570 : : // (3) Confirmed coins don't need to be removed. The chainstate has not changed (we are
1571 : : // holding cs_main and no blocks have been processed) so the confirmed tx cannot disappear like
1572 : : // a mempool tx can. The coin may now be spent after we submitted a tx to mempool, but
1573 : : // we have already checked that the package does not have 2 transactions spending the same coin
1574 : : // and we check whether a mempool transaction spends conflicting coins (CTxMemPool::GetConflictTx).
1575 : : // Keeping them in m_view is an optimization to not re-fetch confirmed coins if we later look up
1576 : : // inputs for this transaction again.
1577 [ + + ]: 92499 : for (const auto& outpoint : m_viewmempool.GetNonBaseCoins()) {
1578 : : // In addition to resetting m_viewmempool, we also need to manually delete these coins from
1579 : : // m_view because it caches copies of the coins it fetched from m_viewmempool previously.
1580 : 8801 : m_view.Uncache(outpoint);
1581 : : }
1582 : : // This deletes the temporary and mempool coins.
1583 : 83698 : m_viewmempool.Reset();
1584 : 83698 : }
1585 : :
1586 : 479 : PackageMempoolAcceptResult MemPoolAccept::AcceptSubPackage(const std::vector<CTransactionRef>& subpackage, ATMPArgs& args)
1587 : : {
1588 : 479 : AssertLockHeld(::cs_main);
1589 : 479 : AssertLockHeld(m_pool.cs);
1590 : 958 : auto result = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_pool.cs) {
1591 [ - + + + ]: 479 : if (subpackage.size() > 1) {
1592 : 99 : return AcceptMultipleTransactionsInternal(subpackage, args);
1593 : : }
1594 : 380 : const auto& tx = subpackage.front();
1595 : 380 : ATMPArgs single_args = ATMPArgs::SingleInPackageAccept(args);
1596 : 380 : const auto single_res = AcceptSingleTransactionInternal(tx, single_args);
1597 [ + + ]: 380 : PackageValidationState package_state_wrapped;
1598 [ + + ]: 380 : if (single_res.m_result_type != MempoolAcceptResult::ResultType::VALID) {
1599 [ + - + - : 466 : package_state_wrapped.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
+ - ]
1600 : : }
1601 [ + - + + : 1520 : return PackageMempoolAcceptResult(package_state_wrapped, {{tx->GetWitnessHash(), single_res}});
- - ]
1602 [ + - + - ]: 1619 : }();
1603 : :
1604 : : // Clean up m_view and m_viewmempool so that other subpackage evaluations don't have access to
1605 : : // coins they shouldn't. Keep some coins in order to minimize re-fetching coins from the UTXO set.
1606 : : // Clean up package feerate and rbf calculations
1607 [ + - ]: 479 : ClearSubPackageState();
1608 : :
1609 : 479 : return result;
1610 : 0 : }
1611 : :
1612 : 173 : PackageMempoolAcceptResult MemPoolAccept::AcceptPackage(const Package& package, ATMPArgs& args)
1613 : : {
1614 : 173 : Assert(!package.empty());
1615 : 173 : AssertLockHeld(cs_main);
1616 : : // Used if returning a PackageMempoolAcceptResult directly from this function.
1617 [ + - ]: 173 : PackageValidationState package_state_quit_early;
1618 : :
1619 : : // There are two topologies we are able to handle through this function:
1620 : : // (1) A single transaction
1621 : : // (2) A child-with-parents package.
1622 : : // Check that the package is well-formed. If it isn't, we won't try to validate any of the
1623 : : // transactions and thus won't return any MempoolAcceptResults, just a package-wide error.
1624 : :
1625 : : // Context-free package checks.
1626 [ + - + + ]: 173 : if (!IsWellFormedPackage(package, package_state_quit_early)) {
1627 [ + - + - ]: 6 : return PackageMempoolAcceptResult(package_state_quit_early, {});
1628 : : }
1629 : :
1630 [ - + + + : 171 : if (package.size() > 1 && !IsChildWithParents(package)) {
+ - + + ]
1631 : : // All transactions in the package must be a parent of the last transaction. This is just an
1632 : : // opportunity for us to fail fast on a context-free check without taking the mempool lock.
1633 [ + - + - : 4 : package_state_quit_early.Invalid(PackageValidationResult::PCKG_POLICY, "package-not-child-with-parents");
+ - ]
1634 [ + - + - ]: 6 : return PackageMempoolAcceptResult(package_state_quit_early, {});
1635 : : }
1636 : :
1637 [ + - ]: 169 : LOCK(m_pool.cs);
1638 : : // Stores results from which we will create the returned PackageMempoolAcceptResult.
1639 : : // A result may be changed if a mempool transaction is evicted later due to LimitMempoolSize().
1640 : 169 : std::map<Wtxid, MempoolAcceptResult> results_final;
1641 : : // Results from individual validation which will be returned if no other result is available for
1642 : : // this transaction. "Nonfinal" because if a transaction fails by itself but succeeds later
1643 : : // (i.e. when evaluated with a fee-bumping child), the result in this map may be discarded.
1644 : 169 : std::map<Wtxid, MempoolAcceptResult> individual_results_nonfinal;
1645 : : // Tracks whether we think package submission could result in successful entry to the mempool
1646 : 169 : bool quit_early{false};
1647 : 169 : std::vector<CTransactionRef> txns_package_eval;
1648 [ + + ]: 648 : for (const auto& tx : package) {
1649 [ + - ]: 479 : const auto& wtxid = tx->GetWitnessHash();
1650 [ + - ]: 479 : const auto& txid = tx->GetHash();
1651 : : // There are 3 possibilities: already in mempool, same-txid-diff-wtxid already in mempool,
1652 : : // or not in mempool. An already confirmed tx is treated as one not in mempool, because all
1653 : : // we know is that the inputs aren't available.
1654 [ + - + + ]: 479 : if (m_pool.exists(wtxid)) {
1655 : : // Exact transaction already exists in the mempool.
1656 : : // Node operators are free to set their mempool policies however they please, nodes may receive
1657 : : // transactions in different orders, and malicious counterparties may try to take advantage of
1658 : : // policy differences to pin or delay propagation of transactions. As such, it's possible for
1659 : : // some package transaction(s) to already be in the mempool, and we don't want to reject the
1660 : : // entire package in that case (as that could be a censorship vector). De-duplicate the
1661 : : // transactions that are already in the mempool, and only call AcceptMultipleTransactions() with
1662 : : // the new transactions. This ensures we don't double-count transaction counts and sizes when
1663 : : // checking ancestor/descendant limits, or double-count transaction fees for fee-related policy.
1664 [ + - + - ]: 97 : const auto& entry{*Assert(m_pool.GetEntry(txid))};
1665 [ + - + - ]: 97 : results_final.emplace(wtxid, MempoolAcceptResult::MempoolTx(entry.GetTxSize(), entry.GetFee()));
1666 [ + - + + ]: 382 : } else if (m_pool.exists(txid)) {
1667 : : // Transaction with the same non-witness data but different witness (same txid,
1668 : : // different wtxid) already exists in the mempool.
1669 : : //
1670 : : // We don't allow replacement transactions right now, so just swap the package
1671 : : // transaction for the mempool one. Note that we are ignoring the validity of the
1672 : : // package transaction passed in.
1673 : : // TODO: allow witness replacement in packages.
1674 [ + - + - ]: 4 : const auto& entry{*Assert(m_pool.GetEntry(txid))};
1675 : : // Provide the wtxid of the mempool tx so that the caller can look it up in the mempool.
1676 [ + - ]: 4 : results_final.emplace(wtxid, MempoolAcceptResult::MempoolTxDifferentWitness(entry.GetTx().GetWitnessHash()));
1677 : : } else {
1678 : : // Transaction does not already exist in the mempool.
1679 : : // Try submitting the transaction on its own.
1680 [ + - + + : 756 : const auto single_package_res = AcceptSubPackage({tx}, args);
+ - - - -
- ]
1681 [ + - ]: 378 : const auto& single_res = single_package_res.m_tx_results.at(wtxid);
1682 [ + + ]: 378 : if (single_res.m_result_type == MempoolAcceptResult::ResultType::VALID) {
1683 : : // The transaction succeeded on its own and is now in the mempool. Don't include it
1684 : : // in package validation, because its fees should only be "used" once.
1685 [ + - - + ]: 147 : assert(m_pool.exists(wtxid));
1686 [ + - ]: 147 : results_final.emplace(wtxid, single_res);
1687 [ - + + + : 231 : } else if (package.size() == 1 || // If there is only one transaction, no need to retry it "as a package"
+ + ]
1688 [ + + ]: 230 : (single_res.m_state.GetResult() != TxValidationResult::TX_RECONSIDERABLE &&
1689 [ + + ]: 128 : single_res.m_state.GetResult() != TxValidationResult::TX_MISSING_INPUTS)) {
1690 : : // Package validation policy only differs from individual policy in its evaluation
1691 : : // of feerate. For example, if a transaction fails here due to violation of a
1692 : : // consensus rule, the result will not change when it is submitted as part of a
1693 : : // package. To minimize the amount of repeated work, unless the transaction fails
1694 : : // due to feerate or missing inputs (its parent is a previous transaction in the
1695 : : // package that failed due to feerate), don't run package validation. Note that this
1696 : : // decision might not make sense if different types of packages are allowed in the
1697 : : // future. Continue individually validating the rest of the transactions, because
1698 : : // some of them may still be valid.
1699 : 21 : quit_early = true;
1700 [ + - + - : 42 : package_state_quit_early.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
+ - ]
1701 [ + - ]: 21 : individual_results_nonfinal.emplace(wtxid, single_res);
1702 : : } else {
1703 [ + - ]: 210 : individual_results_nonfinal.emplace(wtxid, single_res);
1704 [ + - ]: 210 : txns_package_eval.push_back(tx);
1705 : : }
1706 : 378 : }
1707 : : }
1708 : :
1709 [ + + + + : 406 : auto multi_submission_result = quit_early || txns_package_eval.empty() ? PackageMempoolAcceptResult(package_state_quit_early, {}) :
+ - + + -
- ]
1710 [ + - + - : 237 : AcceptSubPackage(txns_package_eval, args);
+ - ]
1711 : 169 : PackageValidationState& package_state_final = multi_submission_result.m_state;
1712 : :
1713 : : // This is invoked by AcceptSubPackage() already, so this is just here for
1714 : : // clarity (since it's not permitted to invoke LimitMempoolSize() while a
1715 : : // changeset is outstanding).
1716 [ + - ]: 169 : ClearSubPackageState();
1717 : :
1718 : : // Make sure we haven't exceeded max mempool size.
1719 : : // Package transactions that were submitted to mempool or already in mempool may be evicted.
1720 : : // If mempool contents change, then the m_view cache is dirty. It has already been cleared above.
1721 [ + - + - ]: 169 : LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip());
1722 : :
1723 [ + + ]: 648 : for (const auto& tx : package) {
1724 : 479 : const auto& wtxid = tx->GetWitnessHash();
1725 [ + + ]: 479 : if (multi_submission_result.m_tx_results.contains(wtxid)) {
1726 : : // We shouldn't have re-submitted if the tx result was already in results_final.
1727 [ + - ]: 158 : Assume(!results_final.contains(wtxid));
1728 : : // If it was submitted, check to see if the tx is still in the mempool. It could have
1729 : : // been evicted due to LimitMempoolSize() above.
1730 [ + - ]: 158 : const auto& txresult = multi_submission_result.m_tx_results.at(wtxid);
1731 [ + + + - : 158 : if (txresult.m_result_type == MempoolAcceptResult::ResultType::VALID && !m_pool.exists(wtxid)) {
+ + ]
1732 [ + - + - : 4 : package_state_final.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
+ - ]
1733 [ + - ]: 2 : TxValidationState mempool_full_state;
1734 [ + - + - : 4 : mempool_full_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
+ - ]
1735 [ + - + - : 4 : results_final.emplace(wtxid, MempoolAcceptResult::Failure(mempool_full_state));
+ - ]
1736 : 2 : } else {
1737 [ + - ]: 156 : results_final.emplace(wtxid, txresult);
1738 : : }
1739 [ + + ]: 321 : } else if (const auto it{results_final.find(wtxid)}; it != results_final.end()) {
1740 : : // Already-in-mempool transaction. Check to see if it's still there, as it could have
1741 : : // been evicted when LimitMempoolSize() was called.
1742 : 248 : Assume(it->second.m_result_type != MempoolAcceptResult::ResultType::INVALID);
1743 [ + - ]: 248 : Assume(!individual_results_nonfinal.contains(wtxid));
1744 : : // Query by txid to include the same-txid-different-witness ones.
1745 [ + - - + ]: 248 : if (!m_pool.exists(tx->GetHash())) {
1746 [ # # # # : 0 : package_state_final.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
# # ]
1747 [ # # ]: 0 : TxValidationState mempool_full_state;
1748 [ # # # # : 0 : mempool_full_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
# # ]
1749 : : // Replace the previous result.
1750 : 0 : results_final.erase(wtxid);
1751 [ # # # # : 0 : results_final.emplace(wtxid, MempoolAcceptResult::Failure(mempool_full_state));
# # ]
1752 : 0 : }
1753 [ + - ]: 73 : } else if (const auto it{individual_results_nonfinal.find(wtxid)}; it != individual_results_nonfinal.end()) {
1754 [ + - ]: 73 : Assume(it->second.m_result_type == MempoolAcceptResult::ResultType::INVALID);
1755 : : // Interesting result from previous processing.
1756 [ + - ]: 73 : results_final.emplace(wtxid, it->second);
1757 : : }
1758 : : }
1759 [ - + + - ]: 169 : Assume(results_final.size() == package.size());
1760 [ + - + - ]: 338 : return PackageMempoolAcceptResult(package_state_final, std::move(results_final));
1761 [ + - + - : 1267 : }
+ - ]
1762 : :
1763 : : } // anon namespace
1764 : :
1765 : 55562 : MempoolAcceptResult AcceptToMemoryPool(Chainstate& active_chainstate, const CTransactionRef& tx,
1766 : : int64_t accept_time, bool bypass_limits, bool test_accept)
1767 : : {
1768 : 55562 : AssertLockHeld(::cs_main);
1769 [ - + ]: 55562 : assert(active_chainstate.GetMempool() != nullptr);
1770 : 55562 : CTxMemPool& pool{*active_chainstate.GetMempool()};
1771 : :
1772 : 55562 : std::vector<COutPoint> coins_to_uncache;
1773 : :
1774 : 55562 : auto args = MemPoolAccept::ATMPArgs::SingleAccept(accept_time, bypass_limits, coins_to_uncache, test_accept);
1775 [ + - + - ]: 55562 : MempoolAcceptResult result = MemPoolAccept(pool, active_chainstate).AcceptSingleTransactionAndCleanup(tx, args);
1776 : :
1777 [ + + ]: 55562 : if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {
1778 : : // Remove coins that were not present in the coins cache before calling
1779 : : // AcceptSingleTransaction(); this is to prevent memory DoS in case we receive a large
1780 : : // number of invalid transactions that attempt to overrun the in-memory coins cache
1781 : : // (`CCoinsViewCache::cacheCoins`).
1782 : :
1783 [ + + ]: 11185 : for (const COutPoint& hashTx : coins_to_uncache)
1784 [ + - + - ]: 1658 : active_chainstate.CoinsTip().Uncache(hashTx);
1785 : : TRACEPOINT(mempool, rejected,
1786 : : tx->GetHash().data(),
1787 : : result.m_state.GetRejectReason().c_str()
1788 : : );
1789 : : }
1790 : : // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
1791 [ + - ]: 55562 : BlockValidationState state_dummy;
1792 [ + - ]: 55562 : active_chainstate.FlushStateToDisk(state_dummy, FlushStateMode::PERIODIC);
1793 : 55562 : return result;
1794 : 55562 : }
1795 : :
1796 : 251 : PackageMempoolAcceptResult ProcessNewPackage(Chainstate& active_chainstate, CTxMemPool& pool,
1797 : : const Package& package, bool test_accept, const std::optional<CFeeRate>& client_maxfeerate)
1798 : : {
1799 : 251 : AssertLockHeld(cs_main);
1800 [ - + ]: 251 : assert(!package.empty());
1801 [ + - - + ]: 1413 : assert(std::all_of(package.cbegin(), package.cend(), [](const auto& tx){return tx != nullptr;}));
1802 : :
1803 : 251 : std::vector<COutPoint> coins_to_uncache;
1804 : 502 : auto result = [&]() EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
1805 : 251 : AssertLockHeld(cs_main);
1806 [ + + ]: 251 : if (test_accept) {
1807 : 78 : auto args = MemPoolAccept::ATMPArgs::PackageTestAccept(GetTime(), coins_to_uncache);
1808 [ + - ]: 78 : return MemPoolAccept(pool, active_chainstate).AcceptMultipleTransactionsAndCleanup(package, args);
1809 : : } else {
1810 : 173 : auto args = MemPoolAccept::ATMPArgs::PackageChildWithParents(GetTime(), coins_to_uncache, client_maxfeerate);
1811 [ + - ]: 173 : return MemPoolAccept(pool, active_chainstate).AcceptPackage(package, args);
1812 : : }
1813 [ + - ]: 251 : }();
1814 : :
1815 : : // Uncache coins pertaining to transactions that were not submitted to the mempool.
1816 [ + + + + ]: 251 : if (test_accept || result.m_state.IsInvalid()) {
1817 [ + + ]: 900 : for (const COutPoint& hashTx : coins_to_uncache) {
1818 [ + - + - ]: 764 : active_chainstate.CoinsTip().Uncache(hashTx);
1819 : : }
1820 : : }
1821 : : // Ensure the coins cache is still within limits.
1822 [ + - ]: 251 : BlockValidationState state_dummy;
1823 [ + - ]: 251 : active_chainstate.FlushStateToDisk(state_dummy, FlushStateMode::PERIODIC);
1824 : 251 : return result;
1825 : 251 : }
1826 : :
1827 : 258048 : CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1828 : : {
1829 : 258048 : int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1830 : : // Force block reward to zero when right shift is undefined.
1831 [ + + ]: 258048 : if (halvings >= 64)
1832 : : return 0;
1833 : :
1834 : 257485 : CAmount nSubsidy = 50 * COIN;
1835 : : // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1836 : 257485 : nSubsidy >>= halvings;
1837 : 257485 : return nSubsidy;
1838 : : }
1839 : :
1840 : 1448 : CoinsViews::CoinsViews(DBParams db_params, CoinsViewOptions options)
1841 [ + + ]: 1450 : : m_dbview{std::move(db_params), std::move(options)},
1842 [ + - ]: 1446 : m_catcherview(&m_dbview) {}
1843 : :
1844 : 1446 : void CoinsViews::InitCache(int32_t prevoutfetch_threads)
1845 : : {
1846 : 1446 : AssertLockHeld(::cs_main);
1847 : 1446 : m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
1848 : 1446 : auto thread_pool{util::MakeNotNullShared<ThreadPool>("prevout")};
1849 [ + + ]: 1446 : if (prevoutfetch_threads > 0) {
1850 [ + - ]: 1439 : thread_pool->Start(prevoutfetch_threads);
1851 [ + - ]: 1439 : LogInfo("Block input prevout fetching uses %d additional threads", prevoutfetch_threads);
1852 : : }
1853 [ + - - + ]: 1446 : m_connect_block_view = std::make_unique<CoinsViewOverlay>(&*m_cacheview, std::move(thread_pool));
1854 : 1446 : }
1855 : :
1856 : 1491 : Chainstate::Chainstate(
1857 : : CTxMemPool* mempool,
1858 : : BlockManager& blockman,
1859 : : ChainstateManager& chainman,
1860 : 1491 : std::optional<uint256> from_snapshot_blockhash)
1861 [ + + ]: 1491 : : m_mempool(mempool),
1862 : 1491 : m_blockman(blockman),
1863 [ + + ]: 1491 : m_chainman(chainman),
1864 [ + + ]: 1491 : m_assumeutxo(from_snapshot_blockhash ? Assumeutxo::UNVALIDATED : Assumeutxo::VALIDATED),
1865 [ + + ]: 1491 : m_from_snapshot_blockhash(from_snapshot_blockhash) {}
1866 : :
1867 : 1478 : fs::path Chainstate::StoragePath() const
1868 : : {
1869 [ + - ]: 2956 : fs::path path{m_chainman.m_options.datadir / "chainstate"};
1870 [ + + ]: 1478 : if (m_from_snapshot_blockhash) {
1871 [ + - ]: 69 : path += node::SNAPSHOT_CHAINSTATE_SUFFIX;
1872 : : }
1873 : 1478 : return path;
1874 : 0 : }
1875 : :
1876 : 793151 : const CBlockIndex* Chainstate::SnapshotBase() const
1877 : : {
1878 [ + + ]: 793151 : if (!m_from_snapshot_blockhash) return nullptr;
1879 [ + + ]: 17455 : if (!m_cached_snapshot_base) m_cached_snapshot_base = Assert(m_chainman.m_blockman.LookupBlockIndex(*m_from_snapshot_blockhash));
1880 : 17455 : return m_cached_snapshot_base;
1881 : : }
1882 : :
1883 : 3265129 : const CBlockIndex* Chainstate::TargetBlock() const
1884 : : {
1885 [ + + ]: 3265129 : if (!m_target_blockhash) return nullptr;
1886 [ + + ]: 1813049 : if (!m_cached_target_block) m_cached_target_block = Assert(m_chainman.m_blockman.LookupBlockIndex(*m_target_blockhash));
1887 : 1813049 : return m_cached_target_block;
1888 : : }
1889 : :
1890 : 4 : void Chainstate::SetTargetBlock(CBlockIndex* block)
1891 : : {
1892 [ - + ]: 4 : if (block) {
1893 [ # # ]: 0 : m_target_blockhash = block->GetBlockHash();
1894 : : } else {
1895 [ + - ]: 4 : m_target_blockhash.reset();
1896 : : }
1897 : 4 : m_cached_target_block = block;
1898 : 4 : }
1899 : :
1900 : 28 : void Chainstate::SetTargetBlockHash(uint256 block_hash)
1901 : : {
1902 [ - + ]: 28 : m_target_blockhash = block_hash;
1903 : 28 : m_cached_target_block = nullptr;
1904 : 28 : }
1905 : :
1906 : 1448 : void Chainstate::InitCoinsDB(
1907 : : size_t cache_size_bytes,
1908 : : bool in_memory,
1909 : : bool should_wipe)
1910 : : {
1911 : 1446 : m_coins_views = std::make_unique<CoinsViews>(
1912 : 4344 : DBParams{
1913 : : .path = StoragePath(),
1914 : : .cache_bytes = cache_size_bytes,
1915 : : .memory_only = in_memory,
1916 : : .wipe_data = should_wipe,
1917 : : .obfuscate = true,
1918 [ + + ]: 1448 : .options = m_chainman.m_options.coins_db},
1919 : 2894 : m_chainman.m_options.coins_view);
1920 : :
1921 : 1446 : m_coinsdb_cache_size_bytes = cache_size_bytes;
1922 : 1446 : }
1923 : :
1924 : 1446 : void Chainstate::InitCoinsCache(size_t cache_size_bytes)
1925 : : {
1926 : 1446 : AssertLockHeld(::cs_main);
1927 [ - + ]: 1446 : assert(m_coins_views != nullptr);
1928 : 1446 : m_coinstip_cache_size_bytes = cache_size_bytes;
1929 : 1446 : m_coins_views->InitCache(m_chainman.m_options.prevoutfetch_threads_num);
1930 : 1446 : }
1931 : :
1932 : : // Lock-free: depends on `m_cached_is_ibd`, which is latched by `UpdateIBDStatus()`.
1933 : 2015866 : bool ChainstateManager::IsInitialBlockDownload() const noexcept
1934 : : {
1935 : 2015866 : return m_cached_is_ibd.load(std::memory_order_relaxed);
1936 : : }
1937 : :
1938 : 134533 : void Chainstate::CheckForkWarningConditions()
1939 : : {
1940 : 134533 : AssertLockHeld(cs_main);
1941 : :
1942 [ + + ]: 134533 : if (this->GetRole().historical) {
1943 : : return;
1944 : : }
1945 : :
1946 [ + + - + : 162887 : if (m_chainman.m_best_invalid && m_chainman.m_best_invalid->nChainWork > m_chain.Tip()->nChainWork + (GetBlockProof(*m_chain.Tip()) * 6)) {
- + + + ]
1947 : 372 : LogWarning("Found invalid chain more than 6 blocks longer than our best chain. This could be due to database corruption or consensus incompatibility with peers.");
1948 [ + - ]: 372 : m_chainman.GetNotifications().warningSet(
1949 : : kernel::Warning::LARGE_WORK_INVALID_CHAIN,
1950 : 744 : _("Warning: Found invalid chain more than 6 blocks longer than our best chain. This could be due to database corruption or consensus incompatibility with peers."));
1951 : : } else {
1952 : 133353 : m_chainman.GetNotifications().warningUnset(kernel::Warning::LARGE_WORK_INVALID_CHAIN);
1953 : : }
1954 : : }
1955 : :
1956 : : // Called both upon regular invalid block discovery *and* InvalidateBlock
1957 : 5726 : void Chainstate::InvalidChainFound(CBlockIndex* pindexNew)
1958 : : {
1959 : 5726 : AssertLockHeld(cs_main);
1960 [ + + + + ]: 5726 : if (!m_chainman.m_best_invalid || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork) {
1961 : 1559 : m_chainman.m_best_invalid = pindexNew;
1962 : : }
1963 : 5726 : SetBlockFailureFlags(pindexNew);
1964 [ + - + + ]: 5726 : if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindexNew->nHeight) == pindexNew) {
1965 : 2760 : m_chainman.RecalculateBestHeader();
1966 : : }
1967 : :
1968 [ + - + - : 5726 : LogInfo("%s: invalid block=%s height=%d log2_work=%f date=%s", __func__,
+ - ]
1969 : : pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1970 : : log(pindexNew->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(pindexNew->GetBlockTime()));
1971 [ - + ]: 5726 : CBlockIndex *tip = m_chain.Tip();
1972 [ - + ]: 5726 : assert (tip);
1973 [ + - - + : 5726 : LogInfo("%s: current best=%s height=%d log2_work=%f date=%s", __func__,
+ - + - ]
1974 : : tip->GetBlockHash().ToString(), m_chain.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1975 : : FormatISO8601DateTime(tip->GetBlockTime()));
1976 : 5726 : CheckForkWarningConditions();
1977 : 5726 : }
1978 : :
1979 : : // Same as InvalidChainFound, above, except not called directly from InvalidateBlock,
1980 : : // which does its own setBlockIndexCandidates management.
1981 : 2798 : void Chainstate::InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state)
1982 : : {
1983 : 2798 : AssertLockHeld(cs_main);
1984 [ + + ]: 2798 : if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
1985 : 2792 : pindex->nStatus |= BLOCK_FAILED_VALID;
1986 : 2792 : m_blockman.m_dirty_blockindex.insert(pindex);
1987 : 2792 : setBlockIndexCandidates.erase(pindex);
1988 : 2792 : InvalidChainFound(pindex);
1989 : : }
1990 : 2798 : }
1991 : :
1992 : 288536 : void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1993 : : {
1994 : : // mark inputs spent
1995 [ + + ]: 288536 : if (!tx.IsCoinBase()) {
1996 [ - + ]: 100864 : txundo.vprevout.reserve(tx.vin.size());
1997 [ + + ]: 241150 : for (const CTxIn &txin : tx.vin) {
1998 : 140286 : txundo.vprevout.emplace_back();
1999 : 140286 : bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
2000 [ - + ]: 140286 : assert(is_spent);
2001 : : }
2002 : : }
2003 : : // add outputs
2004 : 288536 : AddCoins(inputs, tx, nHeight);
2005 : 288536 : }
2006 : :
2007 : 269099 : std::optional<std::pair<ScriptError, std::string>> CScriptCheck::operator()() {
2008 [ + - ]: 269099 : const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
2009 : 269099 : const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
2010 : 269099 : ScriptError error{SCRIPT_ERR_UNKNOWN_ERROR};
2011 [ + - + + ]: 269099 : if (VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, m_flags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *m_signature_cache, *txdata), &error)) {
2012 : 222611 : return std::nullopt;
2013 : : } else {
2014 [ + - + - : 92976 : auto debug_str = strprintf("input %i of %s (wtxid %s), spending %s:%i", nIn, ptxTo->GetHash().ToString(), ptxTo->GetWitnessHash().ToString(), ptxTo->vin[nIn].prevout.hash.ToString(), ptxTo->vin[nIn].prevout.n);
+ - ]
2015 : 46488 : return std::make_pair(error, std::move(debug_str));
2016 : 46488 : }
2017 : : }
2018 : :
2019 : 1412 : ValidationCache::ValidationCache(const size_t script_execution_cache_bytes, const size_t signature_cache_bytes)
2020 [ + - ]: 1412 : : m_signature_cache{signature_cache_bytes}
2021 : : {
2022 : : // Setup the salted hasher
2023 : 1412 : uint256 nonce = GetRandHash();
2024 : : // We want the nonce to be 64 bytes long to force the hasher to process
2025 : : // this chunk, which makes later hash computations more efficient. We
2026 : : // just write our 32-byte entropy twice to fill the 64 bytes.
2027 [ + - ]: 1412 : m_script_execution_cache_hasher.Write(nonce.begin(), 32);
2028 [ + - ]: 1412 : m_script_execution_cache_hasher.Write(nonce.begin(), 32);
2029 : :
2030 [ + - + - ]: 1412 : const auto [num_elems, approx_size_bytes] = m_script_execution_cache.setup_bytes(script_execution_cache_bytes);
2031 [ + - ]: 1412 : LogInfo("Using %zu MiB out of %zu MiB requested for script execution cache, able to store %zu elements",
2032 : : approx_size_bytes >> 20, script_execution_cache_bytes >> 20, num_elems);
2033 : 1412 : }
2034 : :
2035 : : /**
2036 : : * Check whether all of this transaction's input scripts succeed.
2037 : : *
2038 : : * This involves ECDSA signature checks so can be computationally intensive. This function should
2039 : : * only be called after the cheap sanity checks in CheckTxInputs passed.
2040 : : *
2041 : : * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
2042 : : * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
2043 : : * not pushed onto pvChecks/run.
2044 : : *
2045 : : * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
2046 : : * which are matched. This is useful for checking blocks where we will likely never need the cache
2047 : : * entry again.
2048 : : */
2049 : 342308 : bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
2050 : : const CCoinsViewCache& inputs, script_verify_flags flags, CheckInputScriptsFor check_for,
2051 : : bool cacheSigStore,
2052 : : bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
2053 : : ValidationCache& validation_cache,
2054 : : std::vector<CScriptCheck>* pvChecks)
2055 : : {
2056 [ + - ]: 342308 : if (tx.IsCoinBase()) return true;
2057 : :
2058 [ + + ]: 342308 : if (pvChecks) {
2059 [ - + ]: 156644 : pvChecks->reserve(tx.vin.size());
2060 : : }
2061 : :
2062 : : // First check if script executions have been cached with the same
2063 : : // flags. Note that this assumes that the inputs provided are
2064 : : // correct (ie that the transaction hash which is in tx's prevouts
2065 : : // properly commits to the scriptPubKey in the inputs view of that
2066 : : // transaction).
2067 : 342308 : uint256 hashCacheEntry;
2068 : 342308 : CSHA256 hasher = validation_cache.ScriptExecutionCacheHasher();
2069 : 342308 : hasher.Write(UCharCast(tx.GetWitnessHash().begin()), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
2070 : 342308 : AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
2071 [ + + ]: 342308 : if (validation_cache.m_script_execution_cache.contains(hashCacheEntry, !cacheFullScriptStore)) {
2072 : : return true;
2073 : : }
2074 : :
2075 [ + + ]: 249701 : if (!txdata.m_spent_outputs_ready) {
2076 : 78927 : std::vector<CTxOut> spent_outputs;
2077 [ - + + - ]: 78927 : spent_outputs.reserve(tx.vin.size());
2078 : :
2079 [ + + ]: 196673 : for (const auto& txin : tx.vin) {
2080 : 117746 : const COutPoint& prevout = txin.prevout;
2081 [ + - ]: 117746 : const Coin& coin = inputs.AccessCoin(prevout);
2082 [ - + ]: 117746 : assert(!coin.IsSpent());
2083 [ + - ]: 117746 : spent_outputs.emplace_back(coin.out);
2084 : : }
2085 [ + - ]: 78927 : txdata.Init(tx, std::move(spent_outputs));
2086 : 78927 : }
2087 [ - + - + : 249701 : assert(txdata.m_spent_outputs.size() == tx.vin.size());
- + ]
2088 : :
2089 [ - + + + ]: 514962 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
2090 : :
2091 : : // We very carefully only pass in things to CScriptCheck which
2092 : : // are clearly committed to by tx' witness hash. This provides
2093 : : // a sanity check that our caching is not introducing consensus
2094 : : // failures through additional data in, eg, the coins being
2095 : : // spent being checked as a part of CScriptCheck.
2096 : :
2097 : : // Verify signature
2098 : 308982 : CScriptCheck check(txdata.m_spent_outputs[i], tx, validation_cache.m_signature_cache, i, flags, cacheSigStore, &txdata);
2099 [ + + ]: 308982 : if (pvChecks) {
2100 [ + - ]: 89167 : pvChecks->emplace_back(std::move(check));
2101 [ + - + + ]: 219815 : } else if (auto result = check(); result.has_value()) {
2102 : : // Tx failures never trigger disconnections/bans.
2103 : : // This is so that network splits aren't triggered
2104 : : // either due to non-consensus relay policies (such as
2105 : : // non-standard DER encodings or non-null dummy
2106 : : // arguments) or due to new consensus rules introduced in
2107 : : // soft forks.
2108 [ + + - ]: 43721 : switch (check_for) {
2109 : 43700 : case CheckInputScriptsFor::Mempool:
2110 [ + - + - : 43700 : return state.Invalid(TxValidationResult::TX_NOT_STANDARD, strprintf("mempool-script-verify-flag-failed (%s)", ScriptErrorString(result->first)), result->second);
+ - ]
2111 : 21 : case CheckInputScriptsFor::Block:
2112 [ + - + - : 21 : return state.Invalid(TxValidationResult::TX_CONSENSUS, strprintf("block-script-verify-flag-failed (%s)", ScriptErrorString(result->first)), result->second);
+ - ]
2113 : : }
2114 : 0 : AssertUnreachable();
2115 : 219815 : }
2116 : 308982 : }
2117 : :
2118 [ + + ]: 205980 : if (cacheFullScriptStore && !pvChecks) {
2119 : : // We executed all of the provided scripts, and were told to
2120 : : // cache the result. Do so now.
2121 : 84459 : validation_cache.m_script_execution_cache.insert(hashCacheEntry);
2122 : : }
2123 : :
2124 : : return true;
2125 : : }
2126 : :
2127 : 1 : bool FatalError(Notifications& notifications, BlockValidationState& state, const bilingual_str& message)
2128 : : {
2129 : 1 : notifications.fatalError(message);
2130 [ + - ]: 1 : return state.Error(message.original);
2131 : : }
2132 : :
2133 : : /**
2134 : : * Restore the UTXO in a Coin at a given COutPoint
2135 : : * @param undo The Coin to be restored.
2136 : : * @param view The coins view to which to apply the changes.
2137 : : * @param out The out point that corresponds to the tx input.
2138 : : * @return A DisconnectResult as an int
2139 : : */
2140 : 22948 : int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
2141 : : {
2142 : 22948 : bool fClean = true;
2143 : :
2144 [ + + ]: 22948 : if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
2145 : :
2146 [ - + ]: 22948 : if (undo.nHeight == 0) {
2147 : : // Missing undo metadata (height and coinbase). Older versions included this
2148 : : // information only in undo records for the last spend of a transactions'
2149 : : // outputs. This implies that it must be present for some other output of the same tx.
2150 : 0 : const Coin& alternate = AccessByTxid(view, out.hash);
2151 [ # # ]: 0 : if (!alternate.IsSpent()) {
2152 : 0 : undo.nHeight = alternate.nHeight;
2153 : 0 : undo.fCoinBase = alternate.fCoinBase;
2154 : : } else {
2155 : : return DISCONNECT_FAILED; // adding output for transaction without known metadata
2156 : : }
2157 : : }
2158 : : // If the coin already exists as an unspent coin in the cache, then the
2159 : : // possible_overwrite parameter to AddCoin must be set to true. We have
2160 : : // already checked whether an unspent coin exists above using HaveCoin, so
2161 : : // we don't need to guess. When fClean is false, an unspent coin already
2162 : : // existed and it is an overwrite.
2163 : 22948 : view.AddCoin(out, std::move(undo), !fClean);
2164 : :
2165 [ + + ]: 22948 : return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
2166 : : }
2167 : :
2168 : : /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
2169 : : * When FAILED is returned, view is left in an indeterminate state. */
2170 : 15853 : DisconnectResult Chainstate::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
2171 : : {
2172 : 15853 : AssertLockHeld(::cs_main);
2173 : 15853 : bool fClean = true;
2174 : :
2175 : 15853 : CBlockUndo blockUndo;
2176 [ + - + + ]: 15853 : if (!m_blockman.ReadBlockUndo(blockUndo, *pindex)) {
2177 [ + - ]: 1 : LogError("DisconnectBlock(): failure reading undo data\n");
2178 : : return DISCONNECT_FAILED;
2179 : : }
2180 : :
2181 [ - + - + : 15852 : if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
- + ]
2182 [ # # ]: 0 : LogError("DisconnectBlock(): block and undo data inconsistent\n");
2183 : : return DISCONNECT_FAILED;
2184 : : }
2185 : :
2186 : : // Ignore blocks that contain transactions which are 'overwritten' by later transactions,
2187 : : // unless those are already completely spent.
2188 : : // See https://github.com/bitcoin/bitcoin/issues/22596 for additional information.
2189 : : // Note: the blocks specified here are different than the ones used in ConnectBlock because DisconnectBlock
2190 : : // unwinds the blocks in reverse. As a result, the inconsistency is not discovered until the earlier
2191 : : // blocks with the duplicate coinbase transactions are disconnected.
2192 [ - + - - ]: 15852 : bool fEnforceBIP30 = !((pindex->nHeight==91722 && pindex->GetBlockHash() == uint256{"00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"}) ||
2193 [ - + - - ]: 15852 : (pindex->nHeight==91812 && pindex->GetBlockHash() == uint256{"00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"}));
2194 : :
2195 : : // undo transactions in reverse order
2196 [ - + + + ]: 45140 : for (int i = block.vtx.size() - 1; i >= 0; i--) {
2197 : 29288 : const CTransaction &tx = *(block.vtx[i]);
2198 : 29288 : Txid hash = tx.GetHash();
2199 : 29288 : bool is_coinbase = tx.IsCoinBase();
2200 : 29288 : bool is_bip30_exception = (is_coinbase && !fEnforceBIP30);
2201 : :
2202 : : // Check that all outputs are available and match the outputs in the block itself
2203 : : // exactly.
2204 [ - + + + ]: 84225 : for (size_t o = 0; o < tx.vout.size(); o++) {
2205 [ + + ]: 54937 : if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
2206 : 39699 : COutPoint out(hash, o);
2207 : 39699 : Coin coin;
2208 [ + - ]: 39699 : bool is_spent = view.SpendCoin(out, &coin);
2209 [ + - + - : 39699 : if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.IsCoinBase()) {
+ - - + ]
2210 [ # # ]: 0 : if (!is_bip30_exception) {
2211 : 0 : fClean = false; // transaction output mismatch
2212 : : }
2213 : : }
2214 : 39699 : }
2215 : : }
2216 : :
2217 : : // restore inputs
2218 [ + + ]: 29288 : if (i > 0) { // not coinbases
2219 [ - + ]: 13436 : CTxUndo &txundo = blockUndo.vtxundo[i-1];
2220 [ - + - + : 13436 : if (txundo.vprevout.size() != tx.vin.size()) {
- + ]
2221 [ - - ]: 15853 : LogError("DisconnectBlock(): transaction and undo data inconsistent\n");
2222 : : return DISCONNECT_FAILED;
2223 : : }
2224 [ + + ]: 34627 : for (unsigned int j = tx.vin.size(); j > 0;) {
2225 : 21191 : --j;
2226 [ + - ]: 21191 : const COutPoint& out = tx.vin[j].prevout;
2227 [ + - ]: 21191 : int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
2228 [ + - ]: 21191 : if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
2229 : 21191 : fClean = fClean && res != DISCONNECT_UNCLEAN;
2230 : : }
2231 : : // At this point, all of txundo.vprevout should have been moved out.
2232 : : }
2233 : : }
2234 : :
2235 : : // move best block pointer to prevout block
2236 [ + - ]: 15852 : view.SetBestBlock(pindex->pprev->GetBlockHash());
2237 : :
2238 [ - + ]: 15852 : return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
2239 : 15853 : }
2240 : :
2241 : : namespace {
2242 : : /* If STANDARD_SCRIPT_VERIFY_FLAGS doesn't cover a consensus flag,
2243 : : * MemPoolAccept::PolicyScriptChecks may accept txs that violate the
2244 : : * corresponding consensus rule, which would cause us to create invalid
2245 : : * block templates.
2246 : : */
2247 : : static_assert((CONSENSUS_SCRIPT_VERIFY_FLAGS & STANDARD_SCRIPT_VERIFY_FLAGS) == CONSENSUS_SCRIPT_VERIFY_FLAGS, "standard flags must be a superset of consensus flags");
2248 : :
2249 : : /* Check that there's no inconsistency with the policy/policy.h value */
2250 : : static_assert(CONSENSUS_SCRIPT_VERIFY_FLAGS == MANDATORY_SCRIPT_VERIFY_FLAGS);
2251 : :
2252 : : /** Helper class for building up script_verify_flags values for consensus
2253 : : * checks (particularly GetBlockScriptFlags() and
2254 : : * GetAllConsensusScriptFlags()). Designed so that flags can
2255 : : * only be added with constant expressions, and will trigger a
2256 : : * compile-time error on any attempt to include flags other than
2257 : : * CONSENSUS_SCRIPT_VERIFY_FLAGS. This approach avoids enforcing any
2258 : : * particular structure on the consensus logic that enables flags,
2259 : : * keeping flexibility for future soft forks.
2260 : : */
2261 : : class ConsensusScriptVerifyFlags
2262 : : {
2263 : : public:
2264 : : using value_type = script_verify_flags::value_type;
2265 : :
2266 : : consteval ConsensusScriptVerifyFlags(script_verify_flags flags)
2267 : : {
2268 : : if ((flags & CONSENSUS_SCRIPT_VERIFY_FLAGS) != flags) throw;
2269 : : m_value = flags.as_int();
2270 : : }
2271 : :
2272 : : consteval ConsensusScriptVerifyFlags(script_verify_flag_name flag) : ConsensusScriptVerifyFlags{script_verify_flags{flag}} { }
2273 : :
2274 : : /* Merging two sets of consensus script verify flags is fine */
2275 : 911779 : ConsensusScriptVerifyFlags& operator|=(const ConsensusScriptVerifyFlags& flags)
2276 : : {
2277 : 911779 : m_value |= flags.m_value;
2278 : 911779 : return *this;
2279 : : }
2280 : :
2281 : : /* Allow masking with generic script_verify_flags, since that
2282 : : * cannot add non-consensus flags */
2283 : 0 : ConsensusScriptVerifyFlags& operator&=(const script_verify_flags& flags)
2284 : : {
2285 : 0 : m_value &= flags.as_int();
2286 : 0 : return *this;
2287 : : }
2288 : :
2289 : 231364 : operator script_verify_flags() const
2290 : : {
2291 : 231364 : return script_verify_flags::from_int(m_value);
2292 : : }
2293 : :
2294 : : private:
2295 : : value_type m_value{0};
2296 : : };
2297 : :
2298 : : template<script_verify_flag_name VFN>
2299 : 5668 : ConsensusScriptVerifyFlags add_pending_flag(const Consensus::Params& params, auto dep)
2300 : : {
2301 [ + - ]: 5668 : if (DeploymentEnabled(params, dep)) return VFN;
2302 : 0 : return SCRIPT_VERIFY_NONE;
2303 : : }
2304 : : } // namespace
2305 : :
2306 : 1417 : script_verify_flags ChainstateManager::GetAllConsensusScriptFlags(const Consensus::Params& params)
2307 : : {
2308 : 1417 : ConsensusScriptVerifyFlags flags{SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_TAPROOT};
2309 : 1417 : flags |= add_pending_flag<SCRIPT_VERIFY_DERSIG>(params, Consensus::DEPLOYMENT_DERSIG);
2310 : 1417 : flags |= add_pending_flag<SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY>(params, Consensus::DEPLOYMENT_CLTV);
2311 : 1417 : flags |= add_pending_flag<SCRIPT_VERIFY_CHECKSEQUENCEVERIFY>(params, Consensus::DEPLOYMENT_CSV);
2312 : 1417 : flags |= add_pending_flag<SCRIPT_VERIFY_NULLDUMMY>(params, Consensus::DEPLOYMENT_SEGWIT);
2313 : :
2314 : 1417 : return flags;
2315 : : }
2316 : :
2317 : 229947 : script_verify_flags GetBlockScriptFlags(const CBlockIndex& block_index, const ChainstateManager& chainman)
2318 : : {
2319 : 229947 : const Consensus::Params& consensusparams = chainman.GetConsensus();
2320 : :
2321 : : // BIP16 didn't become active until Apr 1 2012 (on mainnet, and
2322 : : // retroactively applied to testnet)
2323 : : // However, only one historical block violated the P2SH rules (on both
2324 : : // mainnet and testnet).
2325 : : // Similarly, only one historical block violated the TAPROOT rules on
2326 : : // mainnet.
2327 : : // For simplicity, always leave P2SH+WITNESS+TAPROOT on except for the two
2328 : : // violating blocks.
2329 : 229947 : ConsensusScriptVerifyFlags flags{SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_TAPROOT};
2330 : 229947 : const auto it{consensusparams.script_flag_exceptions.find(*Assert(block_index.phashBlock))};
2331 [ - + ]: 229947 : if (it != consensusparams.script_flag_exceptions.end()) {
2332 : : // only trimming flags, not trying to enable new ones
2333 : 0 : flags &= it->second;
2334 : 0 : Assume(flags == it->second);
2335 : : }
2336 : :
2337 : : // Enforce the DERSIG (BIP66) rule
2338 [ + + ]: 229947 : if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_DERSIG)) {
2339 : 227059 : flags |= SCRIPT_VERIFY_DERSIG;
2340 : : }
2341 : :
2342 : : // Enforce CHECKLOCKTIMEVERIFY (BIP65)
2343 [ + + ]: 229947 : if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_CLTV)) {
2344 : 227450 : flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2345 : : }
2346 : :
2347 : : // Enforce CHECKSEQUENCEVERIFY (BIP112)
2348 [ + + ]: 229947 : if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_CSV)) {
2349 : 226165 : flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
2350 : : }
2351 : :
2352 : : // Enforce BIP147 NULLDUMMY (activated simultaneously with segwit)
2353 [ + + ]: 229947 : if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_SEGWIT)) {
2354 : 225437 : flags |= SCRIPT_VERIFY_NULLDUMMY;
2355 : : }
2356 : :
2357 : : // Note: flags returned from this function must also be included in
2358 : : // GetAllConsensusScriptFlags() above.
2359 : 229947 : Assume((chainman.m_all_consensus_script_flags & flags) == flags);
2360 : :
2361 : 229947 : return flags;
2362 : : }
2363 : :
2364 : :
2365 : : /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
2366 : : * Validity checks that depend on the UTXO set are also done; ConnectBlock()
2367 : : * can fail if those validity checks fail (among other reasons). */
2368 : 184064 : bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
2369 : : CCoinsViewCache& view, bool fJustCheck)
2370 : : {
2371 : 184064 : AssertLockHeld(cs_main);
2372 [ - + ]: 184064 : assert(pindex);
2373 : :
2374 : 184064 : uint256 block_hash{block.GetHash()};
2375 [ - + ]: 184064 : assert(*pindex->phashBlock == block_hash);
2376 : :
2377 : 184064 : const auto time_start{SteadyClock::now()};
2378 : 184064 : const CChainParams& params{m_chainman.GetParams()};
2379 : :
2380 : : // Check it again in case a previous version let a bad block in
2381 : : // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
2382 : : // ContextualCheckBlockHeader() here. This means that if we add a new
2383 : : // consensus rule that is enforced in one of those two functions, then we
2384 : : // may have let in a block that violates the rule prior to updating the
2385 : : // software, and we would NOT be enforcing the rule here. Fully solving
2386 : : // upgrade from one software version to the next after a consensus rule
2387 : : // change is potentially tricky and issue-specific (see NeedsRedownload()
2388 : : // for one approach that was used for BIP 141 deployment).
2389 : : // Also, currently the rule against blocks more than 2 hours in the future
2390 : : // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
2391 : : // re-enforce that rule here (at least until we make it impossible for
2392 : : // the clock to go backward).
2393 [ - + ]: 184064 : if (!CheckBlock(block, state, params.GetConsensus(), !fJustCheck, !fJustCheck)) {
2394 [ # # ]: 0 : if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED) {
2395 : : // We don't write down blocks to disk if they may have been
2396 : : // corrupted, so this should be impossible unless we're having hardware
2397 : : // problems.
2398 [ # # ]: 0 : return FatalError(m_chainman.GetNotifications(), state, _("Corrupt block found indicating potential hardware failure."));
2399 : : }
2400 [ # # ]: 0 : LogError("%s: Consensus::CheckBlock: %s\n", __func__, state.ToString());
2401 : 0 : return false;
2402 : : }
2403 : :
2404 : : // verify that the view's current state corresponds to the previous block
2405 [ + + ]: 184064 : uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
2406 [ + - ]: 184064 : assert(hashPrevBlock == view.GetBestBlock());
2407 : :
2408 : 184064 : m_chainman.num_blocks_total++;
2409 : :
2410 : : // Special case for the genesis block, skipping connection of its transactions
2411 : : // (its coinbase is unspendable)
2412 [ + + ]: 184064 : if (block_hash == params.GetConsensus().hashGenesisBlock) {
2413 [ + - ]: 532 : if (!fJustCheck)
2414 : 532 : view.SetBestBlock(pindex->GetBlockHash());
2415 : 532 : return true;
2416 : : }
2417 : :
2418 : 183532 : const char* script_check_reason;
2419 [ + + ]: 367064 : if (m_chainman.AssumedValidBlock().IsNull()) {
2420 : 178945 : script_check_reason = "assumevalid=0 (always verify)";
2421 : : } else {
2422 : 4587 : constexpr int64_t TWO_WEEKS_IN_SECONDS{60 * 60 * 24 * 7 * 2};
2423 : : // We've been configured with the hash of a block which has been externally verified to have a valid history.
2424 : : // A suitable default value is included with the software and updated from time to time. Because validity
2425 : : // relative to a piece of software is an objective fact these defaults can be easily reviewed.
2426 : : // This setting doesn't force the selection of any particular chain but makes validating some faster by
2427 : : // effectively caching the result of part of the verification.
2428 [ + + ]: 4587 : BlockMap::const_iterator it{m_blockman.m_block_index.find(m_chainman.AssumedValidBlock())};
2429 [ + + ]: 4587 : if (it == m_blockman.m_block_index.end()) {
2430 : 2280 : script_check_reason = "assumevalid hash not in headers";
2431 [ + + ]: 2307 : } else if (it->second.GetAncestor(pindex->nHeight) != pindex) {
2432 [ + + ]: 2102 : script_check_reason = (pindex->nHeight > it->second.nHeight) ? "block height above assumevalid height" : "block not in assumevalid chain";
2433 [ + + ]: 206 : } else if (m_chainman.m_best_header->GetAncestor(pindex->nHeight) != pindex) {
2434 : 1 : script_check_reason = "block not in best header chain";
2435 [ + + ]: 205 : } else if (m_chainman.m_best_header->nChainWork < m_chainman.MinimumChainWork()) {
2436 : 1 : script_check_reason = "best header chainwork below minimumchainwork";
2437 [ + + ]: 204 : } else if (GetBlockProofEquivalentTime(*m_chainman.m_best_header, *pindex, *m_chainman.m_best_header, params.GetConsensus()) <= TWO_WEEKS_IN_SECONDS) {
2438 : 102 : script_check_reason = "block too recent relative to best header";
2439 : : } else {
2440 : : // This block is a member of the assumed verified chain and an ancestor of the best header.
2441 : : // Script verification is skipped when connecting blocks under the
2442 : : // assumevalid block. Assuming the assumevalid block is valid this
2443 : : // is safe because block merkle hashes are still computed and checked,
2444 : : // Of course, if an assumed valid block is invalid due to false scriptSigs
2445 : : // this optimization would allow an invalid chain to be accepted.
2446 : : // The equivalent time check discourages hash power from extorting the network via DOS attack
2447 : : // into accepting an invalid block through telling users they must manually set assumevalid.
2448 : : // Requiring a software change or burying the invalid block, regardless of the setting, makes
2449 : : // it hard to hide the implication of the demand. This also avoids having release candidates
2450 : : // that are hardly doing any signature verification at all in testing without having to
2451 : : // artificially set the default assumed verified block further back.
2452 : : // The test against the minimum chain work prevents the skipping when denied access to any chain at
2453 : : // least as good as the expected chain.
2454 : 102 : script_check_reason = nullptr;
2455 : : }
2456 : : }
2457 : :
2458 : 183532 : const auto time_1{SteadyClock::now()};
2459 : 183532 : m_chainman.time_check += time_1 - time_start;
2460 [ + + ]: 183532 : LogDebug(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n",
2461 : : Ticks<MillisecondsDouble>(time_1 - time_start),
2462 : : Ticks<SecondsDouble>(m_chainman.time_check),
2463 : : Ticks<MillisecondsDouble>(m_chainman.time_check) / m_chainman.num_blocks_total);
2464 : :
2465 : : // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2466 : : // unless those are already completely spent.
2467 : : // If such overwrites are allowed, coinbases and transactions depending upon those
2468 : : // can be duplicated to remove the ability to spend the first instance -- even after
2469 : : // being sent to another address.
2470 : : // See BIP30, CVE-2012-1909, and https://r6.ca/blog/20120206T005236Z.html for more information.
2471 : : // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
2472 : : // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
2473 : : // two in the chain that violate it. This prevents exploiting the issue against nodes during their
2474 : : // initial block download.
2475 : 183532 : bool fEnforceBIP30 = !IsBIP30Repeat(*pindex);
2476 : :
2477 : : // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
2478 : : // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
2479 : : // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
2480 : : // before the first had been spent. Since those coinbases are sufficiently buried it's no longer possible to create further
2481 : : // duplicate transactions descending from the known pairs either.
2482 : : // 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.
2483 : :
2484 : : // BIP34 requires that a block at height X (block X) has its coinbase
2485 : : // scriptSig start with a CScriptNum of X (indicated height X). The above
2486 : : // logic of no longer requiring BIP30 once BIP34 activates is flawed in the
2487 : : // case that there is a block X before the BIP34 height of 227,931 which has
2488 : : // an indicated height Y where Y is greater than X. The coinbase for block
2489 : : // X would also be a valid coinbase for block Y, which could be a BIP30
2490 : : // violation. An exhaustive search of all mainnet coinbases before the
2491 : : // BIP34 height which have an indicated height greater than the block height
2492 : : // reveals many occurrences. The 3 lowest indicated heights found are
2493 : : // 209,921, 490,897, and 1,983,702 and thus coinbases for blocks at these 3
2494 : : // heights would be the first opportunity for BIP30 to be violated.
2495 : :
2496 : : // The search reveals a great many blocks which have an indicated height
2497 : : // greater than 1,983,702, so we simply remove the optimization to skip
2498 : : // BIP30 checking for blocks at height 1,983,702 or higher. Before we reach
2499 : : // that block in another 25 years or so, we should take advantage of a
2500 : : // future consensus change to do a new and improved version of BIP34 that
2501 : : // will actually prevent ever creating any duplicate coinbases in the
2502 : : // future.
2503 : 183532 : static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
2504 : :
2505 : : // There is no potential to create a duplicate coinbase at block 209,921
2506 : : // because this is still before the BIP34 height and so explicit BIP30
2507 : : // checking is still active.
2508 : :
2509 : : // The final case is block 176,684 which has an indicated height of
2510 : : // 490,897. Unfortunately, this issue was not discovered until about 2 weeks
2511 : : // before block 490,897 so there was not much opportunity to address this
2512 : : // case other than to carefully analyze it and determine it would not be a
2513 : : // problem. Block 490,897 was, in fact, mined with a different coinbase than
2514 : : // block 176,684, but it is important to note that even if it hadn't been or
2515 : : // is remined on an alternate fork with a duplicate coinbase, we would still
2516 : : // not run into a BIP30 violation. This is because the coinbase for 176,684
2517 : : // is spent in block 185,956 in transaction
2518 : : // d4f7fbbf92f4a3014a230b2dc70b8058d02eb36ac06b4a0736d9d60eaa9e8781. This
2519 : : // spending transaction can't be duplicated because it also spends coinbase
2520 : : // 0328dd85c331237f18e781d692c92de57649529bd5edf1d01036daea32ffde29. This
2521 : : // coinbase has an indicated height of over 4.2 billion, and wouldn't be
2522 : : // duplicatable until that height, and it's currently impossible to create a
2523 : : // chain that long. Nevertheless we may wish to consider a future soft fork
2524 : : // which retroactively prevents block 490,897 from creating a duplicate
2525 : : // coinbase. The two historical BIP30 violations often provide a confusing
2526 : : // edge case when manipulating the UTXO and it would be simpler not to have
2527 : : // another edge case to deal with.
2528 : :
2529 : : // testnet3 has no blocks before the BIP34 height with indicated heights
2530 : : // post BIP34 before approximately height 486,000,000. After block
2531 : : // 1,983,702 testnet3 starts doing unnecessary BIP30 checking again.
2532 [ - + ]: 183532 : assert(pindex->pprev);
2533 : 183532 : CBlockIndex* pindexBIP34height = pindex->pprev->GetAncestor(params.GetConsensus().BIP34Height);
2534 : : //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
2535 [ + - + + : 183532 : fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == params.GetConsensus().BIP34Hash));
- + ]
2536 : :
2537 : : // TODO: Remove BIP30 checking from block height 1,983,702 on, once we have a
2538 : : // consensus change that ensures coinbases at those heights cannot
2539 : : // duplicate earlier coinbases.
2540 [ # # ]: 0 : if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
2541 [ + + ]: 434810 : for (const auto& tx : block.vtx) {
2542 [ - + + + ]: 847471 : for (size_t o = 0; o < tx->vout.size(); o++) {
2543 [ + + ]: 596193 : if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
2544 [ + - + - ]: 2 : state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-BIP30",
2545 : 2 : "tried to overwrite transaction");
2546 : : }
2547 : : }
2548 : : }
2549 : : }
2550 : :
2551 : : // Enforce BIP68 (sequence locks)
2552 : 183532 : int nLockTimeFlags = 0;
2553 [ + + ]: 183532 : if (DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_CSV)) {
2554 : 180005 : nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
2555 : : }
2556 : :
2557 : : // Get the script flags for this block
2558 : 183532 : script_verify_flags flags{GetBlockScriptFlags(*pindex, m_chainman)};
2559 : :
2560 : 183532 : const auto time_2{SteadyClock::now()};
2561 : 183532 : m_chainman.time_forks += time_2 - time_1;
2562 [ + + ]: 183532 : LogDebug(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n",
2563 : : Ticks<MillisecondsDouble>(time_2 - time_1),
2564 : : Ticks<SecondsDouble>(m_chainman.time_forks),
2565 : : Ticks<MillisecondsDouble>(m_chainman.time_forks) / m_chainman.num_blocks_total);
2566 : :
2567 : 183532 : const bool fScriptChecks{!!script_check_reason};
2568 : 183532 : const kernel::ChainstateRole role{GetRole()};
2569 [ + + + + : 183533 : if (script_check_reason != m_last_script_check_reason_logged && role.validated && !role.historical) {
+ + ]
2570 [ + + ]: 738 : if (fScriptChecks) {
2571 [ + - ]: 737 : LogInfo("Enabling script verification at block #%d (%s): %s.",
2572 : : pindex->nHeight, block_hash.ToString(), script_check_reason);
2573 : : } else {
2574 [ + - ]: 1 : LogInfo("Disabling script verification at block #%d (%s).",
2575 : : pindex->nHeight, block_hash.ToString());
2576 : : }
2577 : 738 : m_last_script_check_reason_logged = script_check_reason;
2578 : : }
2579 : :
2580 : 183532 : CBlockUndo blockundo;
2581 : :
2582 : : // Precomputed transaction data pointers must not be invalidated
2583 : : // until after `control` has run the script checks (potentially
2584 : : // in multiple threads). Preallocate the vector size so a new allocation
2585 : : // doesn't invalidate pointers into the vector, and keep txsdata in scope
2586 : : // for as long as `control`.
2587 [ - + + - ]: 183532 : std::vector<PrecomputedTransactionData> txsdata(block.vtx.size());
2588 : 183532 : std::optional<CCheckQueueControl<CScriptCheck>> control;
2589 [ + + + + : 183532 : if (auto& queue = m_chainman.GetCheckQueue(); queue.HasThreads() && fScriptChecks) control.emplace(queue);
+ - ]
2590 : :
2591 : 183532 : std::vector<int> prevheights;
2592 : 183532 : CAmount nFees = 0;
2593 : 183532 : int nInputs = 0;
2594 : 183532 : int64_t nSigOpsCost = 0;
2595 [ - + + - ]: 183532 : blockundo.vtxundo.reserve(block.vtx.size() - 1);
2596 [ - + + + ]: 434435 : for (unsigned int i = 0; i < block.vtx.size(); i++)
2597 : : {
2598 [ + + ]: 251276 : if (!state.IsValid()) break;
2599 [ - + ]: 251275 : const CTransaction &tx = *(block.vtx[i]);
2600 : :
2601 [ - + ]: 251275 : nInputs += tx.vin.size();
2602 : :
2603 [ + + ]: 251275 : if (!tx.IsCoinBase())
2604 : : {
2605 : 67744 : CAmount txfee = 0;
2606 [ + - ]: 67744 : TxValidationState tx_state;
2607 [ + - + + ]: 67744 : if (!Consensus::CheckTxInputs(tx, tx_state, view, pindex->nHeight, txfee)) {
2608 : : // Any transaction validation failure in ConnectBlock is a block consensus failure
2609 : 664 : state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,
2610 [ + - ]: 664 : tx_state.GetRejectReason(),
2611 [ + - - + : 1328 : tx_state.GetDebugMessage() + " in transaction " + tx.GetHash().ToString());
+ - + - ]
2612 : 332 : break;
2613 : : }
2614 : 67412 : nFees += txfee;
2615 [ - + ]: 67412 : if (!MoneyRange(nFees)) {
2616 [ # # # # ]: 0 : state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-accumulated-fee-outofrange",
2617 [ # # ]: 0 : "accumulated fee in the block out of range");
2618 : 0 : break;
2619 : : }
2620 : :
2621 : : // Check that transaction is BIP68 final
2622 : : // BIP68 lock checks (as opposed to nLockTime checks) must
2623 : : // be in ConnectBlock because they require the UTXO set
2624 [ - + + - ]: 67412 : prevheights.resize(tx.vin.size());
2625 [ - + + + ]: 175280 : for (size_t j = 0; j < tx.vin.size(); j++) {
2626 [ + - ]: 107868 : prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
2627 : : }
2628 : :
2629 [ + - + + ]: 67412 : if (!SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
2630 [ + - + - ]: 24 : state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal",
2631 [ + - + - ]: 24 : "contains a non-BIP68-final transaction " + tx.GetHash().ToString());
2632 : 12 : break;
2633 : : }
2634 : 67744 : }
2635 : :
2636 : : // GetTransactionSigOpCost counts 3 types of sigops:
2637 : : // * legacy (always)
2638 : : // * p2sh (when P2SH enabled in flags and excludes coinbase)
2639 : : // * witness (when witness enabled in flags and excludes coinbase)
2640 [ + - ]: 250931 : nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
2641 [ + + ]: 250931 : if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST) {
2642 [ + - + - : 14 : state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "too many sigops");
+ - ]
2643 : 7 : break;
2644 : : }
2645 : :
2646 [ + + + + ]: 250924 : if (!tx.IsCoinBase() && fScriptChecks)
2647 : : {
2648 : 67392 : bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
2649 : 67392 : bool tx_ok;
2650 [ + + ]: 67392 : TxValidationState tx_state;
2651 : : // If CheckInputScripts is called with a pointer to a checks vector, the resulting checks are appended to it. In that case
2652 : : // they need to be added to control which runs them asynchronously. Otherwise, CheckInputScripts runs the checks before returning.
2653 [ + + ]: 67392 : if (control) {
2654 : 66642 : std::vector<CScriptCheck> vChecks;
2655 [ + - ]: 66642 : tx_ok = CheckInputScripts(tx, tx_state, view, flags, CheckInputScriptsFor::Block, fCacheResults, fCacheResults, txsdata[i], m_chainman.m_validation_cache, &vChecks);
2656 [ + - + - ]: 66642 : if (tx_ok) control->Add(std::move(vChecks));
2657 : 66642 : } else {
2658 [ + - ]: 750 : tx_ok = CheckInputScripts(tx, tx_state, view, flags, CheckInputScriptsFor::Block, fCacheResults, fCacheResults, txsdata[i], m_chainman.m_validation_cache);
2659 : : }
2660 [ + + ]: 67392 : if (!tx_ok) {
2661 : : // Any transaction validation failure in ConnectBlock is a block consensus failure
2662 [ - + ]: 21 : state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,
2663 [ - + + - ]: 63 : tx_state.GetRejectReason(), tx_state.GetDebugMessage());
2664 : 21 : break;
2665 : : }
2666 : 67392 : }
2667 : :
2668 : 250903 : CTxUndo undoDummy;
2669 [ + + ]: 250903 : if (i > 0) {
2670 [ + - ]: 67372 : blockundo.vtxundo.emplace_back();
2671 : : }
2672 [ + + + - ]: 250903 : UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2673 : 250903 : }
2674 : 183532 : const auto time_3{SteadyClock::now()};
2675 [ + - ]: 183532 : m_chainman.time_connect += time_3 - time_2;
2676 [ + - + + : 183532 : LogDebug(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(),
+ + - + +
- ]
2677 : : Ticks<MillisecondsDouble>(time_3 - time_2), Ticks<MillisecondsDouble>(time_3 - time_2) / block.vtx.size(),
2678 : : nInputs <= 1 ? 0 : Ticks<MillisecondsDouble>(time_3 - time_2) / (nInputs - 1),
2679 : : Ticks<SecondsDouble>(m_chainman.time_connect),
2680 : : Ticks<MillisecondsDouble>(m_chainman.time_connect) / m_chainman.num_blocks_total);
2681 : :
2682 [ + - ]: 183532 : CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, params.GetConsensus());
2683 [ + - + + : 183532 : if (block.vtx[0]->GetValueOut() > blockReward && state.IsValid()) {
+ + ]
2684 [ + - + - ]: 18 : state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-amount",
2685 [ + - + - ]: 18 : strprintf("coinbase pays too much (actual=%d vs limit=%d)", block.vtx[0]->GetValueOut(), blockReward));
2686 : : }
2687 [ + + ]: 183532 : if (control) {
2688 [ + - ]: 182335 : auto parallel_result = control->Complete();
2689 [ + + + + ]: 182335 : if (parallel_result.has_value() && state.IsValid()) {
2690 [ + - + - : 5420 : state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, strprintf("block-script-verify-flag-failed (%s)", ScriptErrorString(parallel_result->first)), parallel_result->second);
+ - ]
2691 : : }
2692 : 182335 : }
2693 [ + + ]: 183532 : if (!state.IsValid()) {
2694 [ + - + - ]: 3092 : LogWarning("Block validation error: %s", state.ToString());
2695 : 3092 : return false;
2696 : : }
2697 : 180440 : const auto time_4{SteadyClock::now()};
2698 [ + - ]: 180440 : m_chainman.time_verify += time_4 - time_2;
2699 [ + - + + : 180440 : LogDebug(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1,
+ + + - ]
2700 : : Ticks<MillisecondsDouble>(time_4 - time_2),
2701 : : nInputs <= 1 ? 0 : Ticks<MillisecondsDouble>(time_4 - time_2) / (nInputs - 1),
2702 : : Ticks<SecondsDouble>(m_chainman.time_verify),
2703 : : Ticks<MillisecondsDouble>(m_chainman.time_verify) / m_chainman.num_blocks_total);
2704 : :
2705 [ + + ]: 180440 : if (fJustCheck) {
2706 : : return true;
2707 : : }
2708 : :
2709 [ + - + - ]: 132478 : if (!m_blockman.WriteBlockUndo(blockundo, state, *pindex)) {
2710 : : return false;
2711 : : }
2712 : :
2713 : 132478 : const auto time_5{SteadyClock::now()};
2714 [ + - ]: 132478 : m_chainman.time_undo += time_5 - time_4;
2715 [ + - + + : 132478 : LogDebug(BCLog::BENCH, " - Write undo data: %.2fms [%.2fs (%.2fms/blk)]\n",
+ - ]
2716 : : Ticks<MillisecondsDouble>(time_5 - time_4),
2717 : : Ticks<SecondsDouble>(m_chainman.time_undo),
2718 : : Ticks<MillisecondsDouble>(m_chainman.time_undo) / m_chainman.num_blocks_total);
2719 : :
2720 [ + - + + ]: 132478 : if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
2721 : 127015 : pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2722 [ + - ]: 127015 : m_blockman.m_dirty_blockindex.insert(pindex);
2723 : : }
2724 : :
2725 : : // add this block to the view's block chain
2726 [ + - ]: 132478 : view.SetBestBlock(pindex->GetBlockHash());
2727 : :
2728 : 132478 : const auto time_6{SteadyClock::now()};
2729 [ + - ]: 132478 : m_chainman.time_index += time_6 - time_5;
2730 [ + - + + : 183532 : LogDebug(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n",
+ - ]
2731 : : Ticks<MillisecondsDouble>(time_6 - time_5),
2732 : : Ticks<SecondsDouble>(m_chainman.time_index),
2733 : : Ticks<MillisecondsDouble>(m_chainman.time_index) / m_chainman.num_blocks_total);
2734 : :
2735 : : TRACEPOINT(validation, block_connected,
2736 : : block_hash.data(),
2737 : : pindex->nHeight,
2738 : : block.vtx.size(),
2739 : : nInputs,
2740 : : nSigOpsCost,
2741 : : Ticks<std::chrono::nanoseconds>(time_5 - time_start)
2742 : : );
2743 : :
2744 : : return true;
2745 : 183532 : }
2746 : :
2747 : 460991 : CoinsCacheSizeState Chainstate::GetCoinsCacheSizeState()
2748 : : {
2749 : 460991 : AssertLockHeld(::cs_main);
2750 : 460991 : return this->GetCoinsCacheSizeState(
2751 : : m_coinstip_cache_size_bytes,
2752 [ + + ]: 460991 : m_mempool ? m_mempool->m_opts.max_size_bytes : 0);
2753 : : }
2754 : :
2755 : 517986 : CoinsCacheSizeState Chainstate::GetCoinsCacheSizeState(
2756 : : size_t max_coins_cache_size_bytes,
2757 : : size_t max_mempool_size_bytes)
2758 : : {
2759 : 517986 : AssertLockHeld(::cs_main);
2760 [ + + ]: 517986 : const int64_t nMempoolUsage = m_mempool ? m_mempool->DynamicMemoryUsage() : 0;
2761 : 517986 : int64_t cacheSize = CoinsTip().DynamicMemoryUsage();
2762 : 517986 : int64_t nTotalSpace =
2763 [ + - ]: 517986 : max_coins_cache_size_bytes + std::max<int64_t>(int64_t(max_mempool_size_bytes) - nMempoolUsage, 0);
2764 : :
2765 [ + + ]: 517986 : if (cacheSize > nTotalSpace) {
2766 : 4 : LogInfo("Cache size (%s) exceeds total space (%s)\n", cacheSize, nTotalSpace);
2767 : 4 : return CoinsCacheSizeState::CRITICAL;
2768 [ + + + + ]: 575803 : } else if (cacheSize > LargeCoinsCacheThreshold(nTotalSpace)) {
2769 : 9826 : return CoinsCacheSizeState::LARGE;
2770 : : }
2771 : : return CoinsCacheSizeState::OK;
2772 : : }
2773 : :
2774 : 459990 : bool Chainstate::FlushStateToDisk(
2775 : : BlockValidationState &state,
2776 : : FlushStateMode mode,
2777 : : int nManualPruneHeight)
2778 : : {
2779 : 459990 : LOCK(cs_main);
2780 [ + - ]: 459990 : assert(this->CanFlushToDisk());
2781 [ + - ]: 459990 : std::set<int> setFilesToPrune;
2782 : 459990 : bool full_flush_completed = false;
2783 : :
2784 [ + - + - ]: 459990 : [[maybe_unused]] const size_t coins_count{CoinsTip().GetCacheSize()};
2785 [ + - + - ]: 459990 : [[maybe_unused]] const size_t coins_mem_usage{CoinsTip().DynamicMemoryUsage()};
2786 : :
2787 : 459990 : try {
2788 : 459990 : {
2789 : 459990 : bool fFlushForPrune = false;
2790 : :
2791 [ + - ]: 459990 : CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
2792 [ + + + + : 459990 : if (m_blockman.IsPruneMode() && (m_blockman.m_check_for_pruning || nManualPruneHeight > 0) && m_chainman.m_blockman.m_blockfiles_indexed) {
+ + + - ]
2793 : : // make sure we don't prune above any of the prune locks bestblocks
2794 : : // pruning is height-based
2795 [ - + ]: 672 : int last_prune{m_chain.Height()}; // last height we can prune
2796 : 672 : std::optional<std::string> limiting_lock; // prune lock that actually was the limiting factor, only used for logging
2797 : :
2798 [ + + - + ]: 1027 : for (const auto& prune_lock : m_blockman.m_prune_locks) {
2799 [ - + ]: 355 : if (prune_lock.second.height_first == std::numeric_limits<int>::max()) continue;
2800 : : // Remove the buffer and one additional block here to get actual height that is outside of the buffer
2801 : 355 : const int lock_height{prune_lock.second.height_first - PRUNE_LOCK_BUFFER - 1};
2802 [ + + + + ]: 639 : last_prune = std::max(1, std::min(last_prune, lock_height));
2803 [ + + ]: 355 : if (last_prune == lock_height) {
2804 [ + - ]: 336 : limiting_lock = prune_lock.first;
2805 : : }
2806 : : }
2807 : :
2808 [ + + ]: 672 : if (limiting_lock) {
2809 [ + - + - : 267 : LogDebug(BCLog::PRUNE, "%s limited pruning to height %d\n", limiting_lock.value(), last_prune);
+ - + - ]
2810 : : }
2811 : :
2812 [ + + ]: 672 : if (nManualPruneHeight > 0) {
2813 [ + - + - : 62 : LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune (manual)", BCLog::BENCH);
+ - ]
2814 : :
2815 [ - + ]: 31 : m_blockman.FindFilesToPruneManual(
2816 : : setFilesToPrune,
2817 [ + - ]: 31 : std::min(last_prune, nManualPruneHeight),
2818 : : *this);
2819 : 31 : } else {
2820 [ + - + - : 1282 : LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune", BCLog::BENCH);
+ - ]
2821 : :
2822 [ + - ]: 641 : m_blockman.FindFilesToPrune(setFilesToPrune, last_prune, *this, m_chainman);
2823 : 641 : m_blockman.m_check_for_pruning = false;
2824 : 641 : }
2825 [ + + ]: 672 : if (!setFilesToPrune.empty()) {
2826 : 38 : fFlushForPrune = true;
2827 [ + + ]: 38 : if (!m_blockman.m_have_pruned) {
2828 [ + - + - ]: 18 : m_blockman.m_block_tree_db->WriteFlag("prunedblockfiles", true);
2829 : 18 : m_blockman.m_have_pruned = true;
2830 : : }
2831 : : }
2832 : 672 : }
2833 : 459990 : const auto nNow{NodeClock::now()};
2834 : : // 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).
2835 : 459990 : bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
2836 : : // The cache is over the limit, we have to write now.
2837 : 459990 : bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
2838 : : // It's been a while since we wrote the block index and chain state to disk. Do this frequently, so we don't need to redownload or reindex after a crash.
2839 [ + + + + ]: 459990 : bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow >= m_next_write;
2840 [ + + + - ]: 459990 : const auto empty_cache{(mode == FlushStateMode::FORCE_FLUSH) || fCacheLarge || fCacheCritical};
2841 : : // Combine all conditions that result in a write to disk.
2842 [ + + + + ]: 459990 : bool should_write = (mode == FlushStateMode::FORCE_SYNC) || empty_cache || fPeriodicWrite || fFlushForPrune;
2843 : : // Write blocks, block index and best chain related state to disk.
2844 : 456175 : if (should_write) {
2845 [ + - + + : 3815 : LogDebug(BCLog::COINDB, "Writing chainstate to disk: flush mode=%s, prune=%d, large=%d, critical=%d, periodic=%d",
+ - ]
2846 : : FlushStateModeNames[size_t(mode)], fFlushForPrune, fCacheLarge, fCacheCritical, fPeriodicWrite);
2847 : :
2848 : : // Ensure we can write block index
2849 [ + - - + ]: 3815 : if (!CheckDiskSpace(m_blockman.m_opts.blocks_dir)) {
2850 [ # # # # ]: 0 : return FatalError(m_chainman.GetNotifications(), state, _("Disk space is too low!"));
2851 : : }
2852 : 3815 : {
2853 [ + - + - : 7630 : LOG_TIME_MILLIS_WITH_CATEGORY("write block and undo data to disk", BCLog::BENCH);
+ - ]
2854 : :
2855 : : // First make sure all block and undo data is flushed to disk.
2856 [ - + + - : 3815 : if (!m_blockman.FlushChainstateBlockFile(m_chain.Height())) {
+ + ]
2857 : : // FlushChainstateBlockFile() already reported the specific error through flushError()
2858 [ + - ]: 2 : return state.Error("Failed to flush block or undo file");
2859 : : }
2860 : 3815 : }
2861 : :
2862 : : // Then update all block file information (which may refer to block and undo files).
2863 : 3814 : {
2864 [ + - + - : 7628 : LOG_TIME_MILLIS_WITH_CATEGORY("write block index to disk", BCLog::BENCH);
+ - ]
2865 : :
2866 [ + - ]: 3814 : m_blockman.WriteBlockIndexDB();
2867 : 3814 : }
2868 : : // Finally remove any pruned files
2869 [ + + ]: 3814 : if (fFlushForPrune) {
2870 [ + - + - : 76 : LOG_TIME_MILLIS_WITH_CATEGORY("unlink pruned files", BCLog::BENCH);
+ - ]
2871 : :
2872 [ + - ]: 38 : m_blockman.UnlinkPrunedFiles(setFilesToPrune);
2873 : 38 : }
2874 : :
2875 [ + - + - : 7628 : if (!CoinsTip().GetBestBlock().IsNull()) {
+ + ]
2876 : : // Typical Coin structures on disk are around 48 bytes in size.
2877 : : // Pushing a new one to the database can cause it to be written
2878 : : // twice (once in the log, and once in the tables). This is already
2879 : : // an overestimation, as most will delete an existing entry or
2880 : : // overwrite one. Still, use a conservative safety factor of 2.
2881 [ + - + - : 3801 : if (!CheckDiskSpace(m_chainman.m_options.datadir, 48 * 2 * 2 * CoinsTip().GetDirtyCount())) {
- + ]
2882 [ # # # # ]: 0 : return FatalError(m_chainman.GetNotifications(), state, _("Disk space is too low!"));
2883 : : }
2884 : : // Flush the chainstate (which may refer to block index entries).
2885 [ + + + - : 3801 : empty_cache ? CoinsTip().Flush() : CoinsTip().Sync();
+ - + - +
- ]
2886 [ + - + - : 3801 : m_last_flushed_block = m_blockman.LookupBlockIndex(CoinsTip().GetBestBlock());
+ - ]
2887 : 3801 : full_flush_completed = true;
2888 : : TRACEPOINT(utxocache, flush,
2889 : : int64_t{Ticks<std::chrono::microseconds>(NodeClock::now() - nNow)},
2890 : : (uint32_t)mode,
2891 : : (uint64_t)coins_count,
2892 : : (uint64_t)coins_mem_usage,
2893 : 3801 : (bool)fFlushForPrune);
2894 : : }
2895 : : }
2896 : :
2897 [ + + ]: 456175 : if (should_write || m_next_write == NodeClock::time_point::max()) {
2898 : 4834 : constexpr auto range{DATABASE_WRITE_INTERVAL_MAX - DATABASE_WRITE_INTERVAL_MIN};
2899 : 4834 : m_next_write = FastRandomContext().rand_uniform_delay(NodeClock::now() + DATABASE_WRITE_INTERVAL_MIN, range);
2900 : : }
2901 : : }
2902 [ + + ]: 459989 : if (full_flush_completed) {
2903 [ + + ]: 3801 : if (m_chainman.m_options.signals) {
2904 [ + - + - : 7580 : m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(m_last_flushed_block));
+ - ]
2905 : : }
2906 : :
2907 [ + - + + : 3801 : if (!m_chainman.m_interrupt && !CoinsDB().IsMemoryOnly() && ShouldCompactChainstate(m_chainman.IsInitialBlockDownload())) {
+ - + + +
+ ]
2908 : 5 : try {
2909 [ + - ]: 5 : const fs::path path{StoragePath()};
2910 [ + - ]: 5 : const uint64_t min_free_space{m_chainman.GetParams().AssumedChainStateSize() * 1_GiB};
2911 [ + - + - ]: 5 : if (CheckDiskSpace(path, min_free_space)) {
2912 [ + - + - ]: 10 : CoinsDB().CompactFullAsync();
2913 : : } else {
2914 [ # # # # : 0 : LogWarning("Deferring chainstate compaction of %s: %.2f GiB free, %u GiB needed. Free up some space so compaction can run.",
# # ]
2915 : : fs::PathToString(path), fs::space(path).available / double{1_GiB}, CeilDiv(min_free_space, 1_GiB));
2916 : : }
2917 [ - - ]: 5 : } catch (const std::exception& e) {
2918 [ - - ]: 0 : LogWarning("Failed to start chainstate compaction (%s)", e.what());
2919 : 0 : }
2920 : : }
2921 : : }
2922 [ - - ]: 0 : } catch (const std::runtime_error& e) {
2923 [ - - - - ]: 0 : return FatalError(m_chainman.GetNotifications(), state, strprintf(_("System error while flushing: %s"), e.what()));
2924 : 0 : }
2925 : : return true;
2926 [ + - ]: 919980 : }
2927 : :
2928 : 3638 : void Chainstate::ForceFlushStateToDisk(bool wipe_cache)
2929 : : {
2930 [ + + ]: 3638 : BlockValidationState state;
2931 [ + + + - : 4855 : if (!this->FlushStateToDisk(state, wipe_cache ? FlushStateMode::FORCE_FLUSH : FlushStateMode::FORCE_SYNC)) {
- + ]
2932 [ # # # # ]: 0 : LogWarning("Failed to force flush state (%s)", state.ToString());
2933 : : }
2934 : 3638 : }
2935 : :
2936 : 68 : void Chainstate::PruneAndFlush()
2937 : : {
2938 [ + - ]: 68 : BlockValidationState state;
2939 : 68 : m_blockman.m_check_for_pruning = true;
2940 [ + - - + ]: 68 : if (!this->FlushStateToDisk(state, FlushStateMode::NONE)) {
2941 [ # # # # ]: 0 : LogWarning("Failed to flush state (%s)", state.ToString());
2942 : : }
2943 : 68 : }
2944 : :
2945 : 140375 : static void UpdateTipLog(
2946 : : const ChainstateManager& chainman,
2947 : : const CCoinsViewCache& coins_tip,
2948 : : const CBlockIndex* tip,
2949 : : const std::string& func_name,
2950 : : const std::string& prefix,
2951 : : const std::string& warning_messages,
2952 : : const bool background_validation) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
2953 : : {
2954 : :
2955 : 140375 : AssertLockHeld(::cs_main);
2956 : :
2957 : : // Disable rate limiting as this may log frequently during IBD.
2958 [ + + + - : 140375 : LogInfo(util::log::NO_RATE_LIMIT, "%s%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)%s\n",
+ - - + -
- + - + -
+ - + - +
- ]
2959 : : prefix, func_name,
2960 : : tip->GetBlockHash().ToString(), tip->nHeight, tip->nVersion,
2961 : : log(tip->nChainWork.getdouble()) / log(2.0), tip->m_chain_tx_count,
2962 : : FormatISO8601DateTime(tip->GetBlockTime()),
2963 : : background_validation ? chainman.GetBackgroundVerificationProgress(*tip) : chainman.GuessVerificationProgress(tip),
2964 : : coins_tip.DynamicMemoryUsage() / double(1_MiB),
2965 : : coins_tip.GetCacheSize(),
2966 : : !warning_messages.empty() ? strprintf(" warning='%s'", warning_messages) : "");
2967 : 140375 : }
2968 : :
2969 : 141376 : void Chainstate::UpdateTip(const CBlockIndex* pindexNew)
2970 : : {
2971 : 141376 : AssertLockHeld(::cs_main);
2972 : 141376 : const auto& coins_tip = this->CoinsTip();
2973 : :
2974 : : // The remainder of the function isn't relevant if we are not acting on
2975 : : // the active chainstate, so return if need be.
2976 [ + + ]: 141376 : if (this != &m_chainman.ActiveChainstate()) {
2977 : : // Only log every so often so that we don't bury log messages at the tip.
2978 : 1001 : constexpr int BACKGROUND_LOG_INTERVAL = 2000;
2979 [ - + ]: 1001 : if (pindexNew->nHeight % BACKGROUND_LOG_INTERVAL == 0) {
2980 [ # # # # : 0 : UpdateTipLog(m_chainman, coins_tip, pindexNew, __func__, "[background validation] ", "", /*background_validation=*/true);
# # ]
2981 : : }
2982 : 1001 : return;
2983 : : }
2984 : :
2985 : : // New best block
2986 [ + + ]: 140375 : if (m_mempool) {
2987 : 139947 : m_mempool->AddTransactionsUpdated(1);
2988 : : }
2989 : :
2990 : 140375 : std::vector<bilingual_str> warning_messages;
2991 [ + + ]: 140375 : if (!m_chainman.IsInitialBlockDownload()) {
2992 [ + - ]: 120760 : auto bits = m_chainman.m_versionbitscache.CheckUnknownActivations(pindexNew, m_chainman.GetParams());
2993 [ + - + + ]: 120908 : for (auto [bit, active] : bits) {
2994 [ + - ]: 148 : const bilingual_str warning = strprintf(_("Unknown new rules activated (versionbit %i)"), bit);
2995 [ + + ]: 148 : if (active) {
2996 [ + - ]: 4 : m_chainman.GetNotifications().warningSet(kernel::Warning::UNKNOWN_NEW_RULES_ACTIVATED, warning);
2997 : : } else {
2998 [ + - ]: 144 : warning_messages.push_back(warning);
2999 : : }
3000 : 148 : }
3001 : 120760 : }
3002 [ + - + - : 280750 : UpdateTipLog(m_chainman, coins_tip, pindexNew, __func__, "",
+ - ]
3003 [ + - + - : 421125 : util::Join(warning_messages, Untranslated(", ")).original, /*background_validation=*/false);
+ - ]
3004 : 140375 : }
3005 : :
3006 : : /** Disconnect m_chain's tip.
3007 : : * After calling, the mempool will be in an inconsistent state, with
3008 : : * transactions from disconnected blocks being added to disconnectpool. You
3009 : : * should make the mempool consistent again by calling MaybeUpdateMempoolForReorg.
3010 : : * with cs_main held.
3011 : : *
3012 : : * If disconnectpool is nullptr, then no disconnected transactions are added to
3013 : : * disconnectpool (note that the caller is responsible for mempool consistency
3014 : : * in any case).
3015 : : */
3016 : 9493 : bool Chainstate::DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool)
3017 : : {
3018 : 9493 : AssertLockHeld(cs_main);
3019 : 9493 : if (m_mempool) AssertLockHeld(m_mempool->cs);
3020 : :
3021 [ - + ]: 9493 : CBlockIndex *pindexDelete = m_chain.Tip();
3022 [ - + ]: 9493 : assert(pindexDelete);
3023 [ - + ]: 9493 : assert(pindexDelete->pprev);
3024 : : // Read block from disk.
3025 : 9493 : std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3026 [ + - ]: 9493 : CBlock& block = *pblock;
3027 [ + - - + ]: 9493 : if (!m_blockman.ReadBlock(block, *pindexDelete)) {
3028 [ - - + + ]: 9493 : LogError("DisconnectTip(): Failed to read block\n");
3029 : : return false;
3030 : : }
3031 : : // Apply the block atomically to the chain state.
3032 : 9493 : const auto time_start{SteadyClock::now()};
3033 : 9493 : {
3034 [ + - + - ]: 9493 : CCoinsViewCache view(&CoinsTip());
3035 [ + - ]: 9493 : assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
3036 [ + - + + ]: 9493 : if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK) {
3037 [ + - + - ]: 1 : LogError("DisconnectTip(): DisconnectBlock %s failed\n", pindexDelete->GetBlockHash().ToString());
3038 : 1 : return false;
3039 : : }
3040 [ + - ]: 9492 : view.Flush(/*reallocate_cache=*/false); // local CCoinsViewCache goes out of scope
3041 : 9493 : }
3042 [ + - + - : 9492 : LogDebug(BCLog::BENCH, "- Disconnect block: %.2fms\n",
+ - ]
3043 : : Ticks<MillisecondsDouble>(SteadyClock::now() - time_start));
3044 : :
3045 : 9492 : {
3046 : : // Prune locks that began at or after the tip should be moved backward so they get a chance to reorg
3047 : 9492 : const int max_height_first{pindexDelete->nHeight - 1};
3048 [ + + - + ]: 9806 : for (auto& prune_lock : m_blockman.m_prune_locks) {
3049 [ - + ]: 314 : if (prune_lock.second.height_first <= max_height_first) continue;
3050 : :
3051 : 314 : prune_lock.second.height_first = max_height_first;
3052 [ + - + - : 314 : LogDebug(BCLog::PRUNE, "%s prune lock moved back to %d\n", prune_lock.first, max_height_first);
+ - ]
3053 : : }
3054 : : }
3055 : :
3056 : : // Write the chain state to disk, if necessary.
3057 [ + - + - ]: 9492 : if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
3058 : : return false;
3059 : : }
3060 : :
3061 [ + + + + ]: 9492 : if (disconnectpool && m_mempool) {
3062 : : // Save transactions to re-add to mempool at end of reorg. If any entries are evicted for
3063 : : // exceeding memory limits, remove them and their descendants from the mempool.
3064 [ + - + + ]: 13239 : for (auto&& evicted_tx : disconnectpool->AddTransactionsFromBlock(block.vtx)) {
3065 [ + - ]: 3849 : m_mempool->removeRecursive(*evicted_tx, MemPoolRemovalReason::REORG);
3066 : : }
3067 : : }
3068 : :
3069 [ + - ]: 9492 : m_chain.SetTip(*pindexDelete->pprev);
3070 [ + - ]: 9492 : m_chainman.UpdateIBDStatus();
3071 : :
3072 [ + - ]: 9492 : UpdateTip(pindexDelete->pprev);
3073 : : // Let wallets know transactions went from 1-confirmed to
3074 : : // 0-confirmed or conflicted:
3075 [ + - ]: 9492 : if (m_chainman.m_options.signals) {
3076 [ + - ]: 18984 : m_chainman.m_options.signals->BlockDisconnected(std::move(pblock), pindexDelete);
3077 : : }
3078 : : return true;
3079 : 9493 : }
3080 : :
3081 [ - + + + ]: 143427 : struct ConnectedBlock {
3082 : : const CBlockIndex* pindex;
3083 : : std::shared_ptr<const CBlock> pblock;
3084 : : };
3085 : :
3086 : : /**
3087 : : * Connect a new block to m_chain. block_to_connect is either nullptr or a pointer to a CBlock
3088 : : * corresponding to pindexNew, to bypass loading it again from disk.
3089 : : *
3090 : : * The block is added to connected_blocks if connection succeeds.
3091 : : */
3092 : 134668 : bool Chainstate::ConnectTip(
3093 : : BlockValidationState& state,
3094 : : CBlockIndex* pindexNew,
3095 : : std::shared_ptr<const CBlock> block_to_connect,
3096 : : std::vector<ConnectedBlock>& connected_blocks,
3097 : : DisconnectedBlockTransactions& disconnectpool)
3098 : : {
3099 : 134668 : AssertLockHeld(cs_main);
3100 : 134668 : if (m_mempool) AssertLockHeld(m_mempool->cs);
3101 : :
3102 [ - + - + ]: 269336 : assert(pindexNew->pprev == m_chain.Tip());
3103 : : // Read block from disk.
3104 : 134668 : const auto time_1{SteadyClock::now()};
3105 [ + + ]: 134668 : if (!block_to_connect) {
3106 : 15926 : std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
3107 [ + - - + ]: 15926 : if (!m_blockman.ReadBlock(*pblockNew, *pindexNew)) {
3108 [ # # # # : 0 : return FatalError(m_chainman.GetNotifications(), state, _("Failed to read block."));
# # ]
3109 : : }
3110 [ - + ]: 15926 : block_to_connect = std::move(pblockNew);
3111 : 15926 : } else {
3112 [ + + ]: 118742 : LogDebug(BCLog::BENCH, " - Using cached block\n");
3113 : : }
3114 : : // Apply the block atomically to the chain state.
3115 : 134668 : const auto time_2{SteadyClock::now()};
3116 : 134668 : SteadyClock::time_point time_3;
3117 : : // When adding aggregate statistics in the future, keep in mind that
3118 : : // num_blocks_total may be zero until the ConnectBlock() call below.
3119 [ + + ]: 134668 : LogDebug(BCLog::BENCH, " - Load block from disk: %.2fms\n",
3120 : : Ticks<MillisecondsDouble>(time_2 - time_1));
3121 : 134668 : {
3122 : 134668 : CoinsViewOverlay& view{*m_coins_views->m_connect_block_view};
3123 : 134668 : const auto reset_guard{view.StartFetching(*block_to_connect)};
3124 [ + - ]: 134668 : bool rv = ConnectBlock(*block_to_connect, state, pindexNew, view);
3125 [ + + ]: 134668 : if (m_chainman.m_options.signals) {
3126 [ + - ]: 134244 : m_chainman.m_options.signals->BlockChecked(block_to_connect, state);
3127 : : }
3128 [ + + ]: 134668 : if (!rv) {
3129 [ + - ]: 2784 : if (state.IsInvalid())
3130 [ + - ]: 2784 : InvalidBlockFound(pindexNew, state);
3131 [ + - + - : 2784 : LogError("%s: ConnectBlock %s failed, %s\n", __func__, pindexNew->GetBlockHash().ToString(), state.ToString());
+ - ]
3132 : 2784 : return false;
3133 : : }
3134 : 131884 : time_3 = SteadyClock::now();
3135 [ - + ]: 131884 : m_chainman.time_connect_total += time_3 - time_2;
3136 [ - + ]: 131884 : assert(m_chainman.num_blocks_total > 0);
3137 [ + - + + : 131884 : LogDebug(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n",
+ - ]
3138 : : Ticks<MillisecondsDouble>(time_3 - time_2),
3139 : : Ticks<SecondsDouble>(m_chainman.time_connect_total),
3140 : : Ticks<MillisecondsDouble>(m_chainman.time_connect_total) / m_chainman.num_blocks_total);
3141 [ + - ]: 131884 : view.Flush(/*reallocate_cache=*/false); // No need to reallocate since it only has capacity for 1 block
3142 : 2784 : }
3143 : 131884 : const auto time_4{SteadyClock::now()};
3144 : 131884 : m_chainman.time_flush += time_4 - time_3;
3145 [ + + ]: 131884 : LogDebug(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n",
3146 : : Ticks<MillisecondsDouble>(time_4 - time_3),
3147 : : Ticks<SecondsDouble>(m_chainman.time_flush),
3148 : : Ticks<MillisecondsDouble>(m_chainman.time_flush) / m_chainman.num_blocks_total);
3149 : : // Write the chain state to disk, if necessary.
3150 [ + - ]: 131884 : if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
3151 : : return false;
3152 : : }
3153 : 131884 : const auto time_5{SteadyClock::now()};
3154 : 131884 : m_chainman.time_chainstate += time_5 - time_4;
3155 [ + + ]: 131884 : LogDebug(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n",
3156 : : Ticks<MillisecondsDouble>(time_5 - time_4),
3157 : : Ticks<SecondsDouble>(m_chainman.time_chainstate),
3158 : : Ticks<MillisecondsDouble>(m_chainman.time_chainstate) / m_chainman.num_blocks_total);
3159 : : // Remove conflicting transactions from the mempool.
3160 : 131884 : std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
3161 [ + + ]: 131884 : if (m_mempool) {
3162 [ + - ]: 261110 : txs_removed_for_block = m_mempool->removeForBlock(block_to_connect->vtx);
3163 [ + - ]: 130555 : disconnectpool.removeForBlock(block_to_connect->vtx);
3164 : : }
3165 : : // Update m_chain & related variables.
3166 [ + - ]: 131884 : m_chain.SetTip(*pindexNew);
3167 [ + - ]: 131884 : m_chainman.UpdateIBDStatus();
3168 : : // Not fired while IBD is active. removeForBlock() above still runs.
3169 [ + + + - : 131884 : if (m_mempool && m_chainman.m_options.signals && !m_chainman.IsInitialBlockDownload()) {
+ + ]
3170 [ + - + - ]: 337635 : m_chainman.m_options.signals->MempoolTransactionsRemovedForBlock(block_to_connect, std::move(txs_removed_for_block), pindexNew->nHeight);
3171 : : }
3172 [ + - ]: 131884 : UpdateTip(pindexNew);
3173 : :
3174 : 131884 : const auto time_6{SteadyClock::now()};
3175 [ + - ]: 131884 : m_chainman.time_post_connect += time_6 - time_5;
3176 : 131884 : m_chainman.time_total += time_6 - time_1;
3177 [ + - + + : 131884 : LogDebug(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n",
+ - ]
3178 : : Ticks<MillisecondsDouble>(time_6 - time_5),
3179 : : Ticks<SecondsDouble>(m_chainman.time_post_connect),
3180 : : Ticks<MillisecondsDouble>(m_chainman.time_post_connect) / m_chainman.num_blocks_total);
3181 [ + - + + : 131884 : LogDebug(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n",
+ - ]
3182 : : Ticks<MillisecondsDouble>(time_6 - time_1),
3183 : : Ticks<SecondsDouble>(m_chainman.time_total),
3184 : : Ticks<MillisecondsDouble>(m_chainman.time_total) / m_chainman.num_blocks_total);
3185 : :
3186 : : // See if this chainstate has reached a target block and can be used to
3187 : : // validate an assumeutxo snapshot. If it can, hashing the UTXO database
3188 : : // will be slow, and cs_main could remain locked here for several minutes.
3189 : : // If the snapshot is validated, the UTXO hash will be saved to
3190 : : // this->m_target_utxohash, causing HistoricalChainstate() to return null
3191 : : // and this chainstate to no longer be used. ActivateBestChain() will also
3192 : : // stop connecting blocks to this chainstate because this->ReachedTarget()
3193 : : // will be true and this->setBlockIndexCandidates will not have additional
3194 : : // blocks.
3195 [ + - ]: 131884 : Chainstate& current_cs{m_chainman.CurrentChainstate()};
3196 [ + - ]: 131884 : m_chainman.MaybeValidateSnapshot(*this, current_cs);
3197 : :
3198 [ + - ]: 131884 : connected_blocks.emplace_back(pindexNew, std::move(block_to_connect));
3199 : 131884 : return true;
3200 : 131884 : }
3201 : :
3202 : : /**
3203 : : * Return the tip of the chain with the most work in it, that isn't
3204 : : * known to be invalid (it's however far from certain to be valid).
3205 : : */
3206 : 152716 : CBlockIndex* Chainstate::FindMostWorkChain()
3207 : : {
3208 : 152716 : AssertLockHeld(::cs_main);
3209 : 152996 : do {
3210 : 152996 : CBlockIndex *pindexNew = nullptr;
3211 : :
3212 : : // Find the best candidate header.
3213 : 152996 : {
3214 [ + + ]: 152996 : std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
3215 [ + + ]: 152996 : if (it == setBlockIndexCandidates.rend())
3216 : : return nullptr;
3217 : 152995 : pindexNew = *it;
3218 : : }
3219 : :
3220 : : // Check whether all blocks on the path between the currently active chain and the candidate are valid.
3221 : : // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
3222 : 152995 : bool fInvalidAncestor = false;
3223 [ + + + + ]: 288099 : for (CBlockIndex *pindexTest = pindexNew; pindexTest && !m_chain.Contains(*pindexTest); pindexTest = pindexTest->pprev) {
3224 [ - - - + ]: 135384 : assert(pindexTest->HaveNumChainTxs() || pindexTest->nHeight == 0);
3225 : :
3226 : : // Pruned nodes may have entries in setBlockIndexCandidates for
3227 : : // which block files have been deleted. Remove those as candidates
3228 : : // for the most work chain if we come across them; we can't switch
3229 : : // to a chain unless we have all the non-active-chain parent blocks.
3230 : 135384 : bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_VALID;
3231 : 135384 : bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
3232 [ + + ]: 135384 : if (fFailedChain || fMissingData) {
3233 : : // Candidate chain is not usable (either invalid or missing data)
3234 [ + + + - : 280 : if (fFailedChain && (m_chainman.m_best_invalid == nullptr || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork)) {
+ + ]
3235 : 1 : m_chainman.m_best_invalid = pindexNew;
3236 : : }
3237 : : // Remove the entire chain from the set.
3238 [ + + ]: 703 : for (CBlockIndex *pindexFailed = pindexNew; pindexFailed != pindexTest; pindexFailed = pindexFailed->pprev) {
3239 : : // If we're missing data and not a descendant of an invalid block,
3240 : : // then add back to m_blocks_unlinked, so that if the block arrives in the future
3241 : : // we can try adding to setBlockIndexCandidates again.
3242 [ + - ]: 423 : if (fMissingData && !fFailedChain) {
3243 : : // Avoid duplicate entries in m_blocks_unlinked. If the same entry is
3244 : : // processed twice in ReceivedBlockTransactions(), it may be re-added to
3245 : : // setBlockIndexCandidates with a modified nSequenceId, breaking ordering
3246 : : // guarantees and leading to undefined behavior.
3247 : 423 : m_blockman.AddUnlinkedBlock(pindexFailed);
3248 : : }
3249 : 423 : setBlockIndexCandidates.erase(pindexFailed);
3250 : : }
3251 : 280 : setBlockIndexCandidates.erase(pindexTest);
3252 : 280 : fInvalidAncestor = true;
3253 : 280 : break;
3254 : : }
3255 : : }
3256 [ + + ]: 152995 : if (!fInvalidAncestor)
3257 : : return pindexNew;
3258 : : } while(true);
3259 : : }
3260 : :
3261 : : /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
3262 : 131892 : void Chainstate::PruneBlockIndexCandidates() {
3263 : : // Note that we can't delete the current block itself, as we may need to return to it later in case a
3264 : : // reorganization to a better block fails.
3265 : 131892 : std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
3266 [ + - - + : 513386 : while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) {
+ + ]
3267 : 124801 : setBlockIndexCandidates.erase(it++);
3268 : : }
3269 : : // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
3270 [ - + ]: 131892 : assert(!setBlockIndexCandidates.empty());
3271 : 131892 : }
3272 : :
3273 : : /**
3274 : : * Try to make some progress towards making index_most_work the active block.
3275 : : * pblock is either nullptr or a pointer to a CBlock corresponding to index_most_work.
3276 : : *
3277 : : * @returns true unless a system error occurred
3278 : : */
3279 : 127943 : bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex& index_most_work, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, std::vector<ConnectedBlock>& connected_blocks)
3280 : : {
3281 : 127943 : AssertLockHeld(cs_main);
3282 : 127943 : if (m_mempool) AssertLockHeld(m_mempool->cs);
3283 : :
3284 [ - + ]: 127943 : const CBlockIndex* pindexOldTip = m_chain.Tip();
3285 : 127943 : const CBlockIndex* pindexFork = m_chain.FindFork(index_most_work);
3286 : :
3287 : : // Disconnect active blocks which are no longer in the best chain.
3288 : 127943 : bool fBlocksDisconnected = false;
3289 : 127943 : DisconnectedBlockTransactions disconnectpool{MAX_DISCONNECTED_TX_POOL_BYTES};
3290 [ - + + - : 396821 : while (m_chain.Tip() && m_chain.Tip() != pindexFork) {
+ + ]
3291 [ + + + - ]: 6763 : if (!DisconnectTip(state, &disconnectpool)) {
3292 : : // This is likely a fatal error, but keep the mempool consistent,
3293 : : // just in case. Only remove from the mempool in this case.
3294 [ + - ]: 1 : MaybeUpdateMempoolForReorg(disconnectpool, false);
3295 : :
3296 : : // If we're unable to disconnect a block during normal operation,
3297 : : // then that is a failure of our local system -- we should abort
3298 : : // rather than stay on a less work chain.
3299 [ + - + - ]: 1 : FatalError(m_chainman.GetNotifications(), state, _("Failed to disconnect block."));
3300 : 1 : return false;
3301 : : }
3302 : : fBlocksDisconnected = true;
3303 : : }
3304 : :
3305 : : // Build list of new blocks to connect (in descending height order).
3306 : 127942 : std::vector<CBlockIndex*> vpindexToConnect;
3307 : 127942 : bool fContinue = true;
3308 [ + + ]: 127942 : int nHeight = pindexFork ? pindexFork->nHeight : -1;
3309 [ + + + + ]: 253264 : while (fContinue && nHeight != index_most_work.nHeight) {
3310 : : // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
3311 : : // a few blocks along the way.
3312 [ + + ]: 128106 : int nTargetHeight = std::min(nHeight + 32, index_most_work.nHeight);
3313 [ + + ]: 128106 : vpindexToConnect.clear();
3314 [ + - ]: 128106 : vpindexToConnect.reserve(nTargetHeight - nHeight);
3315 [ + - ]: 128106 : CBlockIndex* pindexIter = index_most_work.GetAncestor(nTargetHeight);
3316 [ + + + + ]: 491959 : while (pindexIter && pindexIter->nHeight != nHeight) {
3317 [ + - ]: 363853 : vpindexToConnect.push_back(pindexIter);
3318 : 363853 : pindexIter = pindexIter->pprev;
3319 : : }
3320 : 128106 : nHeight = nTargetHeight;
3321 : :
3322 : : // Connect new blocks.
3323 [ + + ]: 134865 : for (CBlockIndex* pindexConnect : vpindexToConnect | std::views::reverse) {
3324 [ + + + - : 257111 : if (!ConnectTip(state, pindexConnect, pindexConnect == &index_most_work ? pblock : std::shared_ptr<const CBlock>(), connected_blocks, disconnectpool)) {
+ + + + ]
3325 [ + - ]: 2784 : if (state.IsInvalid()) {
3326 : : // The block violates a consensus rule.
3327 [ + - ]: 2784 : if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
3328 [ + - ]: 2784 : InvalidChainFound(vpindexToConnect.front());
3329 : : }
3330 : 2784 : state = BlockValidationState();
3331 : 2784 : fInvalidFound = true;
3332 : 2784 : fContinue = false;
3333 : 2784 : break;
3334 : : } else {
3335 : : // A system error occurred (disk space, database error, ...).
3336 : : // Make the mempool consistent with the current tip, just in case
3337 : : // any observers try to use it before shutdown.
3338 [ # # ]: 0 : MaybeUpdateMempoolForReorg(disconnectpool, false);
3339 : : return false;
3340 : : }
3341 : : } else {
3342 [ + - ]: 131884 : PruneBlockIndexCandidates();
3343 [ + + - + : 263236 : if (!pindexOldTip || m_chain.Tip()->nChainWork > pindexOldTip->nChainWork) {
+ - + + ]
3344 : : // We're in a better position than we were. Return temporarily to release the lock.
3345 : : fContinue = false;
3346 : : break;
3347 : : }
3348 : : }
3349 : : }
3350 : : }
3351 : :
3352 [ + + ]: 127942 : if (fBlocksDisconnected) {
3353 : : // If any blocks were disconnected, disconnectpool may be non empty. Add
3354 : : // any disconnected transactions back to the mempool.
3355 [ + - ]: 186 : MaybeUpdateMempoolForReorg(disconnectpool, true);
3356 : : }
3357 [ + + - + : 127942 : if (m_mempool) m_mempool->check(this->CoinsTip(), this->m_chain.Height() + 1);
+ - + - ]
3358 : :
3359 [ + - ]: 127942 : CheckForkWarningConditions();
3360 : :
3361 : : return true;
3362 : 127943 : }
3363 : :
3364 : 224239 : static SynchronizationState GetSynchronizationState(bool init, bool blockfiles_indexed)
3365 : : {
3366 [ + + ]: 224239 : if (!init) return SynchronizationState::POST_INIT;
3367 [ + + ]: 27000 : if (!blockfiles_indexed) return SynchronizationState::INIT_REINDEX;
3368 : : return SynchronizationState::INIT_DOWNLOAD;
3369 : : }
3370 : :
3371 : 143434 : void ChainstateManager::UpdateIBDStatus()
3372 : : {
3373 : 143434 : AssertLockHeld(cs_main);
3374 [ + + ]: 143434 : if (!m_cached_is_ibd.load(std::memory_order_relaxed)) return;
3375 [ + + ]: 22131 : if (m_blockman.LoadingBlocks()) return;
3376 [ + + ]: 19167 : if (!CurrentChainstate().m_chain.IsTipRecent(MinimumChainWork(), m_options.max_tip_age)) return;
3377 : 1000 : LogInfo("Leaving InitialBlockDownload (latching to false)");
3378 : 1000 : m_cached_is_ibd.store(false, std::memory_order_relaxed);
3379 : : }
3380 : :
3381 : 186274 : bool ChainstateManager::NotifyHeaderTip()
3382 : : {
3383 : 186274 : bool fNotify = false;
3384 : 186274 : bool fInitialBlockDownload = false;
3385 : 186274 : CBlockIndex* pindexHeader = nullptr;
3386 : 186274 : {
3387 : 186274 : LOCK(GetMutex());
3388 : 186274 : pindexHeader = m_best_header;
3389 : :
3390 [ + + ]: 186274 : if (pindexHeader != m_last_notified_header) {
3391 : 98882 : fNotify = true;
3392 : 98882 : fInitialBlockDownload = IsInitialBlockDownload();
3393 : 98882 : m_last_notified_header = pindexHeader;
3394 : : }
3395 : 186274 : }
3396 : : // Send block tip changed notifications without the lock held
3397 [ + + ]: 186274 : if (fNotify) {
3398 : 98882 : GetNotifications().headerTip(GetSynchronizationState(fInitialBlockDownload, m_blockman.m_blockfiles_indexed), pindexHeader->nHeight, pindexHeader->nTime, false);
3399 : : }
3400 : 186274 : return fNotify;
3401 : : }
3402 : :
3403 : 163436 : static void LimitValidationInterfaceQueue(ValidationSignals& signals) LOCKS_EXCLUDED(cs_main) {
3404 : 163436 : AssertLockNotHeld(cs_main);
3405 : :
3406 [ + + ]: 163436 : if (signals.CallbacksPending() > 10) {
3407 : 2328 : signals.SyncWithValidationInterfaceQueue();
3408 : : }
3409 : 163436 : }
3410 : :
3411 : 149932 : bool Chainstate::ActivateBestChain(BlockValidationState& state, std::shared_ptr<const CBlock> pblock)
3412 : : {
3413 : 149932 : AssertLockNotHeld(m_chainstate_mutex);
3414 : :
3415 : : // Note that while we're often called here from ProcessNewBlock, this is
3416 : : // far from a guarantee. Things in the P2P/RPC will often end up calling
3417 : : // us in the middle of ProcessNewBlock - do not assume pblock is set
3418 : : // sanely for performance or correctness!
3419 : 149932 : AssertLockNotHeld(::cs_main);
3420 : :
3421 : : // ABC maintains a fair degree of expensive-to-calculate internal state
3422 : : // because this function periodically releases cs_main so that it does not lock up other threads for too long
3423 : : // during large connects - and to allow for e.g. the callback queue to drain
3424 : : // we use m_chainstate_mutex to enforce mutual exclusion so that only one caller may execute this function at a time
3425 : 149932 : LOCK(m_chainstate_mutex);
3426 : :
3427 : : // Belt-and-suspenders check that we aren't attempting to advance the
3428 : : // chainstate past the target block.
3429 [ + - - + : 299864 : if (WITH_LOCK(::cs_main, return m_target_utxohash)) {
+ - ]
3430 [ # # # # ]: 0 : LogError("%s", STR_INTERNAL_BUG("m_target_utxohash is set - this chainstate should not be in operation."));
3431 : 0 : return Assume(false);
3432 : : }
3433 : :
3434 : 149932 : CBlockIndex *pindexMostWork = nullptr;
3435 : 149932 : CBlockIndex *pindexNewTip = nullptr;
3436 : 149932 : bool exited_ibd{false};
3437 : 160989 : do {
3438 : : // Block until the validation queue drains. This should largely
3439 : : // never happen in normal operation, however may happen during
3440 : : // reindex, causing memory blowup if we run too far ahead.
3441 : : // Note that if a validationinterface callback ends up calling
3442 : : // ActivateBestChain this may lead to a deadlock! We should
3443 : : // probably have a DEBUG_LOCKORDER test for this in the future.
3444 [ + + + - ]: 160989 : if (m_chainman.m_options.signals) LimitValidationInterfaceQueue(*m_chainman.m_options.signals);
3445 : :
3446 : 160989 : {
3447 [ + - ]: 160989 : LOCK(cs_main);
3448 : 160989 : {
3449 : : // Lock transaction pool for at least as long as it takes for connected_blocks to be consumed
3450 [ + + + - ]: 319529 : LOCK(MempoolMutex());
3451 : 160989 : const bool was_in_ibd = m_chainman.IsInitialBlockDownload();
3452 [ - + ]: 160989 : CBlockIndex* starting_tip = m_chain.Tip();
3453 : 160989 : bool blocks_connected = false;
3454 : 160995 : do {
3455 : : // We absolutely may not unlock cs_main until we've made forward progress
3456 : : // (with the exception of shutdown due to hardware issues, low disk space, etc).
3457 : 160995 : std::vector<ConnectedBlock> connected_blocks; // Destructed before cs_main is unlocked
3458 : :
3459 [ + + ]: 160995 : if (pindexMostWork == nullptr) {
3460 [ + - ]: 152716 : pindexMostWork = FindMostWorkChain();
3461 : : }
3462 : :
3463 : : // Whether we have anything to do at all.
3464 [ + + - + : 321989 : if (pindexMostWork == nullptr || pindexMostWork == m_chain.Tip()) {
+ + ]
3465 : : break;
3466 : : }
3467 : :
3468 : 127943 : bool fInvalidFound = false;
3469 : 127943 : std::shared_ptr<const CBlock> nullBlockPtr;
3470 : : // BlockConnected signals must be sent for the original role;
3471 : : // in case snapshot validation is completed during ActivateBestChainStep, the
3472 : : // result of GetRole() changes from BACKGROUND to NORMAL.
3473 [ + - ]: 127943 : const ChainstateRole chainstate_role{this->GetRole()};
3474 [ + + + - : 251308 : if (!ActivateBestChainStep(state, *pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connected_blocks)) {
+ - + + ]
3475 : : // A system error occurred
3476 [ - + ]: 1 : return false;
3477 : : }
3478 : 127942 : blocks_connected = true;
3479 : :
3480 [ + + ]: 127942 : if (fInvalidFound) {
3481 : : // Wipe cache, we may need another branch now.
3482 : 2784 : pindexMostWork = nullptr;
3483 : : }
3484 [ - + ]: 127942 : pindexNewTip = m_chain.Tip();
3485 : :
3486 [ + + ]: 259826 : for (auto& [index, block] : std::move(connected_blocks)) {
3487 [ + + ]: 131884 : if (m_chainman.m_options.signals) {
3488 [ + - + - : 262920 : m_chainman.m_options.signals->BlockConnected(chainstate_role, std::move(Assert(block)), Assert(index));
+ - ]
3489 : : }
3490 : : }
3491 : :
3492 : : // Break this do-while to ensure we don't advance past the target block.
3493 [ + - + + ]: 127942 : if (ReachedTarget()) {
3494 : : break;
3495 : : }
3496 [ - + + - : 288935 : } while (!m_chain.Tip() || (starting_tip && CBlockIndexWorkComparator()(m_chain.Tip(), starting_tip)));
+ + + - +
+ + + ]
3497 [ + + ]: 160988 : if (!blocks_connected) return true;
3498 : :
3499 [ + + + - ]: 127936 : const CBlockIndex* pindexFork = starting_tip ? m_chain.FindFork(*starting_tip) : nullptr;
3500 : 127936 : bool still_in_ibd = m_chainman.IsInitialBlockDownload();
3501 : :
3502 [ + + ]: 127936 : if (was_in_ibd && !still_in_ibd) {
3503 : : // Active chainstate has exited IBD.
3504 : 522 : exited_ibd = true;
3505 : : }
3506 : :
3507 : : // Notify external listeners about the new tip.
3508 : : // Enqueue while holding cs_main to ensure that UpdatedBlockTip is called in the order in which blocks are connected
3509 [ + - + + : 127936 : if (this == &m_chainman.ActiveChainstate() && pindexFork != pindexNewTip) {
+ + ]
3510 : : // Notify ValidationInterface subscribers
3511 [ + + ]: 124350 : if (m_chainman.m_options.signals) {
3512 [ + - ]: 123926 : m_chainman.m_options.signals->UpdatedBlockTip(pindexNewTip, pindexFork, still_in_ibd);
3513 : : }
3514 : :
3515 [ + - + + ]: 248700 : if (kernel::IsInterrupted(m_chainman.GetNotifications().blockTip(
3516 [ + - ]: 124350 : /*state=*/GetSynchronizationState(still_in_ibd, m_chainman.m_blockman.m_blockfiles_indexed),
3517 : : /*index=*/*pindexNewTip,
3518 : : /*verification_progress=*/m_chainman.GuessVerificationProgress(pindexNewTip))))
3519 : : {
3520 : : // Just breaking and returning success for now. This could
3521 : : // be changed to bubble up the kernel::Interrupted value to
3522 : : // the caller so the caller could distinguish between
3523 : : // completed and interrupted operations.
3524 : : break;
3525 : : }
3526 : : }
3527 [ + - + - ]: 33055 : } // release MempoolMutex
3528 : : // Notify external listeners about the new tip, even if pindexFork == pindexNewTip.
3529 [ + + + - : 127934 : if (m_chainman.m_options.signals && this == &m_chainman.ActiveChainstate()) {
+ + ]
3530 [ + - + - ]: 126708 : m_chainman.m_options.signals->ActiveTipChange(*Assert(pindexNewTip), m_chainman.IsInitialBlockDownload());
3531 : : }
3532 : 33055 : } // release cs_main
3533 : : // When we reach this point, we switched to a new tip (stored in pindexNewTip).
3534 : :
3535 : 127934 : bool reached_target;
3536 : 127934 : {
3537 [ + - ]: 127934 : LOCK(m_chainman.GetMutex());
3538 [ + + ]: 127934 : if (exited_ibd) {
3539 : : // If a background chainstate is in use, we may need to rebalance our
3540 : : // allocation of caches once a chainstate exits initial block download.
3541 [ + - ]: 522 : m_chainman.MaybeRebalanceCaches();
3542 : : }
3543 : :
3544 : : // Write changes periodically to disk, after relay.
3545 [ + - - + ]: 127934 : if (!FlushStateToDisk(state, FlushStateMode::PERIODIC)) {
3546 [ # # ]: 0 : return false;
3547 : : }
3548 : :
3549 [ + - + - ]: 127934 : reached_target = ReachedTarget();
3550 : 0 : }
3551 : :
3552 [ + + ]: 127934 : if (reached_target) {
3553 : : // Chainstate has reached the target block, so exit.
3554 : : //
3555 : : // Restart indexes so indexes can resync and index new blocks after
3556 : : // the target block.
3557 : : //
3558 : : // This cannot be done while holding cs_main (within
3559 : : // MaybeValidateSnapshot) or a cs_main deadlock will occur.
3560 [ + + ]: 8 : if (m_chainman.snapshot_download_completed) {
3561 [ + - ]: 7 : m_chainman.snapshot_download_completed();
3562 : : }
3563 : : break;
3564 : : }
3565 : :
3566 : : // We check interrupt only after giving ActivateBestChainStep a chance to run once so that we
3567 : : // never interrupt before connecting the genesis block during LoadChainTip(). Previously this
3568 : : // caused an assert() failure during interrupt in such cases as the UTXO DB flushing checks
3569 : : // that the best block hash is non-null.
3570 [ + - + + ]: 127926 : if (m_chainman.m_interrupt) break;
3571 [ + + ]: 127923 : } while (pindexNewTip != pindexMostWork);
3572 : :
3573 [ + - ]: 116879 : m_chainman.CheckBlockIndex();
3574 : :
3575 : : return true;
3576 : 149932 : }
3577 : :
3578 : 10 : bool Chainstate::PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
3579 : : {
3580 : 10 : AssertLockNotHeld(m_chainstate_mutex);
3581 : 10 : AssertLockNotHeld(::cs_main);
3582 : 10 : {
3583 : 10 : LOCK(cs_main);
3584 [ - + + - : 20 : if (pindex->nChainWork < m_chain.Tip()->nChainWork) {
+ + ]
3585 : : // Nothing to do, this block is not at the tip.
3586 [ + - ]: 1 : return true;
3587 : : }
3588 [ - + + - : 18 : if (m_chain.Tip()->nChainWork > m_chainman.nLastPreciousChainwork) {
+ + ]
3589 : : // The chain has been extended since the last call, reset the counter.
3590 : 5 : m_chainman.nBlockReverseSequenceId = -1;
3591 : : }
3592 [ - + ]: 9 : m_chainman.nLastPreciousChainwork = m_chain.Tip()->nChainWork;
3593 [ + - ]: 9 : setBlockIndexCandidates.erase(pindex);
3594 : 9 : pindex->nSequenceId = m_chainman.nBlockReverseSequenceId;
3595 [ + - ]: 9 : if (m_chainman.nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
3596 : : // We can't keep reducing the counter if somebody really wants to
3597 : : // call preciousblock 2**31-1 times on the same set of tips...
3598 : 9 : m_chainman.nBlockReverseSequenceId--;
3599 : : }
3600 [ + + + - : 17 : if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->HaveNumChainTxs()) {
+ - + - ]
3601 [ + - ]: 8 : setBlockIndexCandidates.insert(pindex);
3602 [ + - ]: 8 : PruneBlockIndexCandidates();
3603 : : }
3604 : 1 : }
3605 : :
3606 [ + - - + ]: 9 : return ActivateBestChain(state, std::shared_ptr<const CBlock>());
3607 : : }
3608 : :
3609 : 150 : bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* const pindex)
3610 : : {
3611 : 150 : AssertLockNotHeld(m_chainstate_mutex);
3612 : 150 : AssertLockNotHeld(::cs_main);
3613 : :
3614 : : // Genesis block can't be invalidated
3615 [ - + ]: 150 : assert(pindex);
3616 [ + - ]: 150 : if (pindex->nHeight == 0) return false;
3617 : :
3618 : : // We do not allow ActivateBestChain() to run while InvalidateBlock() is
3619 : : // running, as that could cause the tip to change while we disconnect
3620 : : // blocks.
3621 : 150 : LOCK(m_chainstate_mutex);
3622 : :
3623 : : // We'll be acquiring and releasing cs_main below, to allow the validation
3624 : : // callbacks to run. However, we should keep the block index in a
3625 : : // consistent state as we disconnect blocks -- in particular we need to
3626 : : // add equal-work blocks to setBlockIndexCandidates as we disconnect.
3627 : : // To avoid walking the block index repeatedly in search of candidates,
3628 : : // build a map once so that we can look up candidate blocks by chain
3629 : : // work as we go.
3630 [ + - ]: 150 : std::multimap<const arith_uint256, CBlockIndex*> highpow_outofchain_headers;
3631 : :
3632 : 150 : {
3633 [ + - ]: 150 : LOCK(cs_main);
3634 [ + + + + : 41156 : for (auto& entry : m_blockman.m_block_index) {
+ - ]
3635 : 41006 : CBlockIndex& candidate = entry.second;
3636 : : // We don't need to put anything in our active chain into the
3637 : : // multimap, because those candidates will be found and considered
3638 : : // as we disconnect.
3639 : : // Instead, consider only non-active-chain blocks that score
3640 : : // at least as good with CBlockIndexWorkComparator as the new tip.
3641 [ + + ]: 4069 : if (!m_chain.Contains(candidate) &&
3642 [ + - + + ]: 41006 : !CBlockIndexWorkComparator()(&candidate, pindex->pprev) &&
3643 [ + + ]: 2349 : !(candidate.nStatus & BLOCK_FAILED_VALID)) {
3644 [ + - ]: 463 : highpow_outofchain_headers.insert({candidate.nChainWork, &candidate});
3645 : : }
3646 : : }
3647 : 0 : }
3648 : :
3649 : 150 : CBlockIndex* to_mark_failed = pindex;
3650 : 150 : bool pindex_was_in_chain = false;
3651 : 150 : int disconnected = 0;
3652 : :
3653 : : // Disconnect (descendants of) pindex, and mark them invalid.
3654 : 5604 : while (true) {
3655 [ + - + - ]: 2877 : if (m_chainman.m_interrupt) break;
3656 : :
3657 : : // Make sure the queue of validation callbacks doesn't grow unboundedly.
3658 [ + - + - ]: 2877 : if (m_chainman.m_options.signals) LimitValidationInterfaceQueue(*m_chainman.m_options.signals);
3659 : :
3660 [ + - ]: 2877 : LOCK(cs_main);
3661 : : // Lock for as long as disconnectpool is in scope to make sure MaybeUpdateMempoolForReorg is
3662 : : // called after DisconnectTip without unlocking in between
3663 [ + - + - ]: 5754 : LOCK(MempoolMutex());
3664 [ + + ]: 2877 : if (!m_chain.Contains(*pindex)) break;
3665 : 2727 : pindex_was_in_chain = true;
3666 [ - + ]: 2727 : CBlockIndex* const disconnected_tip{m_chain.Tip()};
3667 : :
3668 : : // ActivateBestChain considers blocks already in m_chain
3669 : : // unconditionally valid already, so force disconnect away from it.
3670 [ + - ]: 2727 : DisconnectedBlockTransactions disconnectpool{MAX_DISCONNECTED_TX_POOL_BYTES};
3671 [ + - ]: 2727 : bool ret = DisconnectTip(state, &disconnectpool);
3672 : : // DisconnectTip will add transactions to disconnectpool.
3673 : : // Adjust the mempool to be consistent with the new tip, adding
3674 : : // transactions back to the mempool if disconnecting was successful,
3675 : : // and we're not doing a very deep invalidation (in which case
3676 : : // keeping the mempool up to date is probably futile anyway).
3677 [ + + - + : 5023 : MaybeUpdateMempoolForReorg(disconnectpool, /* fAddToMempool = */ (++disconnected <= 10) && ret);
+ - ]
3678 [ - + ]: 2727 : if (!ret) return false;
3679 [ - + ]: 2727 : CBlockIndex* new_tip{m_chain.Tip()};
3680 [ - + ]: 2727 : assert(disconnected_tip->pprev == new_tip);
3681 : :
3682 : : // We immediately mark the disconnected blocks as invalid.
3683 : : // This prevents a case where pruned nodes may fail to invalidateblock
3684 : : // and be left unable to start as they have no tip candidates (as there
3685 : : // are no blocks that meet the "have data and are not invalid per
3686 : : // nStatus" criteria for inclusion in setBlockIndexCandidates).
3687 : 2727 : disconnected_tip->nStatus |= BLOCK_FAILED_VALID;
3688 [ + - ]: 2727 : m_blockman.m_dirty_blockindex.insert(disconnected_tip);
3689 [ + - ]: 2727 : setBlockIndexCandidates.erase(disconnected_tip);
3690 [ + - ]: 2727 : setBlockIndexCandidates.insert(new_tip);
3691 : :
3692 : : // Mark out-of-chain descendants of the invalidated block as invalid
3693 : : // Add any equal or more work headers that are not invalidated to setBlockIndexCandidates
3694 : : // Recalculate m_best_header if it became invalid.
3695 [ + - ]: 2727 : auto candidate_it = highpow_outofchain_headers.lower_bound(new_tip->nChainWork);
3696 : :
3697 [ + - ]: 2727 : const bool best_header_needs_update{m_chainman.m_best_header->GetAncestor(disconnected_tip->nHeight) == disconnected_tip};
3698 [ + + ]: 2727 : if (best_header_needs_update) {
3699 : : // new_tip is definitely still valid at this point, but there may be better ones
3700 : 2385 : m_chainman.m_best_header = new_tip;
3701 : : }
3702 : :
3703 [ + + ]: 8210 : while (candidate_it != highpow_outofchain_headers.end()) {
3704 [ + - ]: 5483 : CBlockIndex* candidate{candidate_it->second};
3705 [ + - + + ]: 5483 : if (candidate->GetAncestor(disconnected_tip->nHeight) == disconnected_tip) {
3706 : : // Children of failed blocks are marked as BLOCK_FAILED_VALID.
3707 : 275 : candidate->nStatus |= BLOCK_FAILED_VALID;
3708 [ + - ]: 275 : m_blockman.m_dirty_blockindex.insert(candidate);
3709 : : // If invalidated, the block is irrelevant for setBlockIndexCandidates
3710 : : // and for m_best_header and can be removed from the cache.
3711 : 275 : candidate_it = highpow_outofchain_headers.erase(candidate_it);
3712 : 275 : continue;
3713 : : }
3714 [ + - ]: 5208 : if (!CBlockIndexWorkComparator()(candidate, new_tip) &&
3715 [ + + + - : 5208 : candidate->IsValid(BLOCK_VALID_TRANSACTIONS) &&
+ + + - ]
3716 [ + - ]: 4839 : candidate->HaveNumChainTxs()) {
3717 [ + - ]: 4839 : setBlockIndexCandidates.insert(candidate);
3718 : : // Do not remove candidate from the highpow_outofchain_headers cache, because it might be a descendant of the block being invalidated
3719 : : // which needs to be marked failed later.
3720 : : }
3721 [ + + + + ]: 5302 : if (best_header_needs_update &&
3722 [ + - ]: 94 : m_chainman.m_best_header->nChainWork < candidate->nChainWork) {
3723 : 22 : m_chainman.m_best_header = candidate;
3724 : : }
3725 : 5208 : ++candidate_it;
3726 : : }
3727 : :
3728 : : // Track the last disconnected block to call InvalidChainFound on it.
3729 : 2727 : to_mark_failed = disconnected_tip;
3730 [ - - - - : 8481 : }
+ - + - +
- ]
3731 : :
3732 [ + - ]: 150 : m_chainman.CheckBlockIndex();
3733 : :
3734 : 150 : {
3735 [ + - ]: 150 : LOCK(cs_main);
3736 [ - + ]: 150 : if (m_chain.Contains(*to_mark_failed)) {
3737 : : // If the to-be-marked invalid block is in the active chain, something is interfering and we can't proceed.
3738 [ # # ]: 0 : return false;
3739 : : }
3740 : :
3741 : : // Mark pindex as invalid if it never was in the main chain
3742 [ + + + - ]: 150 : if (!pindex_was_in_chain && !(pindex->nStatus & BLOCK_FAILED_VALID)) {
3743 : 2 : pindex->nStatus |= BLOCK_FAILED_VALID;
3744 [ + - ]: 2 : m_blockman.m_dirty_blockindex.insert(pindex);
3745 [ + - ]: 2 : setBlockIndexCandidates.erase(pindex);
3746 : : }
3747 : :
3748 : : // If any new blocks somehow arrived while we were disconnecting
3749 : : // (above), then the pre-calculation of what should go into
3750 : : // setBlockIndexCandidates may have missed entries. This would
3751 : : // technically be an inconsistency in the block index, but if we clean
3752 : : // it up here, this should be an essentially unobservable error.
3753 : : // Loop back over all block index entries and add any missing entries
3754 : : // to setBlockIndexCandidates.
3755 [ + + + + ]: 41156 : for (auto& [_, block_index] : m_blockman.m_block_index) {
3756 [ + + + + : 76862 : if (block_index.IsValid(BLOCK_VALID_TRANSACTIONS) && block_index.HaveNumChainTxs() && !setBlockIndexCandidates.value_comp()(&block_index, m_chain.Tip())) {
- + + - +
+ + + ]
3757 [ + - ]: 298 : setBlockIndexCandidates.insert(&block_index);
3758 : : }
3759 : : }
3760 : :
3761 [ + - ]: 150 : InvalidChainFound(to_mark_failed);
3762 : 0 : }
3763 : :
3764 : : // Only notify about a new block tip if the active chain was modified.
3765 [ + + ]: 150 : if (pindex_was_in_chain) {
3766 : : // Ignoring return value for now, this could be changed to bubble up
3767 : : // kernel::Interrupted value to the caller so the caller could
3768 : : // distinguish between completed and interrupted operations. It might
3769 : : // also make sense for the blockTip notification to have an enum
3770 : : // parameter indicating the source of the tip change so hooks can
3771 : : // distinguish user-initiated invalidateblock changes from other
3772 : : // changes.
3773 [ + - + - ]: 296 : (void)m_chainman.GetNotifications().blockTip(
3774 : 148 : /*state=*/GetSynchronizationState(m_chainman.IsInitialBlockDownload(), m_chainman.m_blockman.m_blockfiles_indexed),
3775 : 148 : /*index=*/*to_mark_failed->pprev,
3776 [ + - + - : 444 : /*verification_progress=*/WITH_LOCK(m_chainman.GetMutex(), return m_chainman.GuessVerificationProgress(to_mark_failed->pprev)));
+ - ]
3777 : :
3778 : : // Fire ActiveTipChange now for the current chain tip to make sure clients are notified.
3779 : : // ActivateBestChain may call this as well, but not necessarily.
3780 [ + - ]: 148 : if (m_chainman.m_options.signals) {
3781 [ - + + - : 296 : m_chainman.m_options.signals->ActiveTipChange(*Assert(m_chain.Tip()), m_chainman.IsInitialBlockDownload());
+ - ]
3782 : : }
3783 : : }
3784 : : return true;
3785 [ + - ]: 300 : }
3786 : :
3787 : 5726 : void Chainstate::SetBlockFailureFlags(CBlockIndex* invalid_block)
3788 : : {
3789 : 5726 : AssertLockHeld(cs_main);
3790 : :
3791 [ + + + + ]: 11141816 : for (auto& [_, block_index] : m_blockman.m_block_index) {
3792 [ + + + + ]: 11136090 : if (invalid_block != &block_index && block_index.GetAncestor(invalid_block->nHeight) == invalid_block) {
3793 : 7756 : block_index.nStatus |= BLOCK_FAILED_VALID;
3794 : 7756 : m_blockman.m_dirty_blockindex.insert(&block_index);
3795 : : }
3796 : : }
3797 : 5726 : }
3798 : :
3799 : 32 : void Chainstate::ResetBlockFailureFlags(CBlockIndex *pindex) {
3800 : 32 : AssertLockHeld(cs_main);
3801 : :
3802 : 32 : int nHeight = pindex->nHeight;
3803 : :
3804 : : // Remove the invalidity flag from this block and all its descendants and ancestors.
3805 [ + + + + ]: 5878 : for (auto& [_, block_index] : m_blockman.m_block_index) {
3806 [ + + + + : 5846 : if ((block_index.nStatus & BLOCK_FAILED_VALID) && (block_index.GetAncestor(nHeight) == pindex || pindex->GetAncestor(block_index.nHeight) == &block_index)) {
+ + ]
3807 : 1238 : block_index.nStatus &= ~BLOCK_FAILED_VALID;
3808 : 1238 : m_blockman.m_dirty_blockindex.insert(&block_index);
3809 [ + - + + : 2473 : if (block_index.IsValid(BLOCK_VALID_TRANSACTIONS) && block_index.HaveNumChainTxs() && setBlockIndexCandidates.value_comp()(m_chain.Tip(), &block_index)) {
+ - - + +
+ ]
3810 : 1229 : setBlockIndexCandidates.insert(&block_index);
3811 : : }
3812 [ + + ]: 1238 : if (&block_index == m_chainman.m_best_invalid) {
3813 : : // Reset invalid block marker if it was pointing to one of those.
3814 : 32 : m_chainman.m_best_invalid = nullptr;
3815 : : }
3816 : : }
3817 : : }
3818 : 32 : }
3819 : :
3820 : 337111 : void Chainstate::TryAddBlockIndexCandidate(CBlockIndex* pindex)
3821 : : {
3822 : 337111 : AssertLockHeld(cs_main);
3823 : :
3824 : : // Do not continue building a chainstate that is based on an invalid
3825 : : // snapshot. This is a belt-and-suspenders type of check because if an
3826 : : // invalid snapshot is loaded, the node will shut down to force a manual
3827 : : // intervention. But it is good to handle this case correctly regardless.
3828 [ + - ]: 337111 : if (m_assumeutxo == Assumeutxo::INVALID) {
3829 : : return;
3830 : : }
3831 : :
3832 : : // The block only is a candidate for the most-work-chain if it has the same
3833 : : // or more work than our current tip.
3834 [ - + + - : 672448 : if (m_chain.Tip() != nullptr && setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) {
+ + ]
3835 : : return;
3836 : : }
3837 : :
3838 : 130942 : const CBlockIndex* target_block{TargetBlock()};
3839 [ + + ]: 130942 : if (!target_block) {
3840 : : // If no specific target block, add all entries that have more
3841 : : // work than the tip.
3842 : 127945 : setBlockIndexCandidates.insert(pindex);
3843 : : } else {
3844 : : // If there is a target block, only consider connecting blocks
3845 : : // towards the target block.
3846 [ + + ]: 2997 : if (target_block->GetAncestor(pindex->nHeight) == pindex) {
3847 : 810 : setBlockIndexCandidates.insert(pindex);
3848 : : }
3849 : : }
3850 : : }
3851 : :
3852 : : /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
3853 : 131502 : void ChainstateManager::ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos)
3854 : : {
3855 : 131502 : AssertLockHeld(cs_main);
3856 [ - + ]: 131502 : pindexNew->nTx = block.vtx.size();
3857 : : // Typically m_chain_tx_count will be 0 at this point, but it can be nonzero if this
3858 : : // is a pruned block which is being downloaded again, or if this is an
3859 : : // assumeutxo snapshot block which has a hardcoded m_chain_tx_count value from the
3860 : : // snapshot metadata. If the pindex is not the snapshot block and the
3861 : : // m_chain_tx_count value is not zero, assert that value is actually correct.
3862 : 132708 : auto prev_tx_sum = [](CBlockIndex& block) { return block.nTx + (block.pprev ? block.pprev->m_chain_tx_count : 0); };
3863 [ + + + + : 132177 : if (!Assume(pindexNew->m_chain_tx_count == 0 || pindexNew->m_chain_tx_count == prev_tx_sum(*pindexNew) ||
+ - + + +
- - + ]
3864 : : std::ranges::any_of(m_chainstates, [&](const auto& cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->SnapshotBase() == pindexNew; }))) {
3865 [ # # # # ]: 0 : LogWarning("Internal bug detected: block %d has unexpected m_chain_tx_count %i that should be %i (%s %s). Please report this issue here: %s\n",
3866 : : pindexNew->nHeight, pindexNew->m_chain_tx_count, prev_tx_sum(*pindexNew), CLIENT_NAME, FormatFullVersion(), CLIENT_BUGREPORT);
3867 : 0 : pindexNew->m_chain_tx_count = 0;
3868 : : }
3869 : 131502 : pindexNew->nFile = pos.nFile;
3870 : 131502 : pindexNew->nDataPos = pos.nPos;
3871 : 131502 : pindexNew->nUndoPos = 0;
3872 : 131502 : pindexNew->nStatus |= BLOCK_HAVE_DATA;
3873 [ + + ]: 131502 : if (DeploymentActiveAt(*pindexNew, *this, Consensus::DEPLOYMENT_SEGWIT)) {
3874 : 127925 : pindexNew->nStatus |= BLOCK_OPT_WITNESS;
3875 : : }
3876 : 131502 : pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
3877 : 131502 : m_blockman.m_dirty_blockindex.insert(pindexNew);
3878 : :
3879 [ + + + + ]: 131502 : if (pindexNew->pprev == nullptr || pindexNew->pprev->HaveNumChainTxs()) {
3880 : : // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3881 : 127000 : std::deque<CBlockIndex*> queue;
3882 [ + - ]: 127000 : queue.push_back(pindexNew);
3883 : :
3884 : : // Recursively process any descendant blocks that now may be eligible to be connected.
3885 [ + + ]: 258693 : while (!queue.empty()) {
3886 : 131693 : CBlockIndex *pindex = queue.front();
3887 : 131693 : queue.pop_front();
3888 : : // Before setting m_chain_tx_count, assert that it is 0 or already set to
3889 : : // the correct value. This assert will fail after receiving the
3890 : : // assumeutxo snapshot block if assumeutxo snapshot metadata has an
3891 : : // incorrect hardcoded AssumeutxoData::m_chain_tx_count value.
3892 [ + + + - : 133433 : if (!Assume(pindex->m_chain_tx_count == 0 || pindex->m_chain_tx_count == prev_tx_sum(*pindex))) {
+ - - + ]
3893 [ # # # # : 0 : LogWarning("Internal bug detected: block %d has unexpected m_chain_tx_count %i that should be %i (%s %s). Please report this issue here: %s\n",
# # ]
3894 : : pindex->nHeight, pindex->m_chain_tx_count, prev_tx_sum(*pindex), CLIENT_NAME, FormatFullVersion(), CLIENT_BUGREPORT);
3895 : : }
3896 [ + + ]: 131693 : pindex->m_chain_tx_count = prev_tx_sum(*pindex);
3897 : 131693 : pindex->nSequenceId = nBlockSequenceId++;
3898 [ + + ]: 266064 : for (const auto& c : m_chainstates) {
3899 [ + - ]: 134371 : c->TryAddBlockIndexCandidate(pindex);
3900 : : }
3901 : 131693 : std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = m_blockman.m_blocks_unlinked.equal_range(pindex);
3902 [ + + ]: 136386 : while (range.first != range.second) {
3903 : 4693 : std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3904 [ + - ]: 4693 : queue.push_back(it->second);
3905 : 4693 : range.first++;
3906 : 4693 : m_blockman.m_blocks_unlinked.erase(it);
3907 : : }
3908 : : }
3909 : 127000 : } else {
3910 [ + - + - ]: 4502 : if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3911 : 4502 : m_blockman.AddUnlinkedBlock(pindexNew);
3912 : : }
3913 : : }
3914 : 131502 : }
3915 : :
3916 : 401836 : static bool CheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
3917 : : {
3918 : : // Check proof of work matches claimed amount
3919 [ + + + + ]: 401836 : if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
3920 [ + - + - ]: 7 : return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "high-hash", "proof of work failed");
3921 : :
3922 : : return true;
3923 : : }
3924 : :
3925 : 218690 : static bool CheckMerkleRoot(const CBlock& block, BlockValidationState& state)
3926 : : {
3927 [ + + ]: 218690 : if (block.m_checked_merkle_root) return true;
3928 : :
3929 : 160175 : bool mutated;
3930 : 160175 : uint256 merkle_root = BlockMerkleRoot(block, &mutated);
3931 [ + + ]: 160175 : if (block.hashMerkleRoot != merkle_root) {
3932 [ + - ]: 17 : return state.Invalid(
3933 : : /*result=*/BlockValidationResult::BLOCK_MUTATED,
3934 [ + - ]: 34 : /*reject_reason=*/"bad-txnmrklroot",
3935 : 34 : /*debug_message=*/"hashMerkleRoot mismatch");
3936 : : }
3937 : :
3938 : : // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3939 : : // of transactions in a block without affecting the merkle root of a block,
3940 : : // while still invalidating it.
3941 [ + + ]: 160158 : if (mutated) {
3942 [ + - ]: 15 : return state.Invalid(
3943 : : /*result=*/BlockValidationResult::BLOCK_MUTATED,
3944 [ + - ]: 30 : /*reject_reason=*/"bad-txns-duplicate",
3945 : 30 : /*debug_message=*/"duplicate transaction");
3946 : : }
3947 : :
3948 : 160143 : block.m_checked_merkle_root = true;
3949 : 160143 : return true;
3950 : : }
3951 : :
3952 : : /** CheckWitnessMalleation performs checks for block malleation with regard to
3953 : : * its witnesses.
3954 : : *
3955 : : * Note: If the witness commitment is expected (i.e. `expect_witness_commitment
3956 : : * = true`), then the block is required to have at least one transaction and the
3957 : : * first transaction needs to have at least one input. */
3958 : 237802 : static bool CheckWitnessMalleation(const CBlock& block, bool expect_witness_commitment, BlockValidationState& state)
3959 : : {
3960 [ + + ]: 237802 : if (expect_witness_commitment) {
3961 [ + + ]: 232850 : if (block.m_checked_witness_commitment) return true;
3962 : :
3963 : 144227 : int commitpos = GetWitnessCommitmentIndex(block);
3964 [ + + ]: 144227 : if (commitpos != NO_WITNESS_COMMITMENT) {
3965 [ + - - + ]: 111108 : assert(!block.vtx.empty() && !block.vtx[0]->vin.empty());
3966 [ - + ]: 111108 : const auto& witness_stack{block.vtx[0]->vin[0].scriptWitness.stack};
3967 : :
3968 [ - + + + : 111108 : if (witness_stack.size() != 1 || witness_stack[0].size() != 32) {
- + - + ]
3969 [ + - ]: 7 : return state.Invalid(
3970 : : /*result=*/BlockValidationResult::BLOCK_MUTATED,
3971 [ + - ]: 14 : /*reject_reason=*/"bad-witness-nonce-size",
3972 : 14 : /*debug_message=*/strprintf("%s : invalid witness reserved value size", __func__));
3973 : : }
3974 : :
3975 : : // The malleation check is ignored; as the transaction tree itself
3976 : : // already does not permit it, it is impossible to trigger in the
3977 : : // witness tree.
3978 : 111101 : uint256 hash_witness = BlockWitnessMerkleRoot(block);
3979 : :
3980 [ - + ]: 111101 : CHash256().Write(hash_witness).Write(witness_stack[0]).Finalize(hash_witness);
3981 [ - + + + ]: 222202 : if (memcmp(hash_witness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3982 [ + - ]: 5 : return state.Invalid(
3983 : : /*result=*/BlockValidationResult::BLOCK_MUTATED,
3984 [ + - ]: 10 : /*reject_reason=*/"bad-witness-merkle-match",
3985 : 10 : /*debug_message=*/strprintf("%s : witness merkle commitment mismatch", __func__));
3986 : : }
3987 : :
3988 : 111096 : block.m_checked_witness_commitment = true;
3989 : 111096 : return true;
3990 : : }
3991 : : }
3992 : :
3993 : : // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3994 [ + + ]: 117522 : for (const auto& tx : block.vtx) {
3995 [ + + ]: 79457 : if (tx->HasWitness()) {
3996 [ + - ]: 6 : return state.Invalid(
3997 : : /*result=*/BlockValidationResult::BLOCK_MUTATED,
3998 [ + - ]: 12 : /*reject_reason=*/"unexpected-witness",
3999 : 12 : /*debug_message=*/strprintf("%s : unexpected witness data found", __func__));
4000 : : }
4001 : : }
4002 : :
4003 : : return true;
4004 : : }
4005 : :
4006 : 515968 : bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
4007 : : {
4008 : : // These are checks that are independent of context.
4009 : :
4010 [ + + ]: 515968 : if (block.fChecked)
4011 : : return true;
4012 : :
4013 : : // Check that the header is valid (particularly PoW). This is mostly
4014 : : // redundant with the call in AcceptBlockHeader.
4015 [ + + ]: 256370 : if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
4016 : : return false;
4017 : :
4018 : : // Signet only: check block solution
4019 [ + + + + : 256363 : if (consensusParams.signet_blocks && fCheckPOW && !CheckSignetBlockSolution(block, consensusParams)) {
+ + ]
4020 [ + - + - ]: 1 : return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-signet-blksig", "signet block signature validation failure");
4021 : : }
4022 : :
4023 : : // Check the merkle root.
4024 [ + + + + ]: 256362 : if (fCheckMerkleRoot && !CheckMerkleRoot(block, state)) {
4025 : : return false;
4026 : : }
4027 : :
4028 : : // All potential-corruption validation must be done before we do any
4029 : : // transaction validation, as otherwise we may mark the header as invalid
4030 : : // because we receive the wrong transactions for it.
4031 : : // Note that witness malleability is checked in ContextualCheckBlock, so no
4032 : : // checks that use witness data may be performed here.
4033 : :
4034 : : // Size limits
4035 [ + + - + : 256353 : if (block.vtx.empty() || block.vtx.size() * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT || ::GetSerializeSize(TX_NO_WITNESS(block)) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)
+ - + + ]
4036 [ + - + - ]: 4 : return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-length", "size limits failed");
4037 : :
4038 : : // First transaction must be coinbase, the rest must not be
4039 [ + - + + ]: 256349 : if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
4040 [ + - + - ]: 4 : return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-missing", "first tx is not coinbase");
4041 [ - + + + ]: 343809 : for (unsigned int i = 1; i < block.vtx.size(); i++)
4042 [ + + ]: 87466 : if (block.vtx[i]->IsCoinBase())
4043 [ + - + - ]: 2 : return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple", "more than one coinbase");
4044 : :
4045 : : // Check transactions
4046 : : // Must check for duplicate inputs (see CVE-2018-17144)
4047 [ + + ]: 600107 : for (const auto& tx : block.vtx) {
4048 [ + - ]: 343805 : TxValidationState tx_state;
4049 [ + - + + ]: 343805 : if (!CheckTransaction(*tx, tx_state)) {
4050 : : // CheckBlock() does context-free validation checks. The only
4051 : : // possible failures are consensus failures.
4052 [ - + ]: 41 : assert(tx_state.GetResult() == TxValidationResult::TX_CONSENSUS);
4053 [ - + + - ]: 82 : return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, tx_state.GetRejectReason(),
4054 [ + - + - ]: 82 : strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), tx_state.GetDebugMessage()));
4055 : : }
4056 : 343805 : }
4057 : : // This underestimates the number of sigops, because unlike ConnectBlock it
4058 : : // does not count witness and p2sh sigops.
4059 : 256302 : unsigned int nSigOps = 0;
4060 [ + + ]: 600015 : for (const auto& tx : block.vtx)
4061 : : {
4062 : 343713 : nSigOps += GetLegacySigOpCount(*tx);
4063 : : }
4064 [ + + ]: 256302 : if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
4065 [ + - + - ]: 8 : return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "out-of-bounds SigOpCount");
4066 : :
4067 [ + + ]: 256294 : if (fCheckPOW && fCheckMerkleRoot)
4068 : 159746 : block.fChecked = true;
4069 : :
4070 : : return true;
4071 : : }
4072 : :
4073 : 86038 : void ChainstateManager::UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const
4074 : : {
4075 : 86038 : int commitpos = GetWitnessCommitmentIndex(block);
4076 [ + + + - : 86038 : static const std::vector<unsigned char> nonce(32, 0x00);
+ - ]
4077 [ + + + + : 86038 : if (commitpos != NO_WITNESS_COMMITMENT && DeploymentActiveAfter(pindexPrev, *this, Consensus::DEPLOYMENT_SEGWIT) && !block.vtx[0]->HasWitness()) {
+ + ]
4078 : 48789 : CMutableTransaction tx(*block.vtx[0]);
4079 [ + - ]: 48789 : tx.vin[0].scriptWitness.stack.resize(1);
4080 [ + - ]: 48789 : tx.vin[0].scriptWitness.stack[0] = nonce;
4081 [ + - - + ]: 97578 : block.vtx[0] = MakeTransactionRef(std::move(tx));
4082 : 48789 : }
4083 : 86038 : }
4084 : :
4085 : 58009 : void ChainstateManager::GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const
4086 : : {
4087 : 58009 : int commitpos = GetWitnessCommitmentIndex(block);
4088 : 58009 : std::vector<unsigned char> ret(32, 0x00);
4089 [ + - ]: 58009 : if (commitpos == NO_WITNESS_COMMITMENT) {
4090 [ + - ]: 58009 : uint256 witnessroot = BlockWitnessMerkleRoot(block);
4091 [ + - + - : 58009 : CHash256().Write(witnessroot).Write(ret).Finalize(witnessroot);
- + + - +
- ]
4092 : 58009 : CTxOut out;
4093 : 58009 : out.nValue = 0;
4094 : 58009 : out.scriptPubKey.resize(MINIMUM_WITNESS_COMMITMENT);
4095 [ + - ]: 58009 : out.scriptPubKey[0] = OP_RETURN;
4096 [ + - ]: 58009 : out.scriptPubKey[1] = 0x24;
4097 [ + - ]: 58009 : out.scriptPubKey[2] = 0xaa;
4098 [ + - ]: 58009 : out.scriptPubKey[3] = 0x21;
4099 [ + - ]: 58009 : out.scriptPubKey[4] = 0xa9;
4100 [ + - ]: 58009 : out.scriptPubKey[5] = 0xed;
4101 [ + - + - ]: 116018 : memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
4102 [ + - ]: 58009 : CMutableTransaction tx(*block.vtx[0]);
4103 [ + - ]: 58009 : tx.vout.push_back(out);
4104 [ + - - + ]: 116018 : block.vtx[0] = MakeTransactionRef(std::move(tx));
4105 : 58009 : }
4106 [ + - ]: 58009 : UpdateUncommittedBlockStructures(block, pindexPrev);
4107 : 58009 : }
4108 : :
4109 : 9755 : bool HasValidProofOfWork(std::span<const CBlockHeader> headers, const Consensus::Params& consensusParams)
4110 : : {
4111 : 9755 : return std::ranges::all_of(headers,
4112 : 588088 : [&](const auto& header) { return CheckProofOfWork(header.GetHash(), header.nBits, consensusParams); });
4113 : : }
4114 : :
4115 : 58563 : bool IsBlockMutated(const CBlock& block, bool check_witness_root)
4116 : : {
4117 [ + - ]: 58563 : BlockValidationState state;
4118 [ + - + + ]: 58563 : if (!CheckMerkleRoot(block, state)) {
4119 [ + - + - : 23 : LogDebug(BCLog::VALIDATION, "Block mutated: %s\n", state.ToString());
+ - + - ]
4120 : 23 : return true;
4121 : : }
4122 : :
4123 [ + + + + ]: 58540 : if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
4124 : : // Consider the block mutated if any transaction is 64 bytes in size (see 3.1
4125 : : // in "Weaknesses in Bitcoin’s Merkle Root Construction":
4126 : : // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/attachments/20190225/a27d8837/attachment-0001.pdf).
4127 : : //
4128 : : // Note: This is not a consensus change as this only applies to blocks that
4129 : : // don't have a coinbase transaction and would therefore already be invalid.
4130 : 5 : return std::any_of(block.vtx.begin(), block.vtx.end(),
4131 : 9 : [](auto& tx) { return GetSerializeSize(TX_NO_WITNESS(tx)) == 64; });
4132 : : } else {
4133 : : // Theoretically it is still possible for a block with a 64 byte
4134 : : // coinbase transaction to be mutated but we neglect that possibility
4135 : : // here as it requires at least 224 bits of work.
4136 : : }
4137 : :
4138 [ + - + + ]: 58535 : if (!CheckWitnessMalleation(block, check_witness_root, state)) {
4139 [ + - + - : 12 : LogDebug(BCLog::VALIDATION, "Block mutated: %s\n", state.ToString());
+ - + - ]
4140 : 12 : return true;
4141 : : }
4142 : :
4143 : : return false;
4144 : 58563 : }
4145 : :
4146 : 2083 : arith_uint256 CalculateClaimedHeadersWork(std::span<const CBlockHeader> headers)
4147 : : {
4148 : 2083 : arith_uint256 total_work{0};
4149 [ + + ]: 530078 : for (const CBlockHeader& header : headers) {
4150 : 527995 : total_work += GetBlockProof(header);
4151 : : }
4152 : 2083 : return total_work;
4153 : : }
4154 : :
4155 : : /** Context-dependent validity checks.
4156 : : * By "context", we mean only the previous block headers, but not the UTXO
4157 : : * set; UTXO-related validity checks are done in ConnectBlock().
4158 : : * NOTE: This function is not currently invoked by ConnectBlock(), so we
4159 : : * should consider upgrade issues if we change which consensus rules are
4160 : : * enforced in this function (eg by adding a new consensus rule). See comment
4161 : : * in ConnectBlock().
4162 : : * Note that -reindex-chainstate skips the validation that happens here!
4163 : : *
4164 : : * NOTE: failing to check the header's height against the last checkpoint's opened a DoS vector between
4165 : : * v0.12 and v0.15 (when no additional protection was in place) whereby an attacker could unboundedly
4166 : : * grow our in-memory block index. See https://bitcoincore.org/en/2024/07/03/disclose-header-spam.
4167 : : */
4168 : 193733 : static bool ContextualCheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const ChainstateManager& chainman, const CBlockIndex* pindexPrev) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
4169 : : {
4170 : 193733 : AssertLockHeld(::cs_main);
4171 [ - + ]: 193733 : assert(pindexPrev != nullptr);
4172 : 193733 : const int nHeight = pindexPrev->nHeight + 1;
4173 : :
4174 : : // Check proof of work
4175 : 193733 : const Consensus::Params& consensusParams = chainman.GetConsensus();
4176 [ + + ]: 193733 : if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
4177 [ + - + - ]: 4 : return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits", "incorrect proof of work");
4178 : :
4179 : : // Check timestamp against prev
4180 [ + + ]: 193729 : if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
4181 [ + - + - ]: 5 : return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-too-old", "block's timestamp is too early");
4182 : :
4183 : : // Testnet4 and regtest only: Check timestamp against prev for difficulty-adjustment
4184 : : // blocks to prevent timewarp attacks (see https://github.com/bitcoin/bitcoin/pull/15482).
4185 [ + + ]: 193724 : if (consensusParams.enforce_BIP94) {
4186 : : // Check timestamp for the first block of each difficulty adjustment
4187 : : // interval, except the genesis block.
4188 [ + + ]: 509 : if (nHeight % consensusParams.DifficultyAdjustmentInterval() == 0) {
4189 [ + + ]: 9 : if (block.GetBlockTime() < pindexPrev->GetBlockTime() - MAX_TIMEWARP) {
4190 [ + - + - ]: 2 : return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-timewarp-attack", "block's timestamp is too early on diff adjustment block");
4191 : : }
4192 : : }
4193 : : }
4194 : :
4195 : : // Check timestamp
4196 [ + + ]: 193722 : if (block.Time() > NodeClock::now() + std::chrono::seconds{MAX_FUTURE_BLOCK_TIME}) {
4197 [ + - + - ]: 15 : return state.Invalid(BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new", "block timestamp too far in the future");
4198 : : }
4199 : :
4200 : : // Reject blocks with outdated version
4201 [ + + + + ]: 193707 : if ((block.nVersion < 2 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_HEIGHTINCB)) ||
4202 [ + + + + : 387413 : (block.nVersion < 3 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_DERSIG)) ||
+ + ]
4203 [ + + ]: 4 : (block.nVersion < 4 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_CLTV))) {
4204 [ + - + - ]: 3 : return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, strprintf("bad-version(0x%08x)", block.nVersion),
4205 : 6 : strprintf("rejected nVersion=0x%08x block", block.nVersion));
4206 : : }
4207 : :
4208 : : return true;
4209 : : }
4210 : :
4211 : : /** NOTE: This function is not currently invoked by ConnectBlock(), so we
4212 : : * should consider upgrade issues if we change which consensus rules are
4213 : : * enforced in this function (eg by adding a new consensus rule). See comment
4214 : : * in ConnectBlock().
4215 : : * Note that -reindex-chainstate skips the validation that happens here!
4216 : : */
4217 : 179275 : static bool ContextualCheckBlock(const CBlock& block, BlockValidationState& state, const ChainstateManager& chainman, const CBlockIndex* pindexPrev)
4218 : : {
4219 [ + + ]: 179275 : const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
4220 : :
4221 : : // Enforce BIP113 (Median Time Past).
4222 : 179275 : bool enforce_locktime_median_time_past{false};
4223 [ + + ]: 179275 : if (DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_CSV)) {
4224 [ - + ]: 175740 : assert(pindexPrev != nullptr);
4225 : : enforce_locktime_median_time_past = true;
4226 : : }
4227 : :
4228 : 179275 : const int64_t nLockTimeCutoff{enforce_locktime_median_time_past ?
4229 : 175740 : pindexPrev->GetMedianTimePast() :
4230 : 3535 : block.GetBlockTime()};
4231 : :
4232 : : // Check that all transactions are finalized
4233 [ + + ]: 424059 : for (const auto& tx : block.vtx) {
4234 [ + + ]: 244791 : if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
4235 [ + - + - ]: 7 : return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal", "non-final transaction");
4236 : : }
4237 : : }
4238 : :
4239 : : // Enforce rule that the coinbase starts with serialized block height
4240 [ + + ]: 179268 : if (DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_HEIGHTINCB))
4241 : : {
4242 [ + - ]: 176988 : CScript expect = CScript() << nHeight;
4243 [ + + - + : 353976 : if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
+ + + - ]
4244 [ + + - + ]: 353974 : !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
4245 [ + - + - : 1 : return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-height", "block height mismatch in coinbase");
+ - ]
4246 : : }
4247 : 176988 : }
4248 : :
4249 : : // Validation for witness commitments.
4250 : : // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
4251 : : // coinbase (where 0x0000....0000 is used instead).
4252 : : // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness reserved value (unconstrained).
4253 : : // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
4254 : : // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
4255 : : // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness reserved value). In case there are
4256 : : // multiple, the last one is used.
4257 [ + + ]: 179267 : if (!CheckWitnessMalleation(block, DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_SEGWIT), state)) {
4258 : : return false;
4259 : : }
4260 : :
4261 : : // After the coinbase witness reserved value and commitment are verified,
4262 : : // we can check if the block weight passes (before we've checked the
4263 : : // coinbase witness, it would be possible for the weight to be too
4264 : : // large by filling up the coinbase witness, which doesn't change
4265 : : // the block hash, so we couldn't mark the block as permanently
4266 : : // failed).
4267 [ + + ]: 179261 : if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
4268 [ + - + - ]: 1 : return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-weight", strprintf("%s : weight limit failed", __func__));
4269 : : }
4270 : :
4271 : : return true;
4272 : : }
4273 : :
4274 : 269442 : bool ChainstateManager::AcceptBlockHeader(const CBlockHeader& block, BlockValidationState& state, CBlockIndex** ppindex, bool min_pow_checked)
4275 : : {
4276 : 269442 : AssertLockHeld(cs_main);
4277 : :
4278 : : // Check for duplicate
4279 : 269442 : uint256 hash = block.GetHash();
4280 : 269442 : BlockMap::iterator miSelf{m_blockman.m_block_index.find(hash)};
4281 [ + + ]: 269442 : if (hash != GetConsensus().hashGenesisBlock) {
4282 [ + + ]: 269424 : if (miSelf != m_blockman.m_block_index.end()) {
4283 : : // Block header is already known.
4284 [ + - ]: 123958 : CBlockIndex* pindex = &(miSelf->second);
4285 [ + - ]: 123958 : if (ppindex)
4286 : 123958 : *ppindex = pindex;
4287 [ + + ]: 123958 : if (pindex->nStatus & BLOCK_FAILED_VALID) {
4288 [ + - + - ]: 117 : LogDebug(BCLog::VALIDATION, "%s: block %s is marked invalid\n", __func__, hash.ToString());
4289 [ + - + - ]: 117 : return state.Invalid(BlockValidationResult::BLOCK_CACHED_INVALID, "duplicate-invalid",
4290 [ + - ]: 234 : strprintf("block %s was previously marked invalid", hash.ToString()));
4291 : : }
4292 : : return true;
4293 : : }
4294 : :
4295 [ - + ]: 145466 : if (!CheckBlockHeader(block, state, GetConsensus())) {
4296 [ # # # # : 0 : LogDebug(BCLog::VALIDATION, "%s: Consensus::CheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
# # ]
4297 : 0 : return false;
4298 : : }
4299 : :
4300 : : // Get prev block index
4301 : 145466 : CBlockIndex* pindexPrev = nullptr;
4302 : 145466 : BlockMap::iterator mi{m_blockman.m_block_index.find(block.hashPrevBlock)};
4303 [ + + ]: 145466 : if (mi == m_blockman.m_block_index.end()) {
4304 [ + - + - : 3 : LogDebug(BCLog::VALIDATION, "header %s has prev block not found: %s\n", hash.ToString(), block.hashPrevBlock.ToString());
+ - ]
4305 [ + - + - ]: 3 : return state.Invalid(BlockValidationResult::BLOCK_MISSING_PREV, "prev-blk-not-found");
4306 : : }
4307 [ + + ]: 145463 : pindexPrev = &((*mi).second);
4308 [ + + ]: 145463 : if (pindexPrev->nStatus & BLOCK_FAILED_VALID) {
4309 [ + - + - : 5 : LogDebug(BCLog::VALIDATION, "header %s has prev block invalid: %s\n", hash.ToString(), block.hashPrevBlock.ToString());
+ - ]
4310 [ + - + - ]: 5 : return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
4311 : : }
4312 [ + + ]: 145458 : if (!ContextualCheckBlockHeader(block, state, *this, pindexPrev)) {
4313 [ + + + - : 25 : LogDebug(BCLog::VALIDATION, "%s: Consensus::ContextualCheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
+ - ]
4314 : 25 : return false;
4315 : : }
4316 : : }
4317 [ + + ]: 145451 : if (!min_pow_checked) {
4318 [ + - + - ]: 1 : LogDebug(BCLog::VALIDATION, "%s: not adding new block header %s, missing anti-dos proof-of-work validation\n", __func__, hash.ToString());
4319 [ + - + - ]: 1 : return state.Invalid(BlockValidationResult::BLOCK_HEADER_LOW_WORK, "too-little-chainwork");
4320 : : }
4321 : 145450 : CBlockIndex* pindex{m_blockman.AddToBlockIndex(block, m_best_header)};
4322 : :
4323 [ + - ]: 145450 : if (ppindex)
4324 : 145450 : *ppindex = pindex;
4325 : :
4326 : : return true;
4327 : : }
4328 : :
4329 : : // Exposed wrapper for AcceptBlockHeader
4330 : 37839 : bool ChainstateManager::ProcessNewBlockHeaders(std::span<const CBlockHeader> headers, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex)
4331 : : {
4332 : 37839 : AssertLockNotHeld(cs_main);
4333 : 37839 : {
4334 : 37839 : LOCK(cs_main);
4335 [ + + ]: 158587 : for (const CBlockHeader& header : headers) {
4336 : 120842 : CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
4337 [ + - ]: 120842 : bool accepted{AcceptBlockHeader(header, state, &pindex, min_pow_checked)};
4338 [ + - ]: 120842 : CheckBlockIndex();
4339 : :
4340 [ + + ]: 120842 : if (!accepted) {
4341 [ + - ]: 94 : return false;
4342 : : }
4343 [ + + ]: 120748 : if (ppindex) {
4344 : 117572 : *ppindex = pindex;
4345 : : }
4346 : : }
4347 : 94 : }
4348 [ + + ]: 37745 : if (NotifyHeaderTip()) {
4349 [ + + + + : 26642 : if (IsInitialBlockDownload() && ppindex && *ppindex) {
+ - ]
4350 : 1043 : const CBlockIndex& last_accepted{**ppindex};
4351 : 1043 : int64_t blocks_left{(NodeClock::now() - last_accepted.Time()) / GetConsensus().PowTargetSpacing()};
4352 [ + + ]: 1043 : blocks_left = std::max<int64_t>(0, blocks_left);
4353 : 1043 : const double progress{100.0 * last_accepted.nHeight / (last_accepted.nHeight + blocks_left)};
4354 : 1043 : LogInfo("Synchronizing blockheaders, height: %d (~%.2f%%)\n", last_accepted.nHeight, progress);
4355 : : }
4356 : : }
4357 : : return true;
4358 : : }
4359 : :
4360 : 7 : void ChainstateManager::ReportHeadersPresync(int64_t height, int64_t timestamp)
4361 : : {
4362 : 7 : AssertLockNotHeld(GetMutex());
4363 : 7 : {
4364 : 7 : LOCK(GetMutex());
4365 : : // Don't report headers presync progress if we already have a post-minchainwork header chain.
4366 : : // This means we lose reporting for potentially legitimate, but unlikely, deep reorgs, but
4367 : : // prevent attackers that spam low-work headers from filling our logs.
4368 [ + - + - : 7 : if (m_best_header->nChainWork >= UintToArith256(GetConsensus().nMinimumChainWork)) return;
- + ]
4369 : : // Rate limit headers presync updates to 4 per second, as these are not subject to DoS
4370 : : // protection.
4371 : 0 : auto now = MockableSteadyClock::now();
4372 [ # # ]: 0 : if (now < m_last_presync_update + std::chrono::milliseconds{250}) return;
4373 [ # # ]: 0 : m_last_presync_update = now;
4374 : 7 : }
4375 : 0 : bool initial_download = IsInitialBlockDownload();
4376 : 0 : GetNotifications().headerTip(GetSynchronizationState(initial_download, m_blockman.m_blockfiles_indexed), height, timestamp, /*presync=*/true);
4377 [ # # ]: 0 : if (initial_download) {
4378 : 0 : int64_t blocks_left{(NodeClock::now() - NodeSeconds{std::chrono::seconds{timestamp}}) / GetConsensus().PowTargetSpacing()};
4379 [ # # ]: 0 : blocks_left = std::max<int64_t>(0, blocks_left);
4380 : 0 : const double progress{100.0 * height / (height + blocks_left)};
4381 : 0 : LogInfo("Pre-synchronizing blockheaders, height: %d (~%.2f%%)\n", height, progress);
4382 : : }
4383 : : }
4384 : :
4385 : : /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
4386 : 148600 : bool ChainstateManager::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock, bool min_pow_checked)
4387 : : {
4388 [ + + ]: 148600 : const CBlock& block = *pblock;
4389 : :
4390 [ + + ]: 148600 : if (fNewBlock) *fNewBlock = false;
4391 : 148600 : AssertLockHeld(cs_main);
4392 : :
4393 : 148600 : CBlockIndex *pindexDummy = nullptr;
4394 [ + + ]: 148600 : CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
4395 : :
4396 : 148600 : bool accepted_header{AcceptBlockHeader(block, state, &pindex, min_pow_checked)};
4397 : 148600 : CheckBlockIndex();
4398 : :
4399 [ + + ]: 148600 : if (!accepted_header)
4400 : : return false;
4401 : :
4402 : : // Check all requested blocks that we do not already have for validity and
4403 : : // save them to disk. Skip processing of unrequested blocks as an anti-DoS
4404 : : // measure, unless the blocks have more work than the active chain tip, and
4405 : : // aren't too far ahead of it, so are likely to be attached soon.
4406 : 148543 : bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
4407 [ + + + + ]: 148543 : bool fHasMoreOrSameWork = (ActiveTip() ? pindex->nChainWork >= ActiveTip()->nChainWork : true);
4408 : : // Blocks that are too out-of-order needlessly limit the effectiveness of
4409 : : // pruning, because pruning will not delete block files that contain any
4410 : : // blocks which are too close in height to the tip. Apply this test
4411 : : // regardless of whether pruning is enabled; it should generally be safe to
4412 : : // not process unrequested blocks.
4413 : 148543 : bool fTooFarAhead{pindex->nHeight > ActiveHeight() + int(MIN_BLOCKS_TO_KEEP)};
4414 : :
4415 : : // TODO: Decouple this function from the block download logic by removing fRequested
4416 : : // This requires some new chain data structure to efficiently look up if a
4417 : : // block is in a chain leading to a candidate for best tip, despite not
4418 : : // being such a candidate itself.
4419 : : // Note that this would break the getblockfrompeer RPC
4420 : :
4421 : : // TODO: deal better with return value and error conditions for duplicate
4422 : : // and unrequested blocks.
4423 [ + + ]: 148543 : if (fAlreadyHave) return true;
4424 [ + + ]: 131012 : if (!fRequested) { // If we didn't ask for it:
4425 [ + - ]: 733 : if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
4426 [ + + ]: 733 : if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
4427 [ + + ]: 726 : if (fTooFarAhead) return true; // Block height is too high
4428 : :
4429 : : // Protect against DoS attacks from low-work chains.
4430 : : // If our tip is behind, a peer could try to send us
4431 : : // low-work blocks on a fake chain that we would never
4432 : : // request; don't process these.
4433 [ + - ]: 725 : if (pindex->nChainWork < MinimumChainWork()) return true;
4434 : : }
4435 : :
4436 : 131004 : const CChainParams& params{GetParams()};
4437 : :
4438 [ + - + + ]: 262008 : if (!CheckBlock(block, state, params.GetConsensus()) ||
4439 : 131004 : !ContextualCheckBlock(block, state, *this, pindex->pprev)) {
4440 [ + - ]: 14 : if (Assume(state.IsInvalid())) {
4441 : 14 : ActiveChainstate().InvalidBlockFound(pindex, state);
4442 : : }
4443 [ + - ]: 14 : LogError("%s: %s\n", __func__, state.ToString());
4444 : 14 : return false;
4445 : : }
4446 : :
4447 : : // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
4448 : : // (but if it does not build on our best tip, let the SendMessages loop relay it)
4449 [ + + + + : 130990 : if (!IsInitialBlockDownload() && ActiveTip() == pindex->pprev && m_options.signals) {
+ - ]
4450 : 106386 : m_options.signals->NewPoWValidBlock(pindex, pblock);
4451 : : }
4452 : :
4453 : : // Write block to history file
4454 [ + + ]: 130990 : if (fNewBlock) *fNewBlock = true;
4455 : 130990 : try {
4456 : 130990 : FlatFilePos blockPos{};
4457 [ + + ]: 130990 : if (dbp) {
4458 : 2085 : blockPos = *dbp;
4459 [ + - ]: 2085 : m_blockman.UpdateBlockInfo(block, pindex->nHeight, blockPos);
4460 : : } else {
4461 [ + - ]: 128905 : blockPos = m_blockman.WriteBlock(block, pindex->nHeight);
4462 [ - + ]: 128905 : if (blockPos.IsNull()) {
4463 [ # # ]: 0 : state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
4464 : 0 : return false;
4465 : : }
4466 : : }
4467 [ + - ]: 130990 : ReceivedBlockTransactions(block, pindex, blockPos);
4468 [ - - ]: 0 : } catch (const std::runtime_error& e) {
4469 [ - - - - ]: 0 : return FatalError(GetNotifications(), state, strprintf(_("System error while saving block to disk: %s"), e.what()));
4470 : 0 : }
4471 : :
4472 : : // TODO: FlushStateToDisk() handles flushing of both block and chainstate
4473 : : // data, so we should move this to ChainstateManager so that we can be more
4474 : : // intelligent about how we flush.
4475 : : // For now, since FlushStateMode::NONE is used, all that can happen is that
4476 : : // the block files may be pruned, so we can just call this on one
4477 : : // chainstate (particularly if we haven't implemented pruning with
4478 : : // background validation yet).
4479 : : //
4480 : : // Flush errors (e.g. low disk space during pruning) are ignored, so that
4481 : : // callers can't mistreat a flush failure as a block validation failure.
4482 : : // The fatal error notification inside FlushStateToDisk still fires,
4483 : : // so the node will shut down on unrecoverable flush errors regardless.
4484 : : // For state a dummy value is used, and the return value is ignored.
4485 [ + - ]: 130990 : BlockValidationState flush_state_ignore;
4486 [ + - + - ]: 130990 : (void)ActiveChainstate().FlushStateToDisk(flush_state_ignore, FlushStateMode::NONE);
4487 : :
4488 [ + - ]: 130990 : CheckBlockIndex();
4489 : :
4490 : 130990 : return true;
4491 : 130990 : }
4492 : :
4493 : 146471 : bool ChainstateManager::ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block)
4494 : : {
4495 : 146471 : AssertLockNotHeld(cs_main);
4496 : :
4497 : 146471 : {
4498 : 146471 : CBlockIndex *pindex = nullptr;
4499 [ + + ]: 146471 : if (new_block) *new_block = false;
4500 [ + - ]: 146471 : BlockValidationState state;
4501 : :
4502 : : // CheckBlock() does not support multi-threaded block validation because CBlock::fChecked can cause data race.
4503 : : // Therefore, the following critical section must include the CheckBlock() call as well.
4504 [ + - ]: 146471 : LOCK(cs_main);
4505 : :
4506 : : // Skipping AcceptBlock() for CheckBlock() failures means that we will never mark a block as invalid if
4507 : : // CheckBlock() fails. This is protective against consensus failure if there are any unknown forms of block
4508 : : // malleability that cause CheckBlock() to fail; see e.g. CVE-2012-2459 and
4509 : : // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-February/016697.html. Because CheckBlock() is
4510 : : // not very expensive, the anti-DoS benefits of caching failure (of a definitely-invalid block) are not substantial.
4511 [ + - ]: 146471 : bool ret = CheckBlock(*block, state, GetConsensus());
4512 [ + + ]: 146471 : if (ret) {
4513 : : // Store to disk
4514 [ + - ]: 146406 : ret = AcceptBlock(block, state, &pindex, force_processing, nullptr, new_block, min_pow_checked);
4515 : : }
4516 [ + + ]: 146406 : if (!ret) {
4517 [ + - ]: 132 : if (m_options.signals) {
4518 [ + - ]: 132 : m_options.signals->BlockChecked(block, state);
4519 : : }
4520 [ + - + - ]: 132 : LogError("%s: AcceptBlock FAILED (%s)\n", __func__, state.ToString());
4521 [ + - ]: 132 : return false;
4522 : : }
4523 : 146603 : }
4524 : :
4525 : 146339 : NotifyHeaderTip();
4526 : :
4527 [ + - ]: 146339 : BlockValidationState state; // Only used to report errors, not invalidity - ignore it
4528 [ + - + - : 439017 : if (!ActiveChainstate().ActivateBestChain(state, block)) {
+ - + - +
+ ]
4529 [ + - + - ]: 1 : LogError("%s: ActivateBestChain failed (%s)\n", __func__, state.ToString());
4530 : 1 : return false;
4531 : : }
4532 : :
4533 [ + - + - ]: 292676 : Chainstate* bg_chain{WITH_LOCK(cs_main, return HistoricalChainstate())};
4534 [ + + ]: 146338 : BlockValidationState bg_state;
4535 [ + + + - : 150346 : if (bg_chain && !bg_chain->ActivateBestChain(bg_state, block)) {
+ - - + -
+ ]
4536 [ # # # # ]: 0 : LogError("%s: [background] ActivateBestChain failed (%s)\n", __func__, bg_state.ToString());
4537 : 0 : return false;
4538 : : }
4539 : :
4540 : : return true;
4541 : 292677 : }
4542 : :
4543 : 50670 : MempoolAcceptResult ChainstateManager::ProcessTransaction(const CTransactionRef& tx, bool test_accept)
4544 : : {
4545 : 50670 : AssertLockHeld(cs_main);
4546 : 50670 : Chainstate& active_chainstate = ActiveChainstate();
4547 [ - + ]: 50670 : if (!active_chainstate.GetMempool()) {
4548 [ # # ]: 0 : TxValidationState state;
4549 [ # # # # : 0 : state.Invalid(TxValidationResult::TX_NO_MEMPOOL, "no-mempool");
# # ]
4550 [ # # # # ]: 0 : return MempoolAcceptResult::Failure(state);
4551 : 0 : }
4552 : 50670 : auto result = AcceptToMemoryPool(active_chainstate, tx, GetTime(), /*bypass_limits=*/ false, test_accept);
4553 [ - + + - : 50670 : active_chainstate.GetMempool()->check(active_chainstate.CoinsTip(), active_chainstate.m_chain.Height() + 1);
+ - ]
4554 [ + - ]: 50670 : return result;
4555 : 50670 : }
4556 : :
4557 : :
4558 : 48284 : BlockValidationState TestBlockValidity(
4559 : : Chainstate& chainstate,
4560 : : const CBlock& block,
4561 : : const bool check_pow,
4562 : : const bool check_merkle_root)
4563 : : {
4564 : : // Lock must be held throughout this function for two reasons:
4565 : : // 1. We don't want the tip to change during several of the validation steps
4566 : : // 2. To prevent a CheckBlock() race condition for fChecked, see ProcessNewBlock()
4567 : 48284 : AssertLockHeld(chainstate.m_chainman.GetMutex());
4568 : :
4569 [ - + ]: 48284 : BlockValidationState state;
4570 [ - + + - ]: 96568 : CBlockIndex* tip{Assert(chainstate.m_chain.Tip())};
4571 : :
4572 [ + - + + ]: 48284 : if (block.hashPrevBlock != *Assert(tip->phashBlock)) {
4573 [ + - + - : 2 : state.Invalid({}, "inconclusive-not-best-prevblk");
+ - ]
4574 : 1 : return state;
4575 : : }
4576 : :
4577 : : // For signets CheckBlock() verifies the challenge iff fCheckPow is set.
4578 [ + - + + ]: 48283 : if (!CheckBlock(block, state, chainstate.m_chainman.GetConsensus(), /*fCheckPow=*/check_pow, /*fCheckMerkleRoot=*/check_merkle_root)) {
4579 : : // This should never happen, but belt-and-suspenders don't approve the
4580 : : // block if it does.
4581 [ - + ]: 8 : if (state.IsValid()) NONFATAL_UNREACHABLE();
4582 : : return state;
4583 : : }
4584 : :
4585 : : /**
4586 : : * At this point ProcessNewBlock would call AcceptBlock(), but we
4587 : : * don't want to store the block or its header. Run individual checks
4588 : : * instead:
4589 : : * - skip AcceptBlockHeader() because:
4590 : : * - we don't want to update the block index
4591 : : * - we do not care about duplicates
4592 : : * - we already ran CheckBlockHeader() via CheckBlock()
4593 : : * - we already checked for prev-blk-not-found
4594 : : * - we know the tip is valid, so no need to check bad-prevblk
4595 : : * - we already ran CheckBlock()
4596 : : * - do run ContextualCheckBlockHeader()
4597 : : * - do run ContextualCheckBlock()
4598 : : */
4599 : :
4600 [ + - + + ]: 48275 : if (!ContextualCheckBlockHeader(block, state, chainstate.m_chainman, tip)) {
4601 [ - + ]: 4 : if (state.IsValid()) NONFATAL_UNREACHABLE();
4602 : : return state;
4603 : : }
4604 : :
4605 [ + - + + ]: 48271 : if (!ContextualCheckBlock(block, state, chainstate.m_chainman, tip)) {
4606 [ - + ]: 1 : if (state.IsValid()) NONFATAL_UNREACHABLE();
4607 : : return state;
4608 : : }
4609 : :
4610 : : // We don't want ConnectBlock to update the actual chainstate, so create
4611 : : // a cache on top of it, along with a dummy block index.
4612 : 48270 : CBlockIndex index_dummy{block};
4613 [ + - ]: 48270 : uint256 block_hash(block.GetHash());
4614 : 48270 : index_dummy.pprev = tip;
4615 : 48270 : index_dummy.nHeight = tip->nHeight + 1;
4616 : 48270 : index_dummy.phashBlock = &block_hash;
4617 [ + - + - ]: 48270 : CCoinsViewCache view_dummy(&chainstate.CoinsTip());
4618 : :
4619 : : // Set fJustCheck to true in order to update, and not clear, validation caches.
4620 [ + - + + ]: 48270 : if(!chainstate.ConnectBlock(block, state, &index_dummy, view_dummy, /*fJustCheck=*/true)) {
4621 [ - + ]: 308 : if (state.IsValid()) NONFATAL_UNREACHABLE();
4622 : : return state;
4623 : : }
4624 : :
4625 : : // Ensure no check returned successfully while also setting an invalid state.
4626 [ - + ]: 47962 : if (!state.IsValid()) NONFATAL_UNREACHABLE();
4627 : :
4628 : : return state;
4629 : 48270 : }
4630 : :
4631 : : /* This function is called from the RPC code for pruneblockchain */
4632 : 33 : void PruneBlockFilesManual(Chainstate& active_chainstate, int nManualPruneHeight)
4633 : : {
4634 [ + - ]: 33 : BlockValidationState state;
4635 [ + - - + ]: 33 : if (!active_chainstate.FlushStateToDisk(
4636 : : state, FlushStateMode::NONE, nManualPruneHeight)) {
4637 [ # # # # ]: 0 : LogWarning("Failed to flush state after manual prune (%s)", state.ToString());
4638 : : }
4639 : 33 : }
4640 : :
4641 : 867 : bool Chainstate::LoadChainTip()
4642 : : {
4643 : 867 : AssertLockHeld(cs_main);
4644 : 867 : const CCoinsViewCache& coins_cache = CoinsTip();
4645 [ - + ]: 1734 : assert(!coins_cache.GetBestBlock().IsNull()); // Never called when the coins view is empty
4646 [ - + ]: 867 : CBlockIndex* tip = m_chain.Tip();
4647 : :
4648 [ - - - - ]: 867 : if (tip && tip->GetBlockHash() == coins_cache.GetBestBlock()) {
4649 : : return true;
4650 : : }
4651 : :
4652 : : // Load pointer to end of best chain
4653 : 867 : CBlockIndex* pindex = m_blockman.LookupBlockIndex(coins_cache.GetBestBlock());
4654 [ + + ]: 867 : if (!pindex) {
4655 : : return false;
4656 : : }
4657 : 865 : m_chain.SetTip(*pindex);
4658 : 865 : m_chainman.UpdateIBDStatus();
4659 : 865 : m_last_flushed_block = pindex;
4660 [ - + ]: 865 : tip = m_chain.Tip();
4661 : :
4662 : : // nSequenceId is one of the keys used to sort setBlockIndexCandidates. Ensure all
4663 : : // candidate sets are empty to avoid UB, as nSequenceId is about to be modified.
4664 [ + + ]: 1743 : for (const auto& cs : m_chainman.m_chainstates) {
4665 [ - + ]: 878 : assert(cs->setBlockIndexCandidates.empty());
4666 : : }
4667 : :
4668 : : // Make sure our chain tip before shutting down scores better than any other candidate
4669 : : // to maintain a consistent best tip over reboots in case of a tie.
4670 : : auto target = tip;
4671 [ + + ]: 197786 : while (target) {
4672 : 196921 : target->nSequenceId = SEQ_ID_BEST_CHAIN_FROM_DISK;
4673 : 196921 : target = target->pprev;
4674 : : }
4675 : :
4676 [ - + + - : 865 : LogInfo("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f",
+ - ]
4677 : : tip->GetBlockHash().ToString(),
4678 : : m_chain.Height(),
4679 : : FormatISO8601DateTime(tip->GetBlockTime()),
4680 : : m_chainman.GuessVerificationProgress(tip));
4681 : :
4682 : : // Ensure KernelNotifications m_tip_block is set even if no new block arrives.
4683 [ + + ]: 865 : if (!this->GetRole().historical) {
4684 : : // Ignoring return value for now.
4685 : 859 : (void)m_chainman.GetNotifications().blockTip(
4686 : 859 : /*state=*/GetSynchronizationState(/*init=*/true, m_chainman.m_blockman.m_blockfiles_indexed),
4687 : : /*index=*/*pindex,
4688 : : /*verification_progress=*/m_chainman.GuessVerificationProgress(tip));
4689 : : }
4690 : :
4691 : 865 : CheckForkWarningConditions();
4692 : :
4693 : 865 : return true;
4694 : : }
4695 : :
4696 : 858 : CVerifyDB::CVerifyDB(Notifications& notifications)
4697 : 858 : : m_notifications{notifications}
4698 : : {
4699 [ + - ]: 858 : m_notifications.progress(_("Verifying blocks…"), 0, false);
4700 : 858 : }
4701 : :
4702 : 858 : CVerifyDB::~CVerifyDB()
4703 : : {
4704 : 858 : m_notifications.progress(bilingual_str{}, 100, false);
4705 : 858 : }
4706 : :
4707 : 858 : VerifyDBResult CVerifyDB::VerifyDB(
4708 : : Chainstate& chainstate,
4709 : : const Consensus::Params& consensus_params,
4710 : : CCoinsView& coinsview,
4711 : : int nCheckLevel, int nCheckDepth)
4712 : : {
4713 : 858 : AssertLockHeld(cs_main);
4714 : :
4715 [ - + + - : 2439 : if (chainstate.m_chain.Tip() == nullptr || chainstate.m_chain.Tip()->pprev == nullptr) {
+ + ]
4716 : : return VerifyDBResult::SUCCESS;
4717 : : }
4718 : :
4719 : : // Verify blocks in the best chain
4720 [ + + + + ]: 723 : if (nCheckDepth <= 0 || nCheckDepth > chainstate.m_chain.Height()) {
4721 : 19 : nCheckDepth = chainstate.m_chain.Height();
4722 : : }
4723 [ + + + - ]: 1442 : nCheckLevel = std::max(0, std::min(4, nCheckLevel));
4724 : 723 : LogInfo("Verifying last %i blocks at level %i", nCheckDepth, nCheckLevel);
4725 : 723 : CCoinsViewCache coins(&coinsview);
4726 : 723 : CBlockIndex* pindex;
4727 : 723 : CBlockIndex* pindexFailure = nullptr;
4728 : 723 : int nGoodTransactions = 0;
4729 [ + - ]: 723 : BlockValidationState state;
4730 : 723 : int reportDone = 0;
4731 : 723 : bool skipped_no_block_data{false};
4732 : 723 : bool skipped_l3_checks{false};
4733 [ + - ]: 723 : LogInfo("Verification progress: 0%%");
4734 : :
4735 [ - + ]: 723 : const bool is_snapshot_cs{chainstate.m_from_snapshot_blockhash};
4736 : :
4737 [ - + + - : 7576 : for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
+ + ]
4738 [ - + + + : 18479 : const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
+ + + + ]
4739 [ + + ]: 6835 : if (reportDone < percentageDone / 10) {
4740 : : // report every 10% step
4741 [ + - ]: 4231 : LogInfo("Verification progress: %d%%", percentageDone);
4742 : 4231 : reportDone = percentageDone / 10;
4743 : : }
4744 [ + - + - ]: 6835 : m_notifications.progress(_("Verifying blocks…"), percentageDone, false);
4745 [ - + + + ]: 6835 : if (pindex->nHeight <= chainstate.m_chain.Height() - nCheckDepth) {
4746 : : break;
4747 : : }
4748 [ + + + + : 6138 : if ((chainstate.m_blockman.IsPruneMode() || is_snapshot_cs) && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
+ + ]
4749 : : // If pruning or running under an assumeutxo snapshot, only go
4750 : : // back as far as we have data.
4751 [ + - ]: 3 : LogInfo("Block verification stopping at height %d (no data). This could be due to pruning or use of an assumeutxo snapshot.", pindex->nHeight);
4752 : : skipped_no_block_data = true;
4753 : : break;
4754 : : }
4755 : 6135 : CBlock block;
4756 : : // check level 0: read from disk
4757 [ + - + + ]: 6135 : if (!chainstate.m_blockman.ReadBlock(block, *pindex)) {
4758 [ + - + - ]: 1 : LogError("Verification error: ReadBlock failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4759 : 1 : return VerifyDBResult::CORRUPTED_BLOCK_DB;
4760 : : }
4761 : : // check level 1: verify block validity
4762 [ + - + - : 6134 : if (nCheckLevel >= 1 && !CheckBlock(block, state, consensus_params)) {
+ - ]
4763 [ # # # # : 0 : LogError("Verification error: found bad block at %d, hash=%s (%s)",
# # ]
4764 : : pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
4765 : 0 : return VerifyDBResult::CORRUPTED_BLOCK_DB;
4766 : : }
4767 : : // check level 2: verify undo validity
4768 [ + - ]: 6134 : if (nCheckLevel >= 2 && pindex) {
4769 : 6134 : CBlockUndo undo;
4770 [ + - ]: 6134 : if (!pindex->GetUndoPos().IsNull()) {
4771 [ + - + + ]: 6134 : if (!chainstate.m_blockman.ReadBlockUndo(undo, *pindex)) {
4772 [ + - + - ]: 1 : LogError("Verification error: found bad undo data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4773 : 1 : return VerifyDBResult::CORRUPTED_BLOCK_DB;
4774 : : }
4775 : : }
4776 : 6134 : }
4777 : : // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
4778 [ + - + - : 6133 : size_t curr_coins_usage = coins.DynamicMemoryUsage() + chainstate.CoinsTip().DynamicMemoryUsage();
+ - ]
4779 : :
4780 [ + + ]: 6133 : if (nCheckLevel >= 3) {
4781 [ + - ]: 5928 : if (curr_coins_usage <= chainstate.m_coinstip_cache_size_bytes) {
4782 [ + - ]: 5928 : assert(coins.GetBestBlock() == pindex->GetBlockHash());
4783 [ + - ]: 5928 : DisconnectResult res = chainstate.DisconnectBlock(block, pindex, coins);
4784 [ - + ]: 5928 : if (res == DISCONNECT_FAILED) {
4785 [ # # # # ]: 0 : LogError("Verification error: irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4786 : 0 : return VerifyDBResult::CORRUPTED_BLOCK_DB;
4787 : : }
4788 [ - + ]: 5928 : if (res == DISCONNECT_UNCLEAN) {
4789 : 0 : nGoodTransactions = 0;
4790 : 0 : pindexFailure = pindex;
4791 : : } else {
4792 [ - + ]: 5928 : nGoodTransactions += block.vtx.size();
4793 : : }
4794 : : } else {
4795 : : skipped_l3_checks = true;
4796 : : }
4797 : : }
4798 [ + - + + ]: 6133 : if (chainstate.m_chainman.m_interrupt) return VerifyDBResult::INTERRUPTED;
4799 : 6135 : }
4800 [ - + ]: 718 : if (pindexFailure) {
4801 [ - - - - ]: 723 : LogError("Verification error: coin database inconsistencies found (last %i blocks, %i good transactions before that)", chainstate.m_chain.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
4802 : : return VerifyDBResult::CORRUPTED_BLOCK_DB;
4803 : : }
4804 [ - + ]: 718 : if (skipped_l3_checks) {
4805 [ # # ]: 0 : LogWarning("Skipped verification of level >=3 (insufficient database cache size). Consider increasing -dbcache.");
4806 : : }
4807 : :
4808 : : // store block count as we move pindex at check level >= 4
4809 [ - + ]: 718 : int block_count = chainstate.m_chain.Height() - pindex->nHeight;
4810 : :
4811 : : // check level 4: try reconnecting blocks
4812 [ + + + - ]: 718 : if (nCheckLevel >= 4 && !skipped_l3_checks) {
4813 [ - + + + ]: 2250 : while (pindex != chainstate.m_chain.Tip()) {
4814 [ + + + - ]: 2158 : const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
4815 [ + + ]: 1122 : if (reportDone < percentageDone / 10) {
4816 : : // report every 10% step
4817 [ + - ]: 12 : LogInfo("Verification progress: %d%%", percentageDone);
4818 : 12 : reportDone = percentageDone / 10;
4819 : : }
4820 [ + - + - ]: 1122 : m_notifications.progress(_("Verifying blocks…"), percentageDone, false);
4821 : 1122 : pindex = chainstate.m_chain.Next(*pindex);
4822 : 1122 : CBlock block;
4823 [ + - - + ]: 1122 : if (!chainstate.m_blockman.ReadBlock(block, *pindex)) {
4824 [ # # # # ]: 0 : LogError("Verification error: ReadBlock failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4825 : 0 : return VerifyDBResult::CORRUPTED_BLOCK_DB;
4826 : : }
4827 [ + - - + ]: 1122 : if (!chainstate.ConnectBlock(block, state, pindex, coins)) {
4828 [ # # # # : 0 : LogError("Verification error: found unconnectable block at %d, hash=%s (%s)", pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
# # ]
4829 : 0 : return VerifyDBResult::CORRUPTED_BLOCK_DB;
4830 : : }
4831 [ + - + - ]: 1122 : if (chainstate.m_chainman.m_interrupt) return VerifyDBResult::INTERRUPTED;
4832 : 1122 : }
4833 : : }
4834 : :
4835 [ + - ]: 718 : LogInfo("Verification: checked last %i blocks at level %i", block_count, nCheckLevel);
4836 [ + + + - ]: 718 : if (nCheckLevel >= 3 && !skipped_l3_checks) {
4837 [ + - ]: 717 : LogInfo("Verification: no coin database inconsistencies (%i transactions)", nGoodTransactions);
4838 : : }
4839 : :
4840 [ - + ]: 718 : if (skipped_l3_checks) {
4841 : 0 : return VerifyDBResult::SKIPPED_L3_CHECKS;
4842 : : }
4843 [ + + ]: 718 : if (skipped_no_block_data) {
4844 : 3 : return VerifyDBResult::SKIPPED_MISSING_BLOCKS;
4845 : : }
4846 : : return VerifyDBResult::SUCCESS;
4847 : 723 : }
4848 : :
4849 : : /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
4850 : 0 : bool Chainstate::RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs)
4851 : : {
4852 : 0 : AssertLockHeld(cs_main);
4853 : : // TODO: merge with ConnectBlock
4854 : 0 : CBlock block;
4855 [ # # # # ]: 0 : if (!m_blockman.ReadBlock(block, *pindex)) {
4856 [ # # # # ]: 0 : LogError("ReplayBlock(): ReadBlock failed at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4857 : 0 : return false;
4858 : : }
4859 : :
4860 [ # # ]: 0 : for (const CTransactionRef& tx : block.vtx) {
4861 [ # # ]: 0 : if (!tx->IsCoinBase()) {
4862 [ # # ]: 0 : for (const CTxIn &txin : tx->vin) {
4863 [ # # ]: 0 : inputs.SpendCoin(txin.prevout);
4864 : : }
4865 : : }
4866 : : // Pass check = true as every addition may be an overwrite.
4867 [ # # ]: 0 : AddCoins(inputs, *tx, pindex->nHeight, true);
4868 : : }
4869 : : return true;
4870 : 0 : }
4871 : :
4872 : 1402 : bool Chainstate::ReplayBlocks()
4873 : : {
4874 : 1402 : LOCK(cs_main);
4875 : :
4876 [ + - ]: 1402 : CCoinsView& db = this->CoinsDB();
4877 [ + - ]: 1402 : CCoinsViewCache cache(&db);
4878 : :
4879 [ + - ]: 1402 : std::vector<uint256> hashHeads = db.GetHeadBlocks();
4880 [ - + ]: 1402 : if (hashHeads.empty()) return true; // We're already in a consistent state.
4881 [ # # # # ]: 0 : if (hashHeads.size() != 2) {
4882 [ # # ]: 0 : LogError("ReplayBlocks(): unknown inconsistent state\n");
4883 : : return false;
4884 : : }
4885 : :
4886 [ # # # # ]: 0 : m_chainman.GetNotifications().progress(_("Replaying blocks…"), 0, false);
4887 [ # # ]: 0 : LogInfo("Replaying blocks");
4888 : :
4889 : 0 : const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
4890 : 0 : const CBlockIndex* pindexNew; // New tip during the interrupted flush.
4891 : 0 : const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
4892 : :
4893 [ # # ]: 0 : if (!m_blockman.m_block_index.contains(hashHeads[0])) {
4894 [ # # ]: 0 : LogError("ReplayBlocks(): reorganization to unknown block requested\n");
4895 : : return false;
4896 : : }
4897 [ # # ]: 0 : pindexNew = &(m_blockman.m_block_index[hashHeads[0]]);
4898 : :
4899 [ # # ]: 0 : if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
4900 [ # # ]: 0 : if (!m_blockman.m_block_index.contains(hashHeads[1])) {
4901 [ - - ]: 1402 : LogError("ReplayBlocks(): reorganization from unknown block requested\n");
4902 : : return false;
4903 : : }
4904 [ # # ]: 0 : pindexOld = &(m_blockman.m_block_index[hashHeads[1]]);
4905 [ # # ]: 0 : pindexFork = LastCommonAncestor(pindexOld, pindexNew);
4906 [ # # ]: 0 : assert(pindexFork != nullptr);
4907 : : }
4908 : :
4909 : : // Rollback along the old branch.
4910 : 0 : const int nForkHeight{pindexFork ? pindexFork->nHeight : 0};
4911 [ # # ]: 0 : if (pindexOld != pindexFork) {
4912 [ # # # # ]: 0 : LogInfo("Rolling back from %s (%i to %i)", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight, nForkHeight);
4913 [ # # ]: 0 : while (pindexOld != pindexFork) {
4914 [ # # ]: 0 : if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
4915 : 0 : CBlock block;
4916 [ # # # # ]: 0 : if (!m_blockman.ReadBlock(block, *pindexOld)) {
4917 [ # # # # ]: 0 : LogError("RollbackBlock(): ReadBlock() failed at %d, hash=%s\n", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4918 : 0 : return false;
4919 : : }
4920 [ # # ]: 0 : if (pindexOld->nHeight % 10'000 == 0) {
4921 [ # # # # ]: 0 : LogInfo("Rolling back %s (%i)", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
4922 : : }
4923 [ # # ]: 0 : DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
4924 [ # # ]: 0 : if (res == DISCONNECT_FAILED) {
4925 [ # # # # ]: 0 : LogError("RollbackBlock(): DisconnectBlock failed at %d, hash=%s\n", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4926 : 0 : return false;
4927 : : }
4928 : : // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
4929 : : // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
4930 : : // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
4931 : : // the result is still a version of the UTXO set with the effects of that block undone.
4932 : 0 : }
4933 : 0 : pindexOld = pindexOld->pprev;
4934 : : }
4935 [ # # # # ]: 0 : LogInfo("Rolled back to %s", pindexFork->GetBlockHash().ToString());
4936 : : }
4937 : :
4938 : : // Roll forward from the forking point to the new tip.
4939 [ # # ]: 0 : if (nForkHeight < pindexNew->nHeight) {
4940 [ # # # # ]: 0 : LogInfo("Rolling forward to %s (%i to %i)", pindexNew->GetBlockHash().ToString(), nForkHeight, pindexNew->nHeight);
4941 [ # # ]: 0 : for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
4942 [ # # # # ]: 0 : const CBlockIndex& pindex{*Assert(pindexNew->GetAncestor(nHeight))};
4943 : :
4944 [ # # ]: 0 : if (nHeight % 10'000 == 0) {
4945 [ # # # # ]: 0 : LogInfo("Rolling forward %s (%i)", pindex.GetBlockHash().ToString(), nHeight);
4946 : : }
4947 [ # # # # ]: 0 : m_chainman.GetNotifications().progress(_("Replaying blocks…"), (int)((nHeight - nForkHeight) * 100.0 / (pindexNew->nHeight - nForkHeight)), false);
4948 [ # # # # ]: 0 : if (!RollforwardBlock(&pindex, cache)) return false;
4949 : : }
4950 [ # # # # ]: 0 : LogInfo("Rolled forward to %s", pindexNew->GetBlockHash().ToString());
4951 : : }
4952 : :
4953 [ # # ]: 0 : cache.SetBestBlock(pindexNew->GetBlockHash());
4954 [ # # ]: 0 : cache.Flush(/*reallocate_cache=*/false); // local CCoinsViewCache goes out of scope
4955 [ # # ]: 0 : m_chainman.GetNotifications().progress(bilingual_str{}, 100, false);
4956 : 0 : return true;
4957 [ + - ]: 2804 : }
4958 : :
4959 : 1400 : bool Chainstate::NeedsRedownload() const
4960 : : {
4961 : 1400 : AssertLockHeld(cs_main);
4962 : :
4963 : : // At and above m_params.SegwitHeight, segwit consensus rules must be validated
4964 [ - + ]: 1400 : CBlockIndex* block{m_chain.Tip()};
4965 : :
4966 [ + + + + ]: 198185 : while (block != nullptr && DeploymentActiveAt(*block, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) {
4967 [ + + ]: 196786 : if (!(block->nStatus & BLOCK_OPT_WITNESS)) {
4968 : : // block is insufficiently validated for a segwit client
4969 : : return true;
4970 : : }
4971 : 196785 : block = block->pprev;
4972 : : }
4973 : :
4974 : : return false;
4975 : : }
4976 : :
4977 : 8 : void Chainstate::ClearBlockIndexCandidates()
4978 : : {
4979 : 8 : AssertLockHeld(::cs_main);
4980 : 8 : setBlockIndexCandidates.clear();
4981 : 8 : }
4982 : :
4983 : 1421 : void Chainstate::PopulateBlockIndexCandidates()
4984 : : {
4985 : 1421 : AssertLockHeld(::cs_main);
4986 : :
4987 [ + + ]: 209493 : for (CBlockIndex* pindex : m_blockman.GetAllBlockIndices()) {
4988 : : // With assumeutxo, the snapshot block is a candidate for the tip, but it
4989 : : // may not have BLOCK_VALID_TRANSACTIONS (e.g. if we haven't yet downloaded
4990 : : // the block), so we special-case it here.
4991 [ + - + + ]: 208072 : if (pindex == SnapshotBase() ||
4992 [ + + ]: 411840 : (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) &&
4993 [ + + - + ]: 203768 : (pindex->HaveNumChainTxs() || pindex->pprev == nullptr))) {
4994 [ + - ]: 202740 : TryAddBlockIndexCandidate(pindex);
4995 : : }
4996 : : }
4997 : 1421 : }
4998 : :
4999 : 1407 : bool ChainstateManager::LoadBlockIndex()
5000 : : {
5001 : 1407 : AssertLockHeld(cs_main);
5002 : : // Load block index from databases
5003 [ + + ]: 1407 : if (m_blockman.m_blockfiles_indexed) {
5004 : 1388 : bool ret{m_blockman.LoadBlockIndexDB(CurrentChainstate().m_from_snapshot_blockhash)};
5005 [ + + ]: 1388 : if (!ret) return false;
5006 : :
5007 : 1383 : m_blockman.ScanAndUnlinkAlreadyPrunedFiles();
5008 : :
5009 : 1383 : std::vector<CBlockIndex*> vSortedByHeight{m_blockman.GetAllBlockIndices()};
5010 [ + - ]: 1383 : std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
5011 : : CBlockIndexHeightOnlyComparator());
5012 : :
5013 [ + + ]: 203418 : for (CBlockIndex* pindex : vSortedByHeight) {
5014 [ + - - + ]: 202035 : if (m_interrupt) return false;
5015 [ + + + + : 202035 : if (pindex->nStatus & BLOCK_FAILED_VALID && (!m_best_invalid || pindex->nChainWork > m_best_invalid->nChainWork)) {
+ - + - ]
5016 : 843 : m_best_invalid = pindex;
5017 : : }
5018 [ + + + - : 400809 : if (pindex->IsValid(BLOCK_VALID_TREE) && (m_best_header == nullptr || CBlockIndexWorkComparator()(m_best_header, pindex)))
+ + + - +
+ ]
5019 : 198774 : m_best_header = pindex;
5020 : : }
5021 : 1383 : }
5022 : : return true;
5023 : : }
5024 : :
5025 : 1398 : bool ChainstateManager::LoadGenesisBlock()
5026 : : {
5027 : 1398 : LOCK(cs_main);
5028 : :
5029 [ + - ]: 1398 : const CBlock& genesis_block{GetParams().GenesisBlock()};
5030 : :
5031 : : // Check whether we're already initialized by checking for genesis in
5032 : : // m_blockman.m_block_index. Note that we can't use a chainstate's m_chain here, since it is
5033 : : // set based on the coins db, not the block index db, which is the only
5034 : : // thing loaded at this point.
5035 [ + - + + ]: 1398 : if (m_blockman.m_block_index.contains(genesis_block.GetHash())) {
5036 : : return true;
5037 : : }
5038 : :
5039 : 512 : try {
5040 [ + - ]: 512 : FlatFilePos blockPos{m_blockman.WriteBlock(genesis_block, 0)};
5041 [ - + ]: 512 : if (blockPos.IsNull()) {
5042 [ - - + - ]: 1398 : LogError("Writing genesis block to disk failed");
5043 : : return false;
5044 : : }
5045 [ + - ]: 512 : CBlockIndex* pindex{m_blockman.AddToBlockIndex(genesis_block, m_best_header)};
5046 [ + - ]: 512 : ReceivedBlockTransactions(genesis_block, pindex, blockPos);
5047 [ - - ]: 0 : } catch (const std::runtime_error& e) {
5048 [ - - ]: 0 : LogError("Failed to write genesis block: %s", e.what());
5049 : 0 : return false;
5050 : 0 : }
5051 : :
5052 : : return true;
5053 : 1398 : }
5054 : :
5055 : 20 : void ChainstateManager::LoadExternalBlockFile(
5056 : : AutoFile& file_in,
5057 : : FlatFilePos* dbp,
5058 : : std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent)
5059 : : {
5060 : : // Either both should be specified (-reindex), or neither (-loadblock).
5061 [ - + ]: 20 : assert(!dbp == !blocks_with_unknown_parent);
5062 : :
5063 : 20 : const auto start{SteadyClock::now()};
5064 [ + - ]: 20 : const CChainParams& params{GetParams()};
5065 : :
5066 : 20 : int nLoaded = 0;
5067 : 20 : try {
5068 [ + - ]: 20 : BufferedFile blkdat{file_in, 2 * MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE + 8};
5069 : : // nRewind indicates where to resume scanning in case something goes wrong,
5070 : : // such as a block fails to deserialize.
5071 : 20 : uint64_t nRewind = blkdat.GetPos();
5072 [ + + ]: 6292780 : while (!blkdat.eof()) {
5073 [ + - + + ]: 6292779 : if (m_interrupt) return;
5074 : :
5075 : 6292776 : blkdat.SetPos(nRewind);
5076 : 6292776 : nRewind++; // start one byte further next time, in case of failure
5077 [ + + ]: 6292776 : blkdat.SetLimit(); // remove former limit
5078 : 6292776 : unsigned int nSize = 0;
5079 : 6292776 : try {
5080 : : // locate a header
5081 : 6292776 : MessageStartChars buf;
5082 [ + + ]: 6292776 : blkdat.FindByte(std::byte(params.MessageStart()[0]));
5083 [ + - ]: 6292760 : nRewind = blkdat.GetPos() + 1;
5084 [ + - ]: 6292760 : blkdat >> buf;
5085 [ + + ]: 6292760 : if (buf != params.MessageStart()) {
5086 : 6290570 : continue;
5087 : : }
5088 : : // read size
5089 [ + - ]: 2190 : blkdat >> nSize;
5090 [ - + ]: 2190 : if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
5091 : 0 : continue;
5092 [ - + ]: 16 : } catch (const std::exception&) {
5093 : : // no valid block header found; don't complain
5094 : : // (this happens at the end of every blk.dat file)
5095 : 16 : break;
5096 : 16 : }
5097 : 2190 : try {
5098 : : // read block header
5099 [ + + ]: 2190 : const uint64_t nBlockPos{blkdat.GetPos()};
5100 [ + + ]: 2190 : if (dbp)
5101 : 2089 : dbp->nPos = nBlockPos;
5102 [ + - ]: 2190 : blkdat.SetLimit(nBlockPos + nSize);
5103 : 2190 : CBlockHeader header;
5104 [ + - ]: 2190 : blkdat >> header;
5105 [ + - ]: 2190 : const uint256 hash{header.GetHash()};
5106 : : // Skip the rest of this block (this may read from disk into memory); position to the marker before the
5107 : : // next block, but it's still possible to rewind to the start of the current block (without a disk read).
5108 : 2190 : nRewind = nBlockPos + nSize;
5109 [ + - ]: 2190 : blkdat.SkipTo(nRewind);
5110 : :
5111 : 2190 : std::shared_ptr<CBlock> pblock{}; // needs to remain available after the cs_main lock is released to avoid duplicate reads from disk
5112 : :
5113 : 2190 : {
5114 [ + - ]: 2190 : LOCK(cs_main);
5115 : : // detect out of order blocks, and store them for later
5116 [ + + + - : 2190 : if (hash != params.GetConsensus().hashGenesisBlock && !m_blockman.LookupBlockIndex(header.hashPrevBlock)) {
+ + ]
5117 [ + - + - : 111 : LogDebug(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
+ - + - +
- ]
5118 : : header.hashPrevBlock.ToString());
5119 [ + - ]: 111 : if (dbp && blocks_with_unknown_parent) {
5120 [ + - ]: 111 : blocks_with_unknown_parent->emplace(header.hashPrevBlock, *dbp);
5121 : : }
5122 [ + - ]: 111 : continue;
5123 : : }
5124 : :
5125 : : // process in case the block isn't known yet
5126 [ + - ]: 2079 : const CBlockIndex* pindex = m_blockman.LookupBlockIndex(hash);
5127 [ + + - + ]: 2079 : if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) {
5128 : : // This block can be processed immediately; rewind to its start, read and deserialize it.
5129 : 2078 : blkdat.SetPos(nBlockPos);
5130 [ + - - + ]: 4156 : pblock = std::make_shared<CBlock>();
5131 [ + - ]: 2078 : blkdat >> TX_WITH_WITNESS(*pblock);
5132 [ + - ]: 2078 : nRewind = blkdat.GetPos();
5133 : :
5134 [ + - ]: 2078 : BlockValidationState state;
5135 [ + - + - : 6234 : if (AcceptBlock(pblock, state, nullptr, true, dbp, nullptr, true)) {
+ - + + ]
5136 : 2074 : nLoaded++;
5137 : : }
5138 [ + - ]: 2078 : if (state.IsError()) {
5139 : : break;
5140 : : }
5141 [ - - - + : 2079 : } else if (hash != params.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
- - + - ]
5142 [ # # # # : 0 : LogDebug(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
# # # # ]
5143 : : }
5144 : 111 : }
5145 : :
5146 : : // Activate the genesis block so normal node progress can continue
5147 : : // During first -reindex, this will only connect Genesis since
5148 : : // ActivateBestChain only connects blocks which are in the block tree db,
5149 : : // which only contains blocks whose parents are in it.
5150 : : // But do this only if genesis isn't activated yet, to avoid connecting many blocks
5151 : : // without assumevalid in the case of a continuation of a reindex that
5152 : : // was interrupted by the user.
5153 [ + + + - : 2111 : if (hash == params.GetConsensus().hashGenesisBlock && WITH_LOCK(::cs_main, return ActiveHeight()) == -1) {
+ + + - +
- ]
5154 [ + - ]: 15 : BlockValidationState state;
5155 [ + - + - : 15 : if (!ActiveChainstate().ActivateBestChain(state, nullptr)) {
- + + - ]
5156 : : break;
5157 : : }
5158 : 15 : }
5159 : :
5160 [ + + - + : 2079 : if (m_blockman.IsPruneMode() && m_blockman.m_blockfiles_indexed && pblock) {
- - ]
5161 : : // must update the tip for pruning to work while importing with -loadblock.
5162 : : // this is a tradeoff to conserve disk space at the expense of time
5163 : : // spent updating the tip to be able to prune.
5164 : : // otherwise, ActivateBestChain won't be called by the import process
5165 : : // until after all of the block files are loaded. ActivateBestChain can be
5166 : : // called by concurrent network message processing. but, that is not
5167 : : // reliable for the purpose of pruning while importing.
5168 [ # # # # ]: 0 : if (auto result{ActivateBestChains()}; !result) {
5169 [ # # # # : 0 : LogDebug(BCLog::REINDEX, "%s\n", util::ErrorString(result).original);
# # # # ]
5170 : 0 : break;
5171 : 0 : }
5172 : : }
5173 : :
5174 [ + - ]: 2079 : NotifyHeaderTip();
5175 : :
5176 [ + + ]: 2079 : if (!blocks_with_unknown_parent) continue;
5177 : :
5178 : : // Recursively process earlier encountered successors of this block
5179 [ + - ]: 1978 : std::deque<uint256> queue;
5180 [ + - ]: 1978 : queue.push_back(hash);
5181 [ + + ]: 4067 : while (!queue.empty()) {
5182 : 2089 : uint256 head = queue.front();
5183 : 2089 : queue.pop_front();
5184 : 2089 : auto range = blocks_with_unknown_parent->equal_range(head);
5185 [ + + ]: 2200 : while (range.first != range.second) {
5186 : 111 : std::multimap<uint256, FlatFilePos>::iterator it = range.first;
5187 [ + - ]: 111 : std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
5188 [ + - + - ]: 111 : if (m_blockman.ReadBlock(*pblockrecursive, it->second, {})) {
5189 [ + - ]: 111 : const auto& block_hash{pblockrecursive->GetHash()};
5190 [ + - + - : 111 : LogDebug(BCLog::REINDEX, "%s: Processing out of order child %s of %s", __func__, block_hash.ToString(), head.ToString());
+ - + - +
- ]
5191 [ + - ]: 111 : LOCK(cs_main);
5192 [ + - ]: 111 : BlockValidationState dummy;
5193 [ + - + - : 333 : if (AcceptBlock(pblockrecursive, dummy, nullptr, true, &it->second, nullptr, true)) {
+ - + - ]
5194 : 111 : nLoaded++;
5195 [ + - ]: 111 : queue.push_back(block_hash);
5196 : : }
5197 [ + - ]: 222 : }
5198 : 111 : range.first++;
5199 : 111 : blocks_with_unknown_parent->erase(it);
5200 [ + - ]: 111 : NotifyHeaderTip();
5201 : 111 : }
5202 : : }
5203 [ + - - - ]: 4168 : } catch (const std::exception& e) {
5204 : : // historical bugs added extra data to the block files that does not deserialize cleanly.
5205 : : // commonly this data is between readable blocks, but it does not really matter. such data is not fatal to the import process.
5206 : : // the code that reads the block files deals with invalid data by simply ignoring it.
5207 : : // it continues to search for the next {4 byte magic message start bytes + 4 byte length + block} that does deserialize cleanly
5208 : : // and passes all of the other block validation checks dealing with POW and the merkle root, etc...
5209 : : // we merely note with this informational log message when unexpected data is encountered.
5210 : : // we could also be experiencing a storage system read error, or a read of a previous bad write. these are possible, but
5211 : : // less likely scenarios. we don't have enough information to tell a difference here.
5212 : : // the reindex process is not the place to attempt to clean and/or compact the block files. if so desired, a studious node operator
5213 : : // may use knowledge of the fact that the block files are not entirely pristine in order to prepare a set of pristine, and
5214 : : // perhaps ordered, block files for later reindexing.
5215 [ - - - - : 0 : LogDebug(BCLog::REINDEX, "%s: unexpected data at file offset 0x%x - %s. continuing\n", __func__, (nRewind - 1), e.what());
- - ]
5216 : 0 : }
5217 : : }
5218 [ - - ]: 20 : } catch (const std::runtime_error& e) {
5219 [ - - - - ]: 0 : GetNotifications().fatalError(strprintf(_("System error while loading external block file: %s"), e.what()));
5220 : 0 : }
5221 : 17 : LogInfo("Loaded %i blocks from external file in %dms", nLoaded, Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
5222 : : }
5223 : :
5224 : 517461 : bool ChainstateManager::ShouldCheckBlockIndex() const
5225 : : {
5226 : : // Assert to verify Flatten() has been called.
5227 [ + + ]: 517461 : if (!*Assert(m_options.check_block_index)) return false;
5228 [ - + ]: 419925 : if (FastRandomContext().randrange(*m_options.check_block_index) >= 1) return false;
5229 : : return true;
5230 : : }
5231 : :
5232 : 517461 : void ChainstateManager::CheckBlockIndex() const
5233 : : {
5234 [ + + ]: 517461 : if (!ShouldCheckBlockIndex()) {
5235 : : return;
5236 : : }
5237 : :
5238 : 419925 : LOCK(cs_main);
5239 : :
5240 : : // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
5241 : : // so we have the genesis block in m_blockman.m_block_index but no active chain. (A few of the
5242 : : // tests when iterating the block tree require that m_chain has been initialized.)
5243 [ + - - + : 419925 : if (ActiveChain().Height() < 0) {
+ + ]
5244 [ - + ]: 28 : assert(m_blockman.m_block_index.size() <= 1);
5245 [ + - ]: 28 : return;
5246 : : }
5247 : :
5248 : : // Build forward-pointing data structure for the entire block tree.
5249 : : // For performance reasons, indexes of the best header chain are stored in a vector (within CChain).
5250 : : // All remaining blocks are stored in a multimap.
5251 : : // The best header chain can differ from the active chain: E.g. its entries may belong to blocks that
5252 : : // are not yet validated.
5253 : 419897 : CChain best_hdr_chain;
5254 [ - + ]: 419897 : assert(m_best_header);
5255 [ - + ]: 419897 : assert(!(m_best_header->nStatus & BLOCK_FAILED_VALID));
5256 [ + - ]: 419897 : best_hdr_chain.SetTip(*m_best_header);
5257 : :
5258 : 419897 : std::multimap<const CBlockIndex*, const CBlockIndex*> forward;
5259 [ + + + + ]: 309404583 : for (auto& [_, block_index] : m_blockman.m_block_index) {
5260 : : // Only save indexes in forward that are not part of the best header chain.
5261 [ + + ]: 308984686 : if (!best_hdr_chain.Contains(block_index)) {
5262 : : // Only genesis, which must be part of the best header chain, can have a nullptr parent.
5263 [ - + ]: 25804663 : assert(block_index.pprev);
5264 [ + - ]: 25804663 : forward.emplace(block_index.pprev, &block_index);
5265 : : }
5266 : : }
5267 [ - + - + ]: 419897 : assert(forward.size() + best_hdr_chain.Height() + 1 == m_blockman.m_block_index.size());
5268 : :
5269 [ + - ]: 419897 : const CBlockIndex* pindex = best_hdr_chain[0];
5270 [ - + ]: 419897 : assert(pindex);
5271 : : // Iterate over the entire block tree, using depth-first search.
5272 : : // Along the way, remember whether there are blocks on the path from genesis
5273 : : // block being explored which are the first to have certain properties.
5274 : 419897 : size_t nNodes = 0;
5275 : 419897 : int nHeight = 0;
5276 : 419897 : const CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
5277 : 419897 : const CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA, since assumeutxo snapshot if used.
5278 : 419897 : const CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0, since assumeutxo snapshot if used.
5279 : 419897 : const CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
5280 : 419897 : const CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not), since assumeutxo snapshot if used.
5281 : 419897 : const CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not), since assumeutxo snapshot if used.
5282 : 419897 : const CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not), since assumeutxo snapshot if used.
5283 : :
5284 : : // After checking an assumeutxo snapshot block, reset pindexFirst pointers
5285 : : // to earlier blocks that have not been downloaded or validated yet, so
5286 : : // checks for later blocks can assume the earlier blocks were validated and
5287 : : // be stricter, testing for more requirements.
5288 [ + - + - ]: 419897 : const CBlockIndex* snap_base{CurrentChainstate().SnapshotBase()};
5289 : 419897 : const CBlockIndex *snap_first_missing{}, *snap_first_notx{}, *snap_first_notv{}, *snap_first_nocv{}, *snap_first_nosv{};
5290 : 335209246 : auto snap_update_firsts = [&] {
5291 [ + + ]: 334789349 : if (pindex == snap_base) {
5292 : 9352 : std::swap(snap_first_missing, pindexFirstMissing);
5293 : 9352 : std::swap(snap_first_notx, pindexFirstNeverProcessed);
5294 : 9352 : std::swap(snap_first_notv, pindexFirstNotTransactionsValid);
5295 : 9352 : std::swap(snap_first_nocv, pindexFirstNotChainValid);
5296 : 9352 : std::swap(snap_first_nosv, pindexFirstNotScriptsValid);
5297 : : }
5298 : 335209246 : };
5299 : :
5300 [ + + ]: 308996199 : while (pindex != nullptr) {
5301 : 308984686 : nNodes++;
5302 [ + + + + ]: 308984686 : if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
5303 [ + + + + ]: 308984686 : if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
5304 : 599185 : pindexFirstMissing = pindex;
5305 : : }
5306 [ + + + + ]: 308984686 : if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
5307 [ + + + - : 308984686 : if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
- + ]
5308 : :
5309 [ + + ]: 308984686 : if (pindex->pprev != nullptr) {
5310 [ + + ]: 308564789 : if (pindexFirstNotTransactionsValid == nullptr &&
5311 [ + + ]: 243174943 : (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) {
5312 : 583322 : pindexFirstNotTransactionsValid = pindex;
5313 : : }
5314 : :
5315 [ + + ]: 308564789 : if (pindexFirstNotChainValid == nullptr &&
5316 [ + + ]: 239305775 : (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) {
5317 : 13565994 : pindexFirstNotChainValid = pindex;
5318 : : }
5319 : :
5320 [ + + ]: 308564789 : if (pindexFirstNotScriptsValid == nullptr &&
5321 [ + + ]: 239305775 : (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) {
5322 : 13565994 : pindexFirstNotScriptsValid = pindex;
5323 : : }
5324 : : }
5325 : :
5326 : : // Begin: actual consistency checks.
5327 [ + + ]: 308984686 : if (pindex->pprev == nullptr) {
5328 : : // Genesis block checks.
5329 [ - + ]: 419897 : assert(pindex->GetBlockHash() == GetConsensus().hashGenesisBlock); // Genesis block's hash must match.
5330 [ + + ]: 848805 : for (const auto& c : m_chainstates) {
5331 [ - + + - ]: 1286724 : if (c->m_chain.Genesis() != nullptr) {
5332 [ - + ]: 428908 : assert(pindex == c->m_chain.Genesis()); // The chain's genesis block must be this block.
5333 : : }
5334 : : }
5335 : : }
5336 : : // nSequenceId can't be set higher than SEQ_ID_INIT_FROM_DISK{1} for blocks that aren't linked
5337 : : // (negative is used for preciousblock, SEQ_ID_BEST_CHAIN_FROM_DISK{0} for active chain when loaded from disk)
5338 [ + + - + ]: 308984686 : if (!pindex->HaveNumChainTxs()) assert(pindex->nSequenceId <= SEQ_ID_INIT_FROM_DISK);
5339 : : // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
5340 : : // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
5341 [ + + ]: 308984686 : if (!m_blockman.m_have_pruned) {
5342 : : // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
5343 [ - + ]: 261568511 : assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
5344 [ - + ]: 261568511 : assert(pindexFirstMissing == pindexFirstNeverProcessed);
5345 : : } else {
5346 : : // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
5347 [ + + - + ]: 47416175 : if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
5348 : : }
5349 [ + + - + ]: 308984686 : if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
5350 [ + + + - : 308984686 : if (snap_base && snap_base->GetAncestor(pindex->nHeight) == pindex) {
+ + ]
5351 : : // Assumed-valid blocks should connect to the main chain.
5352 [ - + ]: 2468940 : assert((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE);
5353 : : }
5354 : : // There should only be an nTx value if we have
5355 : : // actually seen a block's transactions.
5356 [ - + ]: 308984686 : assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
5357 : : // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to HaveNumChainTxs().
5358 : : // HaveNumChainTxs will also be set in the assumeutxo snapshot block from snapshot metadata.
5359 [ + + + + : 374952673 : assert((pindexFirstNeverProcessed == nullptr || pindex == snap_base) == pindex->HaveNumChainTxs());
- + ]
5360 [ + + + + : 374952673 : assert((pindexFirstNotTransactionsValid == nullptr || pindex == snap_base) == pindex->HaveNumChainTxs());
- + ]
5361 [ - + ]: 308984686 : assert(pindex->nHeight == nHeight); // nHeight must be consistent.
5362 [ + + + - : 308984686 : 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.
- + ]
5363 [ + + + - : 308984686 : assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
- + ]
5364 [ - + ]: 308984686 : assert(pindexFirstNotTreeValid == nullptr); // All m_blockman.m_block_index entries must at least be TREE valid
5365 : 308984686 : if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
5366 [ + + - + ]: 308984686 : if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
5367 [ + + - + ]: 308984686 : if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
5368 [ + + ]: 308984686 : if (pindexFirstInvalid == nullptr) {
5369 : : // Checks for not-invalid blocks.
5370 [ - + ]: 294115059 : assert((pindex->nStatus & BLOCK_FAILED_VALID) == 0); // The failed flag cannot be set for blocks without invalid parents.
5371 : : } else {
5372 [ - + ]: 14869627 : assert(pindex->nStatus & BLOCK_FAILED_VALID); // Invalid blocks and their descendants must be marked as invalid
5373 : : }
5374 : : // Make sure m_chain_tx_count sum is correctly computed.
5375 [ + + ]: 308984686 : if (!pindex->pprev) {
5376 : : // If no previous block, nTx and m_chain_tx_count must be the same.
5377 [ - + ]: 419897 : assert(pindex->m_chain_tx_count == pindex->nTx);
5378 [ + + + + ]: 308564789 : } else if (pindex->pprev->m_chain_tx_count > 0 && pindex->nTx > 0) {
5379 : : // If previous m_chain_tx_count is set and number of transactions in block is known, sum must be set.
5380 [ - + ]: 242591621 : assert(pindex->m_chain_tx_count == pindex->nTx + pindex->pprev->m_chain_tx_count);
5381 : : } else {
5382 : : // Otherwise m_chain_tx_count should only be set if this is a snapshot
5383 : : // block, and must be set if it is.
5384 [ - + ]: 65973168 : assert((pindex->m_chain_tx_count != 0) == (pindex == snap_base));
5385 : : }
5386 : : // There should be no block with more work than m_best_header, unless it's known to be invalid
5387 [ + + + - : 308984686 : assert((pindex->nStatus & BLOCK_FAILED_VALID) || pindex->nChainWork <= m_best_header->nChainWork);
- + ]
5388 : :
5389 : : // Chainstate-specific checks on setBlockIndexCandidates
5390 [ + + ]: 621526460 : for (const auto& c : m_chainstates) {
5391 [ - + - + ]: 625083548 : if (c->m_chain.Tip() == nullptr) continue;
5392 : : // Two main factors determine whether pindex is a candidate in
5393 : : // setBlockIndexCandidates:
5394 : : //
5395 : : // - If pindex has less work than the chain tip, it should not be a
5396 : : // candidate, and this will be asserted below. Otherwise it is a
5397 : : // potential candidate.
5398 : : //
5399 : : // - If pindex or one of its parent blocks back to the genesis block
5400 : : // or an assumeutxo snapshot never downloaded transactions
5401 : : // (pindexFirstNeverProcessed is non-null), it should not be a
5402 : : // candidate, and this will be asserted below. The only exception
5403 : : // is if pindex itself is an assumeutxo snapshot block. Then it is
5404 : : // also a potential candidate.
5405 [ + - + + : 312541774 : if (!CBlockIndexWorkComparator()(pindex, c->m_chain.Tip()) && (pindexFirstNeverProcessed == nullptr || pindex == snap_base)) {
+ + + + ]
5406 : : // If pindex was detected as invalid (pindexFirstInvalid is
5407 : : // non-null), it is not required to be in
5408 : : // setBlockIndexCandidates.
5409 [ + + ]: 2679097 : if (pindexFirstInvalid == nullptr) {
5410 : : // If pindex and all its parents back to the genesis block
5411 : : // or an assumeutxo snapshot block downloaded transactions,
5412 : : // and the transactions were not pruned (pindexFirstMissing
5413 : : // is null), it is a potential candidate. The check
5414 : : // excludes pruned blocks, because if any blocks were
5415 : : // pruned between pindex and the current chain tip, pindex will
5416 : : // only temporarily be added to setBlockIndexCandidates,
5417 : : // before being moved to m_blocks_unlinked. This check
5418 : : // could be improved to verify that if all blocks between
5419 : : // the chain tip and pindex have data, pindex must be a
5420 : : // candidate.
5421 : : //
5422 : : // If pindex is the chain tip, it also is a potential
5423 : : // candidate.
5424 : : //
5425 : : // If the chainstate was loaded from a snapshot and pindex
5426 : : // is the base of the snapshot, pindex is also a potential
5427 : : // candidate.
5428 [ + + - + : 2059320 : if (pindexFirstMissing == nullptr || pindex == c->m_chain.Tip() || pindex == c->SnapshotBase()) {
+ + + - -
+ ]
5429 : : // If this chainstate is not a historical chainstate
5430 : : // targeting a specific block, pindex must be in
5431 : : // setBlockIndexCandidates. Otherwise, pindex only
5432 : : // needs to be added if it is an ancestor of the target
5433 : : // block.
5434 [ + - + + : 1939871 : if (!c->TargetBlock() || c->TargetBlock()->GetAncestor(pindex->nHeight) == pindex) {
+ - + - +
+ ]
5435 [ + - - + ]: 1046109 : assert(c->setBlockIndexCandidates.contains(pindex));
5436 : : }
5437 : : }
5438 : : // If some parent is missing, then it could be that this block was in
5439 : : // setBlockIndexCandidates but had to be removed because of the missing data.
5440 : : // In this case it must be in m_blocks_unlinked -- see test below.
5441 : : }
5442 : : } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
5443 [ + - - + ]: 309862677 : assert(!c->setBlockIndexCandidates.contains(pindex));
5444 : : }
5445 : : }
5446 : : // Check whether this block is in m_blocks_unlinked.
5447 : 308984686 : auto rangeUnlinked{m_blockman.m_blocks_unlinked.equal_range(pindex->pprev)};
5448 : 308984686 : bool foundInUnlinked = false;
5449 [ + + ]: 334240923 : for (auto it = rangeUnlinked.first; it != rangeUnlinked.second; ++it) {
5450 [ - + ]: 25256237 : assert(it->first == pindex->pprev);
5451 [ + + ]: 25256237 : if (it->second == pindex) {
5452 [ - + ]: 25208556 : assert(!foundInUnlinked); // No duplicates in m_blocks_unlinked
5453 : : foundInUnlinked = true;
5454 : : }
5455 : : }
5456 [ + + + + : 308984686 : if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
+ + + - ]
5457 : : // If this block has block data available, some parent was never received, and has no invalid parents, it must be in m_blocks_unlinked.
5458 [ - + ]: 25083024 : assert(foundInUnlinked);
5459 : : }
5460 [ + + - + ]: 308984686 : if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in m_blocks_unlinked if we don't HAVE_DATA
5461 [ + + - + ]: 308984686 : if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in m_blocks_unlinked.
5462 [ + + + + : 308984686 : if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
+ + + + ]
5463 : : // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
5464 [ - + ]: 26517037 : assert(m_blockman.m_have_pruned);
5465 : : // This block may have entered m_blocks_unlinked if:
5466 : : // - it has a descendant that at some point had more work than the
5467 : : // tip, and
5468 : : // - we tried switching to that descendant but were missing
5469 : : // data for some intermediate block between m_chain and the
5470 : : // tip.
5471 : : // So if this block is itself better than any m_chain.Tip() and it wasn't in
5472 : : // setBlockIndexCandidates, then it must be in m_blocks_unlinked.
5473 [ + + ]: 53034074 : for (const auto& c : m_chainstates) {
5474 [ - + + - : 53034074 : if (!CBlockIndexWorkComparator()(pindex, c->m_chain.Tip()) && !c->setBlockIndexCandidates.contains(pindex)) {
+ + + - +
+ ]
5475 [ + + ]: 278839 : if (pindexFirstInvalid == nullptr) {
5476 [ + - - + : 32968 : if (!c->TargetBlock() || c->TargetBlock()->GetAncestor(pindex->nHeight) == pindex) {
- - - - -
- ]
5477 [ - + ]: 32968 : assert(foundInUnlinked);
5478 : : }
5479 : : }
5480 : : }
5481 : : }
5482 : : }
5483 : : // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
5484 : : // End: actual consistency checks.
5485 : :
5486 : :
5487 : : // Try descending into the first subnode. Always process forks first and the best header chain after.
5488 : 308984686 : snap_update_firsts();
5489 : 308984686 : auto range{forward.equal_range(pindex)};
5490 [ + + ]: 308984686 : if (range.first != range.second) {
5491 : : // A subnode not part of the best header chain was found.
5492 : 19489470 : pindex = range.first->second;
5493 : 19489470 : nHeight++;
5494 : 19489470 : continue;
5495 [ + + ]: 289495216 : } else if (best_hdr_chain.Contains(*pindex)) {
5496 : : // Descend further into best header chain.
5497 : 275861217 : nHeight++;
5498 [ + - ]: 275861217 : pindex = best_hdr_chain[nHeight];
5499 [ + + ]: 275861217 : if (!pindex) break; // we are finished, since the best header chain is always processed last
5500 : 275452833 : continue;
5501 : : }
5502 : : // This is a leaf node.
5503 : : // Move upwards until we reach a node of which we have not yet visited the last child.
5504 [ + - ]: 25804663 : while (pindex) {
5505 : : // We are going to either move to a parent or a sibling of pindex.
5506 : 25804663 : snap_update_firsts();
5507 : : // If pindex was the first with a certain property, unset the corresponding variable.
5508 [ + + ]: 25804663 : if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
5509 [ + + ]: 25804663 : if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
5510 [ + + ]: 25804663 : if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
5511 [ - + ]: 25804663 : if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
5512 [ + + ]: 25804663 : if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
5513 [ + + ]: 25804663 : if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
5514 [ + + ]: 25804663 : if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
5515 : : // Find our parent.
5516 : 25804663 : CBlockIndex* pindexPar = pindex->pprev;
5517 : : // Find which child we just visited.
5518 : 25804663 : auto rangePar{forward.equal_range(pindexPar)};
5519 [ + + ]: 36756697 : while (rangePar.first->second != pindex) {
5520 [ - + ]: 10952034 : assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
5521 : 10952034 : rangePar.first++;
5522 : : }
5523 : : // Proceed to the next one.
5524 : 25804663 : rangePar.first++;
5525 [ + + ]: 25804663 : if (rangePar.first != rangePar.second) {
5526 : : // Move to a sibling not part of the best header chain.
5527 : 6315193 : pindex = rangePar.first->second;
5528 : 6315193 : break;
5529 [ + - + + ]: 38978940 : } else if (pindexPar == best_hdr_chain[nHeight - 1]) {
5530 : : // Move to pindex's sibling on the best-chain, if it has one.
5531 [ + - ]: 7318806 : pindex = best_hdr_chain[nHeight];
5532 : : // There will not be a next block if (and only if) parent block is the best header.
5533 [ - + - + ]: 14637612 : assert((pindex == nullptr) == (pindexPar == best_hdr_chain.Tip()));
5534 : : break;
5535 : : } else {
5536 : : // Move up further.
5537 : 12170664 : pindex = pindexPar;
5538 : 12170664 : nHeight--;
5539 : 12170664 : continue;
5540 : : }
5541 : : }
5542 : : }
5543 : :
5544 : : // Check that we actually traversed the entire block index.
5545 [ - + - + ]: 419897 : assert(nNodes == forward.size() + best_hdr_chain.Height() + 1);
5546 [ + - ]: 839822 : }
5547 : :
5548 : 1694 : std::string Chainstate::ToString()
5549 : : {
5550 : 1694 : AssertLockHeld(::cs_main);
5551 [ - + ]: 1694 : CBlockIndex* tip = m_chain.Tip();
5552 : 274 : return strprintf("Chainstate [%s] @ height %d (%s)",
5553 : 3388 : m_from_snapshot_blockhash ? "snapshot" : "ibd",
5554 [ + - - + : 4983 : tip ? tip->nHeight : -1, tip ? tip->GetBlockHash().ToString() : "null");
+ + + - ]
5555 : : }
5556 : :
5557 : 2037 : bool Chainstate::ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
5558 : : {
5559 : 2037 : AssertLockHeld(::cs_main);
5560 [ + + ]: 2037 : if (coinstip_size == m_coinstip_cache_size_bytes &&
5561 [ - + ]: 1905 : coinsdb_size == m_coinsdb_cache_size_bytes) {
5562 : : // Cache sizes are unchanged, no need to continue.
5563 : : return true;
5564 : : }
5565 : 132 : size_t old_coinstip_size = m_coinstip_cache_size_bytes;
5566 : 132 : m_coinstip_cache_size_bytes = coinstip_size;
5567 : 132 : m_coinsdb_cache_size_bytes = coinsdb_size;
5568 : 132 : CoinsDB().ResizeCache(coinsdb_size);
5569 : :
5570 [ + - ]: 132 : LogInfo("[%s] resized coinsdb cache to %.1f MiB",
5571 : : this->ToString(), coinsdb_size / double(1_MiB));
5572 [ + - ]: 132 : LogInfo("[%s] resized coinstip cache to %.1f MiB",
5573 : : this->ToString(), coinstip_size / double(1_MiB));
5574 : :
5575 [ + + ]: 132 : BlockValidationState state;
5576 : 132 : bool ret;
5577 : :
5578 [ + + ]: 132 : if (coinstip_size > old_coinstip_size) {
5579 : : // Likely no need to flush if cache sizes have grown.
5580 [ + - ]: 63 : ret = FlushStateToDisk(state, FlushStateMode::IF_NEEDED);
5581 : : } else {
5582 : : // Otherwise, flush state to disk and deallocate the in-memory coins map.
5583 [ + - ]: 69 : ret = FlushStateToDisk(state, FlushStateMode::FORCE_FLUSH);
5584 : : }
5585 : 132 : return ret;
5586 : 132 : }
5587 : :
5588 : 365786 : double ChainstateManager::GuessVerificationProgress(const CBlockIndex* pindex) const
5589 : : {
5590 : 365786 : AssertLockHeld(GetMutex());
5591 [ + + ]: 365786 : const ChainTxData& data{GetParams().TxData()};
5592 [ + + ]: 365786 : if (pindex == nullptr) {
5593 : : return 0.0;
5594 : : }
5595 : :
5596 [ + + ]: 365784 : if (pindex->m_chain_tx_count == 0) {
5597 [ + - ]: 198 : LogDebug(BCLog::VALIDATION, "Block %d has unset m_chain_tx_count. Unable to estimate verification progress.\n", pindex->nHeight);
5598 : 198 : return 0.0;
5599 : : }
5600 : :
5601 : 365586 : const int64_t nNow{TicksSinceEpoch<std::chrono::seconds>(NodeClock::now())};
5602 : 365586 : const auto block_time{
5603 [ + - + + : 365586 : (Assume(m_best_header) && std::abs(nNow - pindex->GetBlockTime()) <= Ticks<std::chrono::seconds>(2h) &&
+ - ]
5604 [ + - + - ]: 675195 : Assume(m_best_header->nHeight >= pindex->nHeight)) ?
5605 : : // When the header is known to be recent, switch to a height-based
5606 : : // approach. This ensures the returned value is quantized when
5607 : : // close to "1.0", because some users expect it to be. This also
5608 : : // avoids relying too much on the exact miner-set timestamp, which
5609 : : // may be off.
5610 : 309609 : nNow - (m_best_header->nHeight - pindex->nHeight) * GetConsensus().nPowTargetSpacing :
5611 : 55977 : pindex->GetBlockTime(),
5612 : 309609 : };
5613 : :
5614 : 365586 : double fTxTotal;
5615 : :
5616 [ + + ]: 365586 : if (pindex->m_chain_tx_count <= data.tx_count) {
5617 : 4453 : fTxTotal = data.tx_count + (nNow - data.nTime) * data.dTxRate;
5618 : : } else {
5619 : 361133 : fTxTotal = pindex->m_chain_tx_count + (nNow - block_time) * data.dTxRate;
5620 : : }
5621 : :
5622 [ + + ]: 365586 : return std::min<double>(pindex->m_chain_tx_count / fTxTotal, 1.0);
5623 : : }
5624 : :
5625 : 5 : double ChainstateManager::GetBackgroundVerificationProgress(const CBlockIndex& pindex) const
5626 : : {
5627 : 5 : AssertLockHeld(GetMutex());
5628 : 5 : Assert(HistoricalChainstate());
5629 : 5 : auto target_block = HistoricalChainstate()->TargetBlock();
5630 : :
5631 [ + - - + ]: 5 : if (pindex.m_chain_tx_count == 0 || target_block->m_chain_tx_count == 0) {
5632 [ # # ]: 0 : LogDebug(BCLog::VALIDATION, "[background validation] Block %d has unset m_chain_tx_count. Unable to estimate verification progress.", pindex.nHeight);
5633 : 0 : return 0.0;
5634 : : }
5635 : 5 : return static_cast<double>(pindex.m_chain_tx_count) / static_cast<double>(target_block->m_chain_tx_count);
5636 : : }
5637 : :
5638 : 1439 : Chainstate& ChainstateManager::InitializeChainstate(CTxMemPool* mempool)
5639 : : {
5640 : 1439 : AssertLockHeld(::cs_main);
5641 [ - + ]: 1439 : assert(m_chainstates.empty());
5642 [ + - ]: 1439 : m_chainstates.emplace_back(std::make_unique<Chainstate>(mempool, m_blockman, *this));
5643 : 1439 : return *m_chainstates.back();
5644 : : }
5645 : :
5646 : 30 : [[nodiscard]] static bool DeleteCoinsDBFromDisk(const fs::path db_path, bool is_snapshot)
5647 : : EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
5648 : : {
5649 : 30 : AssertLockHeld(::cs_main);
5650 : :
5651 [ + + ]: 30 : if (is_snapshot) {
5652 [ + - ]: 54 : fs::path base_blockhash_path = db_path / node::SNAPSHOT_BLOCKHASH_FILENAME;
5653 : :
5654 : 27 : try {
5655 [ + - ]: 27 : bool existed = fs::remove(base_blockhash_path);
5656 [ + + ]: 27 : if (!existed) {
5657 [ - + + - ]: 50 : LogWarning("[snapshot] snapshot chainstate dir being removed lacks %s file",
5658 : : fs::PathToString(node::SNAPSHOT_BLOCKHASH_FILENAME));
5659 : : }
5660 [ - - ]: 0 : } catch (const fs::filesystem_error& e) {
5661 [ - - - - : 0 : LogWarning("[snapshot] failed to remove file %s: %s\n",
- - ]
5662 : : fs::PathToString(base_blockhash_path), e.code().message());
5663 [ - - ]: 0 : }
5664 : 27 : }
5665 : :
5666 [ - + ]: 30 : std::string path_str = fs::PathToString(db_path);
5667 [ + - ]: 30 : LogInfo("Removing leveldb dir at %s\n", path_str);
5668 : :
5669 : : // We have to destruct before this call leveldb::DB in order to release the db
5670 : : // lock, otherwise `DestroyDB` will fail. See `leveldb::~DBImpl()`.
5671 [ + - ]: 30 : const bool destroyed = DestroyDB(path_str);
5672 : :
5673 [ + - ]: 30 : if (!destroyed) {
5674 [ # # ]: 0 : LogError("leveldb DestroyDB call failed on %s", path_str);
5675 : : }
5676 : :
5677 : : // Datadir should be removed from filesystem; otherwise initialization may detect
5678 : : // it on subsequent statups and get confused.
5679 : : //
5680 : : // If the base_blockhash_path removal above fails in the case of snapshot
5681 : : // chainstates, this will return false since leveldb won't remove a non-empty
5682 : : // directory.
5683 [ + - - + ]: 30 : return destroyed && !fs::exists(db_path);
5684 : 30 : }
5685 : :
5686 : 65 : util::Result<CBlockIndex*> ChainstateManager::ActivateSnapshot(
5687 : : AutoFile& coins_file,
5688 : : const SnapshotMetadata& metadata,
5689 : : bool in_memory)
5690 : : {
5691 : 65 : uint256 base_blockhash = metadata.m_base_blockhash;
5692 : :
5693 : 65 : CBlockIndex* snapshot_start_block{};
5694 : :
5695 : 65 : {
5696 : 65 : LOCK(::cs_main);
5697 : :
5698 [ + - + + ]: 65 : if (this->CurrentChainstate().m_from_snapshot_blockhash) {
5699 [ + - + - ]: 15 : return util::Error{Untranslated("Can't activate a snapshot-based chainstate more than once")};
5700 : : }
5701 [ + + ]: 60 : if (!GetParams().AssumeutxoForBlockhash(base_blockhash).has_value()) {
5702 [ + - ]: 14 : auto available_heights = GetParams().GetAvailableSnapshotHeights();
5703 [ + - + - ]: 56 : std::string heights_formatted = util::Join(available_heights, ", ", [&](const auto& i) { return util::ToString(i); });
5704 [ + - + - ]: 28 : return util::Error{Untranslated(strprintf("assumeutxo block hash in snapshot metadata not recognized (hash: %s). The following snapshot heights are available: %s",
5705 [ + - ]: 28 : base_blockhash.ToString(),
5706 : 14 : heights_formatted))};
5707 : 14 : }
5708 : :
5709 [ + - ]: 46 : snapshot_start_block = m_blockman.LookupBlockIndex(base_blockhash);
5710 [ + + ]: 46 : if (!snapshot_start_block) {
5711 [ + - + - ]: 6 : return util::Error{Untranslated(strprintf("The base block header (%s) must appear in the headers chain. Make sure all headers are syncing, and call loadtxoutset again",
5712 [ + - ]: 9 : base_blockhash.ToString()))};
5713 : : }
5714 : :
5715 : 43 : bool start_block_invalid = snapshot_start_block->nStatus & BLOCK_FAILED_VALID;
5716 [ + + ]: 43 : if (start_block_invalid) {
5717 [ + - + - : 6 : return util::Error{Untranslated(strprintf("The base block header (%s) is part of an invalid chain", base_blockhash.ToString()))};
+ - ]
5718 : : }
5719 : :
5720 [ + - + - : 41 : if (!m_best_header || m_best_header->GetAncestor(snapshot_start_block->nHeight) != snapshot_start_block) {
+ + ]
5721 [ + - + - ]: 3 : return util::Error{Untranslated("A forked headers-chain with more work than the chain with the snapshot base block header exists. Please proceed to sync without AssumeUtxo.")};
5722 : : }
5723 : :
5724 [ + - + - ]: 40 : auto mempool{CurrentChainstate().GetMempool()};
5725 [ + - + - : 40 : if (mempool && mempool->size() > 0) {
+ + ]
5726 [ + - + - ]: 3 : return util::Error{Untranslated("Can't activate a snapshot when mempool not empty")};
5727 : : }
5728 : 26 : }
5729 : :
5730 : 39 : int64_t current_coinsdb_cache_size{0};
5731 : 39 : int64_t current_coinstip_cache_size{0};
5732 : :
5733 : : // Cache percentages to allocate to each chainstate.
5734 : : //
5735 : : // These particular percentages don't matter so much since they will only be
5736 : : // relevant during snapshot activation; caches are rebalanced at the conclusion of
5737 : : // this function. We want to give (essentially) all available cache capacity to the
5738 : : // snapshot to aid the bulk load later in this function.
5739 : 39 : static constexpr double IBD_CACHE_PERC = 0.01;
5740 : 39 : static constexpr double SNAPSHOT_CACHE_PERC = 0.99;
5741 : :
5742 : 39 : {
5743 : 39 : LOCK(::cs_main);
5744 : : // Resize the coins caches to ensure we're not exceeding memory limits.
5745 : : //
5746 : : // Allocate the majority of the cache to the incoming snapshot chainstate, since
5747 : : // (optimistically) getting to its tip will be the top priority. We'll need to call
5748 : : // `MaybeRebalanceCaches()` once we're done with this function to ensure
5749 : : // the right allocation (including the possibility that no snapshot was activated
5750 : : // and that we should restore the active chainstate caches to their original size).
5751 : : //
5752 [ + - ]: 39 : current_coinsdb_cache_size = this->ActiveChainstate().m_coinsdb_cache_size_bytes;
5753 [ + - ]: 39 : current_coinstip_cache_size = this->ActiveChainstate().m_coinstip_cache_size_bytes;
5754 : :
5755 : : // Temporarily resize the active coins cache to make room for the newly-created
5756 : : // snapshot chain.
5757 [ + - ]: 39 : this->ActiveChainstate().ResizeCoinsCaches(
5758 : 39 : static_cast<size_t>(current_coinstip_cache_size * IBD_CACHE_PERC),
5759 [ + - ]: 39 : static_cast<size_t>(current_coinsdb_cache_size * IBD_CACHE_PERC));
5760 : 0 : }
5761 : :
5762 [ + - ]: 117 : auto snapshot_chainstate = WITH_LOCK(::cs_main,
5763 : : return std::make_unique<Chainstate>(
5764 : : /*mempool=*/nullptr, m_blockman, *this, base_blockhash));
5765 : :
5766 : 39 : {
5767 [ + - ]: 39 : LOCK(::cs_main);
5768 [ + - ]: 39 : snapshot_chainstate->InitCoinsDB(
5769 [ + - ]: 39 : static_cast<size_t>(current_coinsdb_cache_size * SNAPSHOT_CACHE_PERC),
5770 : : in_memory, /*should_wipe=*/false);
5771 [ + - ]: 39 : snapshot_chainstate->InitCoinsCache(
5772 [ + - ]: 39 : static_cast<size_t>(current_coinstip_cache_size * SNAPSHOT_CACHE_PERC));
5773 : 0 : }
5774 : :
5775 : 63 : auto cleanup_bad_snapshot = [&](bilingual_str reason) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
5776 : 24 : this->MaybeRebalanceCaches();
5777 : :
5778 : : // PopulateAndValidateSnapshot can return (in error) before the leveldb datadir
5779 : : // has been created, so only attempt removal if we got that far.
5780 [ + - ]: 24 : if (auto snapshot_datadir = node::FindAssumeutxoChainstateDir(m_options.datadir)) {
5781 : : // We have to destruct leveldb::DB in order to release the db lock, otherwise
5782 : : // DestroyDB() (in DeleteCoinsDBFromDisk()) will fail. See `leveldb::~DBImpl()`.
5783 : : // Destructing the chainstate (and so resetting the coinsviews object) does this.
5784 [ + - ]: 24 : snapshot_chainstate.reset();
5785 [ + - + - ]: 24 : bool removed = DeleteCoinsDBFromDisk(*snapshot_datadir, /*is_snapshot=*/true);
5786 [ - + ]: 24 : if (!removed) {
5787 [ # # # # ]: 0 : GetNotifications().fatalError(strprintf(_("Failed to remove snapshot chainstate dir (%s). "
5788 [ # # # # ]: 0 : "Manually remove it before restarting.\n"), fs::PathToString(*snapshot_datadir)));
5789 : : }
5790 : 24 : }
5791 : 24 : return util::Error{std::move(reason)};
5792 : 39 : };
5793 : :
5794 [ + - + + ]: 39 : if (auto res{this->PopulateAndValidateSnapshot(*snapshot_chainstate, coins_file, metadata)}; !res) {
5795 [ + - ]: 24 : LOCK(::cs_main);
5796 [ + - + - : 120 : return cleanup_bad_snapshot(Untranslated(strprintf("Population failed: %s", util::ErrorString(res).original)));
+ - + - +
- ]
5797 : 24 : }
5798 : :
5799 [ + - ]: 15 : LOCK(::cs_main); // cs_main required for rest of snapshot activation.
5800 : :
5801 : : // Do a final check to ensure that the snapshot chainstate is actually a more
5802 : : // work chain than the active chainstate; a user could have loaded a snapshot
5803 : : // very late in the IBD process, and we wouldn't want to load a useless chainstate.
5804 [ - + + - : 30 : if (!CBlockIndexWorkComparator()(ActiveTip(), snapshot_chainstate->m_chain.Tip())) {
+ - - + ]
5805 [ # # # # : 0 : return cleanup_bad_snapshot(Untranslated("work does not exceed active chainstate"));
# # ]
5806 : : }
5807 : : // If not in-memory, persist the base blockhash for use during subsequent
5808 : : // initialization.
5809 [ + - ]: 15 : if (!in_memory) {
5810 [ + - - + ]: 15 : if (!node::WriteSnapshotBaseBlockhash(*snapshot_chainstate)) {
5811 [ # # # # : 0 : return cleanup_bad_snapshot(Untranslated("could not write base blockhash"));
# # ]
5812 : : }
5813 : : }
5814 : :
5815 [ + - ]: 15 : Chainstate& chainstate{AddChainstate(std::move(snapshot_chainstate))};
5816 [ + - + - : 15 : m_blockman.m_snapshot_height = Assert(chainstate.SnapshotBase())->nHeight;
+ - ]
5817 : :
5818 [ + - ]: 15 : chainstate.PopulateBlockIndexCandidates();
5819 : :
5820 [ + - + - ]: 15 : LogInfo("[snapshot] successfully activated snapshot %s", base_blockhash.ToString());
5821 [ + - + - : 15 : LogInfo("[snapshot] (%.2f MB)",
+ - ]
5822 : : chainstate.CoinsTip().DynamicMemoryUsage() / (1000 * 1000));
5823 : :
5824 [ + - ]: 15 : this->MaybeRebalanceCaches();
5825 : 15 : return snapshot_start_block;
5826 : 39 : }
5827 : :
5828 : 23 : static void FlushSnapshotToDisk(CCoinsViewCache& coins_cache, bool snapshot_loaded)
5829 : : {
5830 [ - + + - : 46 : LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE(
+ - ]
5831 : : strprintf("%s (%.2f MB)",
5832 : : snapshot_loaded ? "saving snapshot chainstate" : "flushing coins cache",
5833 : : coins_cache.DynamicMemoryUsage() / (1000 * 1000)),
5834 : : BCLog::LogFlags::ALL);
5835 : :
5836 [ + - ]: 23 : coins_cache.Flush();
5837 : 23 : }
5838 : :
5839 : 0 : struct StopHashingException : public std::exception
5840 : : {
5841 : 0 : const char* what() const noexcept override
5842 : : {
5843 : 0 : return "ComputeUTXOStats interrupted.";
5844 : : }
5845 : : };
5846 : :
5847 : 8304 : static void SnapshotUTXOHashBreakpoint(const util::SignalInterrupt& interrupt)
5848 : : {
5849 [ - + ]: 8304 : if (interrupt) throw StopHashingException();
5850 : 8304 : }
5851 : :
5852 : 39 : util::Result<void> ChainstateManager::PopulateAndValidateSnapshot(
5853 : : Chainstate& snapshot_chainstate,
5854 : : AutoFile& coins_file,
5855 : : const SnapshotMetadata& metadata)
5856 : : {
5857 : : // It's okay to release cs_main before we're done using `coins_cache` because we know
5858 : : // that nothing else will be referencing the newly created snapshot_chainstate yet.
5859 [ + - + - ]: 117 : CCoinsViewCache& coins_cache = *WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsTip());
5860 : :
5861 : 39 : uint256 base_blockhash = metadata.m_base_blockhash;
5862 : :
5863 [ + - + - ]: 117 : CBlockIndex* snapshot_start_block = WITH_LOCK(::cs_main, return m_blockman.LookupBlockIndex(base_blockhash));
5864 : :
5865 [ - + ]: 39 : if (!snapshot_start_block) {
5866 : : // Needed for ComputeUTXOStats to determine the
5867 : : // height and to avoid a crash when base_blockhash.IsNull()
5868 [ # # # # ]: 0 : return util::Error{Untranslated(strprintf("Did not find snapshot start blockheader %s",
5869 : 0 : base_blockhash.ToString()))};
5870 : : }
5871 : :
5872 : 39 : int base_height = snapshot_start_block->nHeight;
5873 : 39 : const auto& maybe_au_data = GetParams().AssumeutxoForHeight(base_height);
5874 : :
5875 [ - + ]: 39 : if (!maybe_au_data) {
5876 [ # # ]: 0 : return util::Error{Untranslated(strprintf("Assumeutxo height in snapshot metadata not recognized "
5877 : 0 : "(%d) - refusing to load snapshot", base_height))};
5878 : : }
5879 : :
5880 : 39 : const AssumeutxoData& au_data = *maybe_au_data;
5881 : :
5882 : : // This work comparison is a duplicate check with the one performed later in
5883 : : // ActivateSnapshot(), but is done so that we avoid doing the long work of staging
5884 : : // a snapshot that isn't actually usable.
5885 [ + + + - : 117 : if (WITH_LOCK(::cs_main, return !CBlockIndexWorkComparator()(ActiveTip(), snapshot_start_block))) {
+ - + - ]
5886 [ + - ]: 6 : return util::Error{Untranslated("Work does not exceed active chainstate")};
5887 : : }
5888 : :
5889 : 37 : const uint64_t coins_count = metadata.m_coins_count;
5890 : 37 : uint64_t coins_left = metadata.m_coins_count;
5891 : :
5892 [ + - ]: 37 : LogInfo("[snapshot] loading %d coins from snapshot %s", coins_left, base_blockhash.ToString());
5893 : 37 : int64_t coins_processed{0};
5894 : :
5895 [ + + ]: 6683 : while (coins_left > 0) {
5896 : 6655 : try {
5897 [ + + ]: 6655 : Txid txid;
5898 [ + + ]: 6655 : coins_file >> txid;
5899 : 6650 : size_t coins_per_txid{0};
5900 [ + - ]: 6650 : coins_per_txid = ReadCompactSize(coins_file);
5901 : :
5902 [ + + ]: 6650 : if (coins_per_txid > coins_left) {
5903 [ + - + - ]: 3 : return util::Error{Untranslated("Mismatch in coins count in snapshot metadata and actual snapshot data")};
5904 : : }
5905 : :
5906 [ + + ]: 13296 : for (size_t i = 0; i < coins_per_txid; i++) {
5907 : 6650 : COutPoint outpoint;
5908 : 6650 : Coin coin;
5909 [ + - ]: 6650 : outpoint.n = static_cast<uint32_t>(ReadCompactSize(coins_file));
5910 : 6650 : outpoint.hash = txid;
5911 [ + - ]: 6650 : coins_file >> coin;
5912 [ + + ]: 6650 : if (coin.nHeight > base_height ||
5913 [ - + ]: 6648 : outpoint.n >= std::numeric_limits<decltype(outpoint.n)>::max() // Avoid integer wrap-around in coinstats.cpp:ApplyHash
5914 : : ) {
5915 [ + - ]: 4 : return util::Error{Untranslated(strprintf("Bad snapshot data after deserializing %d coins",
5916 [ + - ]: 4 : coins_count - coins_left))};
5917 : : }
5918 [ + + ]: 6648 : if (!MoneyRange(coin.out.nValue)) {
5919 [ + - ]: 2 : return util::Error{Untranslated(strprintf("Bad snapshot data after deserializing %d coins - bad tx out value",
5920 [ + - ]: 2 : coins_count - coins_left))};
5921 : : }
5922 [ + - ]: 6647 : coins_cache.EmplaceCoinInternalDANGER(outpoint, std::move(coin));
5923 : :
5924 : 6647 : --coins_left;
5925 : 6647 : ++coins_processed;
5926 : :
5927 [ - + ]: 6647 : if (coins_processed % 1000000 == 0) {
5928 [ # # # # ]: 0 : LogInfo("[snapshot] %d coins loaded (%.2f%%, %.2f MB)",
5929 : : coins_processed,
5930 : : static_cast<float>(coins_processed) * 100 / static_cast<float>(coins_count),
5931 : : coins_cache.DynamicMemoryUsage() / (1000 * 1000));
5932 : : }
5933 : :
5934 : : // Batch write and flush (if we need to) every so often.
5935 : : //
5936 : : // If our average Coin size is roughly 41 bytes, checking every 120,000 coins
5937 : : // means <5MB of memory imprecision.
5938 [ - + ]: 6647 : if (coins_processed % 120000 == 0) {
5939 [ # # # # ]: 0 : if (m_interrupt) {
5940 [ # # # # ]: 0 : return util::Error{Untranslated("Aborting after an interrupt was requested")};
5941 : : }
5942 : :
5943 [ # # # # : 0 : const auto snapshot_cache_state = WITH_LOCK(::cs_main,
# # ]
5944 : : return snapshot_chainstate.GetCoinsCacheSizeState());
5945 : :
5946 [ # # ]: 0 : if (snapshot_cache_state >= CoinsCacheSizeState::CRITICAL) {
5947 : : // This is a hack - we don't know what the actual best block is, but that
5948 : : // doesn't matter for the purposes of flushing the cache here. We'll set this
5949 : : // to its correct value (`base_blockhash`) below after the coins are loaded.
5950 [ # # ]: 0 : coins_cache.SetBestBlock(GetRandHash());
5951 : :
5952 : : // No need to acquire cs_main since this chainstate isn't being used yet.
5953 [ # # ]: 0 : FlushSnapshotToDisk(coins_cache, /*snapshot_loaded=*/false);
5954 : : }
5955 : : }
5956 : 6650 : }
5957 [ - + ]: 5 : } catch (const std::ios_base::failure&) {
5958 [ + - + - ]: 10 : return util::Error{Untranslated(strprintf("Bad snapshot format or truncated snapshot after deserializing %d coins",
5959 : 5 : coins_processed))};
5960 : 5 : }
5961 : : }
5962 : :
5963 : : // Important that we set this. This and the coins_cache accesses above are
5964 : : // sort of a layer violation, but either we reach into the innards of
5965 : : // CCoinsViewCache here or we have to invert some of the Chainstate to
5966 : : // embed them in a snapshot-activation-specific CCoinsViewCache bulk load
5967 : : // method.
5968 : 28 : coins_cache.SetBestBlock(base_blockhash);
5969 : :
5970 : 28 : bool out_of_coins{false};
5971 : 28 : try {
5972 : 28 : std::byte left_over_byte;
5973 [ + + ]: 28 : coins_file >> left_over_byte;
5974 [ - + ]: 23 : } catch (const std::ios_base::failure&) {
5975 : : // We expect an exception since we should be out of coins.
5976 : 23 : out_of_coins = true;
5977 : 23 : }
5978 : 28 : if (!out_of_coins) {
5979 [ + - ]: 10 : return util::Error{Untranslated(strprintf("Bad snapshot - coins left over after deserializing %d coins",
5980 : 5 : coins_count))};
5981 : : }
5982 : :
5983 [ + - + - ]: 23 : LogInfo("[snapshot] loaded %d (%.2f MB) coins from snapshot %s",
5984 : : coins_count,
5985 : : coins_cache.DynamicMemoryUsage() / (1000 * 1000),
5986 : : base_blockhash.ToString());
5987 : :
5988 : : // No need to acquire cs_main since this chainstate isn't being used yet.
5989 : 23 : FlushSnapshotToDisk(coins_cache, /*snapshot_loaded=*/true);
5990 : :
5991 [ - + ]: 23 : assert(coins_cache.GetBestBlock() == base_blockhash);
5992 : :
5993 : : // As above, okay to immediately release cs_main here since no other context knows
5994 : : // about the snapshot_chainstate.
5995 [ + - + - ]: 69 : const CCoinsViewDB& snapshot_coinsdb = WITH_LOCK(::cs_main, return snapshot_chainstate.CoinsDB());
5996 : :
5997 : 23 : std::optional<CCoinsStats> maybe_stats;
5998 : :
5999 : 23 : try {
6000 : 23 : maybe_stats = ComputeUTXOStats(
6001 [ + - ]: 5195 : CoinStatsHashType::HASH_SERIALIZED, snapshot_coinsdb, m_blockman, [&interrupt = m_interrupt] { SnapshotUTXOHashBreakpoint(interrupt); });
6002 [ - - ]: 0 : } catch (StopHashingException const&) {
6003 [ - - - - ]: 0 : return util::Error{Untranslated("Aborting after an interrupt was requested")};
6004 : 0 : }
6005 [ - + ]: 23 : if (!maybe_stats.has_value()) {
6006 [ - - ]: 0 : return util::Error{Untranslated("Failed to generate coins stats")};
6007 : : }
6008 : :
6009 : : // Assert that the deserialized chainstate contents match the expected assumeutxo value.
6010 [ + + ]: 23 : if (AssumeutxoHash{maybe_stats->hashSerialized} != au_data.hash_serialized) {
6011 [ + - ]: 24 : return util::Error{Untranslated(strprintf("Bad snapshot content hash: expected %s, got %s",
6012 [ + - + - ]: 24 : au_data.hash_serialized.ToString(), maybe_stats->hashSerialized.ToString()))};
6013 : : }
6014 : :
6015 : 15 : snapshot_chainstate.m_chain.SetTip(*snapshot_start_block);
6016 : :
6017 : : // The remainder of this function requires modifying data protected by cs_main.
6018 : 15 : LOCK(::cs_main);
6019 : :
6020 : : // Fake various pieces of CBlockIndex state:
6021 : 15 : CBlockIndex* index = nullptr;
6022 : :
6023 : : // Don't make any modifications to the genesis block since it shouldn't be
6024 : : // necessary, and since the genesis block doesn't have normal flags like
6025 : : // BLOCK_VALID_SCRIPTS set.
6026 : 15 : constexpr int AFTER_GENESIS_START{1};
6027 : :
6028 [ - + + + ]: 3555 : for (int i = AFTER_GENESIS_START; i <= snapshot_chainstate.m_chain.Height(); ++i) {
6029 [ + - ]: 3540 : index = snapshot_chainstate.m_chain[i];
6030 : :
6031 : : // Fake BLOCK_OPT_WITNESS so that Chainstate::NeedsRedownload()
6032 : : // won't ask for -reindex on startup.
6033 [ + - ]: 3540 : if (DeploymentActiveAt(*index, *this, Consensus::DEPLOYMENT_SEGWIT)) {
6034 : 3540 : index->nStatus |= BLOCK_OPT_WITNESS;
6035 : : }
6036 : :
6037 [ + - ]: 3540 : m_blockman.m_dirty_blockindex.insert(index);
6038 : : // Changes to the block index will be flushed to disk after this call
6039 : : // returns in `ActivateSnapshot()`, when `MaybeRebalanceCaches()` is
6040 : : // called, since we've added a snapshot chainstate and therefore will
6041 : : // have to downsize the IBD chainstate, which will result in a call to
6042 : : // `FlushStateToDisk(FORCE_FLUSH)`.
6043 : : }
6044 : :
6045 [ - + ]: 15 : assert(index);
6046 [ - + ]: 15 : assert(index == snapshot_start_block);
6047 : 15 : index->m_chain_tx_count = au_data.m_chain_tx_count;
6048 : :
6049 [ + - + - ]: 15 : LogInfo("[snapshot] validated snapshot (%.2f MB)",
6050 : : coins_cache.DynamicMemoryUsage() / (1000 * 1000));
6051 [ + - ]: 15 : return {};
6052 : 15 : }
6053 : :
6054 : : // Currently, this function holds cs_main for its duration, which could be for
6055 : : // multiple minutes due to the ComputeUTXOStats call. Holding cs_main used to be
6056 : : // necessary (before d43a1f1a2fa3) to avoid advancing validated_cs farther than
6057 : : // its target block. Now it should be possible to avoid this, but simply
6058 : : // releasing cs_main here would not be possible because this function is invoked
6059 : : // by ConnectTip within ActivateBestChain.
6060 : : //
6061 : : // Eventually (TODO) it would be better to call this function outside of
6062 : : // ActivateBestChain, on a separate thread that should not require cs_main to
6063 : : // hash, because the UTXO set is only hashed after the historical chainstate
6064 : : // reaches its target block and is no longer changing.
6065 : 131893 : SnapshotCompletionResult ChainstateManager::MaybeValidateSnapshot(Chainstate& validated_cs, Chainstate& unvalidated_cs)
6066 : : {
6067 : 131893 : AssertLockHeld(cs_main);
6068 : :
6069 : : // If the snapshot does not need to be validated...
6070 [ + - ]: 2013 : if (unvalidated_cs.m_assumeutxo != Assumeutxo::UNVALIDATED ||
6071 : : // Or if either chainstate is unusable...
6072 [ + - ]: 2013 : !unvalidated_cs.m_from_snapshot_blockhash ||
6073 [ + + ]: 2013 : validated_cs.m_assumeutxo != Assumeutxo::VALIDATED ||
6074 [ - + + - : 1818 : !validated_cs.m_chain.Tip() ||
+ - ]
6075 : : // Or the validated chainstate is not targeting the snapshot block...
6076 [ + - + - ]: 909 : !validated_cs.TargetBlockHash() ||
6077 [ + + + - : 133711 : *validated_cs.TargetBlockHash() != *unvalidated_cs.m_from_snapshot_blockhash ||
+ + ]
6078 : : // Or the validated chainstate has not reached the snapshot block yet...
6079 : 909 : !validated_cs.ReachedTarget()) {
6080 : : // Then the snapshot cannot be validated and there is nothing to do.
6081 : 131880 : return SnapshotCompletionResult::SKIPPED;
6082 : : }
6083 [ - + - + ]: 26 : assert(validated_cs.TargetBlock() == validated_cs.m_chain.Tip());
6084 : :
6085 : 14 : auto handle_invalid_snapshot = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
6086 : 1 : bilingual_str user_error = strprintf(_(
6087 : : "%s failed to validate the -assumeutxo snapshot state. "
6088 : : "This indicates a hardware problem, or a bug in the software, or a "
6089 : : "bad software modification that allowed an invalid snapshot to be "
6090 : : "loaded. As a result of this, the node will shut down and stop using any "
6091 : : "state that was built on the snapshot, resetting the chain height "
6092 : : "from %d to %d. On the next "
6093 : : "restart, the node will resume syncing from %d "
6094 : : "without using any snapshot data. "
6095 : : "Please report this incident to %s, including how you obtained the snapshot. "
6096 : : "The invalid snapshot chainstate will be left on disk in case it is "
6097 : : "helpful in diagnosing the issue that caused this error."),
6098 : 2 : CLIENT_NAME, unvalidated_cs.m_chain.Height(),
6099 : 1 : validated_cs.m_chain.Height(),
6100 [ - + - + ]: 1 : validated_cs.m_chain.Height(), CLIENT_BUGREPORT);
6101 : :
6102 [ + - ]: 1 : LogError("[snapshot] !!! %s\n", user_error.original);
6103 [ + - ]: 1 : LogError("[snapshot] deleting snapshot, reverting to validated chain, and stopping node\n");
6104 : :
6105 : : // Reset chainstate target to network tip instead of snapshot block.
6106 [ + - ]: 1 : validated_cs.SetTargetBlock(nullptr);
6107 : :
6108 : 1 : unvalidated_cs.m_assumeutxo = Assumeutxo::INVALID;
6109 : :
6110 [ + - ]: 1 : auto rename_result = unvalidated_cs.InvalidateCoinsDBOnDisk();
6111 [ - + ]: 1 : if (!rename_result) {
6112 [ # # # # : 0 : user_error += Untranslated("\n") + util::ErrorString(rename_result);
# # # # ]
6113 : : }
6114 : :
6115 [ + - ]: 1 : GetNotifications().fatalError(user_error);
6116 : 2 : };
6117 : :
6118 : 13 : CCoinsViewDB& validated_coins_db = validated_cs.CoinsDB();
6119 : 13 : validated_cs.ForceFlushStateToDisk();
6120 : :
6121 [ - + ]: 13 : const auto& maybe_au_data = m_options.chainparams.AssumeutxoForHeight(validated_cs.m_chain.Height());
6122 [ - + ]: 13 : if (!maybe_au_data) {
6123 : 0 : LogWarning("[snapshot] assumeutxo data not found for height "
6124 : : "(%d) - refusing to validate snapshot", validated_cs.m_chain.Height());
6125 : 0 : handle_invalid_snapshot();
6126 : 0 : return SnapshotCompletionResult::MISSING_CHAINPARAMS;
6127 : : }
6128 : :
6129 : 13 : const AssumeutxoData& au_data = *maybe_au_data;
6130 : 13 : std::optional<CCoinsStats> validated_cs_stats;
6131 : 13 : LogInfo("[snapshot] computing UTXO stats for background chainstate to validate "
6132 : : "snapshot - this could take a few minutes");
6133 : 13 : try {
6134 : 13 : validated_cs_stats = ComputeUTXOStats(
6135 : : CoinStatsHashType::HASH_SERIALIZED,
6136 : : validated_coins_db,
6137 [ + - ]: 13 : m_blockman,
6138 [ + - ]: 3145 : [&interrupt = m_interrupt] { SnapshotUTXOHashBreakpoint(interrupt); });
6139 [ - - ]: 0 : } catch (StopHashingException const&) {
6140 : 0 : return SnapshotCompletionResult::STATS_FAILED;
6141 : 0 : }
6142 : :
6143 : : // XXX note that this function is slow and will hold cs_main for potentially minutes.
6144 [ - + ]: 13 : if (!validated_cs_stats) {
6145 : 0 : LogWarning("[snapshot] failed to generate stats for validation coins db");
6146 : : // While this isn't a problem with the snapshot per se, this condition
6147 : : // prevents us from validating the snapshot, so we should shut down and let the
6148 : : // user handle the issue manually.
6149 : 0 : handle_invalid_snapshot();
6150 : 0 : return SnapshotCompletionResult::STATS_FAILED;
6151 : : }
6152 : :
6153 : : // Compare the validated chainstate's UTXO set hash against the hard-coded
6154 : : // assumeutxo hash we expect.
6155 : : //
6156 : : // TODO: For belt-and-suspenders, we could cache the UTXO set
6157 : : // hash for the snapshot when it's loaded in its chainstate's leveldb. We could then
6158 : : // reference that here for an additional check.
6159 [ + + ]: 13 : if (AssumeutxoHash{validated_cs_stats->hashSerialized} != au_data.hash_serialized) {
6160 [ + - + - ]: 1 : LogWarning("[snapshot] hash mismatch: actual=%s, expected=%s",
6161 : : validated_cs_stats->hashSerialized.ToString(),
6162 : : au_data.hash_serialized.ToString());
6163 : 1 : handle_invalid_snapshot();
6164 : 1 : return SnapshotCompletionResult::HASH_MISMATCH;
6165 : : }
6166 : :
6167 [ + - ]: 12 : LogInfo("[snapshot] snapshot beginning at %s has been fully validated",
6168 : : unvalidated_cs.m_from_snapshot_blockhash->ToString());
6169 : :
6170 : 12 : unvalidated_cs.m_assumeutxo = Assumeutxo::VALIDATED;
6171 [ - + ]: 12 : validated_cs.m_target_utxohash = AssumeutxoHash{validated_cs_stats->hashSerialized};
6172 : 12 : this->MaybeRebalanceCaches();
6173 : :
6174 : 12 : return SnapshotCompletionResult::SUCCESS;
6175 : : }
6176 : :
6177 : 4689522 : Chainstate& ChainstateManager::ActiveChainstate() const
6178 : : {
6179 : 4689522 : LOCK(::cs_main);
6180 [ + - + - ]: 4689522 : return CurrentChainstate();
6181 : 4689522 : }
6182 : :
6183 : 1969 : void ChainstateManager::MaybeRebalanceCaches()
6184 : : {
6185 : 1969 : AssertLockHeld(::cs_main);
6186 : 1969 : Chainstate& current_cs{CurrentChainstate()};
6187 : 1969 : Chainstate* historical_cs{HistoricalChainstate()};
6188 [ + + + + ]: 1969 : if (!historical_cs && !current_cs.m_from_snapshot_blockhash) {
6189 : : // Allocate everything to the IBD chainstate. This will always happen
6190 : : // when we are not using a snapshot.
6191 : 1930 : current_cs.ResizeCoinsCaches(m_total_coinstip_cache, m_total_coinsdb_cache);
6192 [ + + ]: 39 : } else if (!historical_cs) {
6193 : : // If background validation has completed and snapshot is our active chain...
6194 : 13 : LogInfo("[snapshot] allocating all cache to the snapshot chainstate");
6195 : : // Allocate everything to the snapshot chainstate.
6196 : 13 : current_cs.ResizeCoinsCaches(m_total_coinstip_cache, m_total_coinsdb_cache);
6197 : : } else {
6198 : : // If both chainstates exist, determine who needs more cache based on IBD status.
6199 : : //
6200 : : // Note: shrink caches first so that we don't inadvertently overwhelm available memory.
6201 [ + + ]: 26 : if (IsInitialBlockDownload()) {
6202 : 14 : historical_cs->ResizeCoinsCaches(
6203 : 14 : m_total_coinstip_cache * 0.05, m_total_coinsdb_cache * 0.05);
6204 : 14 : current_cs.ResizeCoinsCaches(
6205 : 14 : m_total_coinstip_cache * 0.95, m_total_coinsdb_cache * 0.95);
6206 : : } else {
6207 : 12 : current_cs.ResizeCoinsCaches(
6208 : 12 : m_total_coinstip_cache * 0.05, m_total_coinsdb_cache * 0.05);
6209 : 12 : historical_cs->ResizeCoinsCaches(
6210 : 12 : m_total_coinstip_cache * 0.95, m_total_coinsdb_cache * 0.95);
6211 : : }
6212 : : }
6213 : 1969 : }
6214 : :
6215 : 39 : void ChainstateManager::ResetChainstates()
6216 : : {
6217 : 39 : m_chainstates.clear();
6218 : 39 : }
6219 : :
6220 : : /**
6221 : : * Apply default chain params to nullopt members.
6222 : : * This helps to avoid coding errors around the accidental use of the compare
6223 : : * operators that accept nullopt, thus ignoring the intended default value.
6224 : : */
6225 : 1414 : static ChainstateManager::Options&& Flatten(ChainstateManager::Options&& opts)
6226 : : {
6227 [ + + ]: 1414 : if (!opts.check_block_index.has_value()) opts.check_block_index = opts.chainparams.DefaultConsistencyChecks();
6228 [ + + - + ]: 1414 : if (!opts.minimum_chain_work.has_value()) opts.minimum_chain_work = UintToArith256(opts.chainparams.GetConsensus().nMinimumChainWork);
6229 [ + + ]: 1414 : if (!opts.assumed_valid_block.has_value()) opts.assumed_valid_block = opts.chainparams.GetConsensus().defaultAssumeValid;
6230 : 1414 : return std::move(opts);
6231 : : }
6232 : :
6233 : 1414 : ChainstateManager::ChainstateManager(const util::SignalInterrupt& interrupt, Options options, node::BlockManager::Options blockman_options)
6234 : 1414 : : m_script_check_queue{/*batch_size=*/128, std::clamp(options.worker_threads_num, 0, MAX_SCRIPTCHECK_THREADS)},
6235 : 1414 : m_interrupt{interrupt},
6236 [ + - ]: 1416 : m_options{Flatten(std::move(options))},
6237 [ + - + + ]: 1414 : m_blockman{interrupt, std::move(blockman_options)},
6238 [ + - ]: 1412 : m_all_consensus_script_flags{GetAllConsensusScriptFlags(m_options.chainparams.GetConsensus())},
6239 [ + - + - : 4240 : m_validation_cache{m_options.script_execution_cache_bytes, m_options.signature_cache_bytes}
+ - ]
6240 : : {
6241 : 1414 : }
6242 : :
6243 : 1412 : ChainstateManager::~ChainstateManager()
6244 : : {
6245 : 1412 : LOCK(::cs_main);
6246 : :
6247 [ + - ]: 1412 : m_versionbitscache.Clear();
6248 : 5648 : }
6249 : :
6250 : 1401 : Chainstate* ChainstateManager::LoadAssumeutxoChainstate()
6251 : : {
6252 [ - + ]: 1401 : assert(!CurrentChainstate().m_from_snapshot_blockhash);
6253 : 1401 : std::optional<fs::path> path = node::FindAssumeutxoChainstateDir(m_options.datadir);
6254 [ + + ]: 1401 : if (!path) {
6255 : : return nullptr;
6256 : : }
6257 [ + - + - ]: 9 : std::optional<uint256> base_blockhash = node::ReadSnapshotBaseBlockhash(*path);
6258 [ + - ]: 9 : if (!base_blockhash) {
6259 : : return nullptr;
6260 : : }
6261 [ - + + - ]: 18 : LogInfo("[snapshot] detected active snapshot chainstate (%s) - loading",
6262 : : fs::PathToString(*path));
6263 : :
6264 [ + - ]: 9 : auto snapshot_chainstate{std::make_unique<Chainstate>(nullptr, m_blockman, *this, base_blockhash)};
6265 [ + - + - ]: 9 : LogInfo("[snapshot] switching active chainstate to %s", snapshot_chainstate->ToString());
6266 [ + - ]: 9 : return &this->AddChainstate(std::move(snapshot_chainstate));
6267 : 1410 : }
6268 : :
6269 : 28 : Chainstate& ChainstateManager::AddChainstate(std::unique_ptr<Chainstate> chainstate)
6270 : : {
6271 : 28 : Chainstate& prev_chainstate{CurrentChainstate()};
6272 [ - + ]: 28 : assert(prev_chainstate.m_assumeutxo == Assumeutxo::VALIDATED);
6273 : : // Set target block for historical chainstate to snapshot block.
6274 [ - + ]: 28 : assert(!prev_chainstate.TargetBlockHash());
6275 : 28 : prev_chainstate.SetTargetBlockHash(*Assert(chainstate->m_from_snapshot_blockhash));
6276 : 28 : m_chainstates.push_back(std::move(chainstate));
6277 : 28 : Chainstate& curr_chainstate{CurrentChainstate()};
6278 [ - + ]: 28 : assert(&curr_chainstate == m_chainstates.back().get());
6279 : :
6280 : : // Transfer possession of the mempool to the chainstate.
6281 : : // Mempool is empty at this point because we're still in IBD.
6282 [ + + - + ]: 28 : assert(!prev_chainstate.m_mempool || prev_chainstate.m_mempool->size() == 0);
6283 [ - + ]: 28 : assert(!curr_chainstate.m_mempool);
6284 : 28 : std::swap(curr_chainstate.m_mempool, prev_chainstate.m_mempool);
6285 : 28 : return curr_chainstate;
6286 : : }
6287 : :
6288 : 183808 : bool IsBIP30Repeat(const CBlockIndex& block_index)
6289 : : {
6290 [ - + - - ]: 183808 : return (block_index.nHeight==91842 && block_index.GetBlockHash() == uint256{"00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec"}) ||
6291 [ - + - - ]: 183808 : (block_index.nHeight==91880 && block_index.GetBlockHash() == uint256{"00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"});
6292 : : }
6293 : :
6294 : 12312 : bool IsBIP30Unspendable(const uint256& block_hash, int block_height)
6295 : : {
6296 [ - + - - : 12312 : return (block_height==91722 && block_hash == uint256{"00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"}) ||
- + ]
6297 [ # # ]: 0 : (block_height==91812 && block_hash == uint256{"00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"});
6298 : : }
6299 : :
6300 : 1 : util::Result<void> Chainstate::InvalidateCoinsDBOnDisk()
6301 : : {
6302 : : // Should never be called on a non-snapshot chainstate.
6303 [ - + ]: 1 : assert(m_from_snapshot_blockhash);
6304 : :
6305 : : // Coins views no longer usable.
6306 [ + - ]: 1 : m_coins_views.reset();
6307 : :
6308 : 1 : const fs::path db_path{StoragePath()};
6309 [ + - + - ]: 2 : const fs::path invalid_path{db_path + "_INVALID"};
6310 [ - + ]: 1 : const std::string db_path_str{fs::PathToString(db_path)};
6311 [ - + ]: 1 : const std::string invalid_path_str{fs::PathToString(invalid_path)};
6312 [ + - ]: 1 : LogInfo("[snapshot] renaming snapshot datadir %s to %s", db_path_str, invalid_path_str);
6313 : :
6314 : : // The invalid storage directory is simply moved and not deleted because we may
6315 : : // want to do forensics later during issue investigation. The user is instructed
6316 : : // accordingly in MaybeValidateSnapshot().
6317 : 1 : try {
6318 [ + - ]: 1 : fs::rename(db_path, invalid_path);
6319 [ - - ]: 0 : } catch (const fs::filesystem_error& e) {
6320 [ - - ]: 0 : LogError("While invalidating the coins db: Error renaming file '%s' -> '%s': %s",
6321 : : db_path_str, invalid_path_str, e.what());
6322 [ - - ]: 0 : return util::Error{strprintf(_(
6323 : : "Rename of '%s' -> '%s' failed. "
6324 : : "You should resolve this by manually moving or deleting the invalid "
6325 : : "snapshot directory %s, otherwise you will encounter the same error again "
6326 : : "on the next startup."),
6327 : 0 : db_path_str, invalid_path_str, db_path_str)};
6328 [ - - ]: 0 : }
6329 : 1 : return {};
6330 : 3 : }
6331 : :
6332 : 3 : bool ChainstateManager::DeleteChainstate(Chainstate& chainstate)
6333 : : {
6334 : 3 : AssertLockHeld(::cs_main);
6335 [ - + ]: 3 : assert(!chainstate.m_coins_views);
6336 : 3 : const fs::path db_path{chainstate.StoragePath()};
6337 [ + - + - : 6 : if (!DeleteCoinsDBFromDisk(db_path, /*is_snapshot=*/bool{chainstate.m_from_snapshot_blockhash})) {
- + ]
6338 [ # # # # ]: 0 : LogError("Deletion of %s failed. Please remove it manually to continue reindexing.",
6339 : : fs::PathToString(db_path));
6340 : 0 : return false;
6341 : : }
6342 [ + - ]: 3 : std::unique_ptr<Chainstate> prev_chainstate{Assert(RemoveChainstate(chainstate))};
6343 [ + - ]: 3 : Chainstate& curr_chainstate{CurrentChainstate()};
6344 [ + + + - : 3 : assert(!prev_chainstate->m_mempool || prev_chainstate->m_mempool->size() == 0);
- + ]
6345 [ - + ]: 3 : assert(!curr_chainstate.m_mempool);
6346 : 3 : std::swap(curr_chainstate.m_mempool, prev_chainstate->m_mempool);
6347 : 3 : return true;
6348 : 6 : }
6349 : :
6350 : 451200 : ChainstateRole Chainstate::GetRole() const
6351 : : {
6352 : 451200 : return ChainstateRole{.validated = m_assumeutxo == Assumeutxo::VALIDATED, .historical = bool{m_target_blockhash}};
6353 : : }
6354 : :
6355 : 2791 : void ChainstateManager::RecalculateBestHeader()
6356 : : {
6357 : 2791 : AssertLockHeld(cs_main);
6358 [ - + ]: 2791 : m_best_header = ActiveChain().Tip();
6359 [ + + + + ]: 5552647 : for (auto& entry : m_blockman.m_block_index) {
6360 [ + + + + ]: 5549856 : if (!(entry.second.nStatus & BLOCK_FAILED_VALID) && m_best_header->nChainWork < entry.second.nChainWork) {
6361 : 69 : m_best_header = &entry.second;
6362 : : }
6363 : : }
6364 : 2791 : }
6365 : :
6366 : 0 : std::optional<int> ChainstateManager::BlocksAheadOfTip() const
6367 : : {
6368 : 0 : LOCK(::cs_main);
6369 : 0 : const CBlockIndex* best_header{m_best_header};
6370 [ # # # # ]: 0 : const CBlockIndex* tip{ActiveChain().Tip()};
6371 : : // Only consider headers that extend the active tip; ignore competing branches.
6372 [ # # # # : 0 : if (best_header && tip && best_header->nChainWork > tip->nChainWork &&
# # # # ]
6373 [ # # ]: 0 : best_header->GetAncestor(tip->nHeight) == tip) {
6374 : 0 : return best_header->nHeight - tip->nHeight;
6375 : : }
6376 : 0 : return std::nullopt;
6377 : 0 : }
6378 : :
6379 : 3 : bool ChainstateManager::ValidatedSnapshotCleanup(Chainstate& validated_cs, Chainstate& unvalidated_cs)
6380 : : {
6381 : 3 : AssertLockHeld(::cs_main);
6382 [ + - ]: 3 : if (unvalidated_cs.m_assumeutxo != Assumeutxo::VALIDATED) {
6383 : : // No need to clean up.
6384 : : return false;
6385 : : }
6386 : :
6387 : 3 : const fs::path validated_path{validated_cs.StoragePath()};
6388 [ + - ]: 3 : const fs::path assumed_valid_path{unvalidated_cs.StoragePath()};
6389 [ + - + - ]: 6 : const fs::path delete_path{validated_path + "_todelete"};
6390 : :
6391 : : // Since we're going to be moving around the underlying leveldb filesystem content
6392 : : // for each chainstate, make sure that the chainstates (and their constituent
6393 : : // CoinsViews members) have been destructed first.
6394 : : //
6395 : : // The caller of this method will be responsible for reinitializing chainstates
6396 : : // if they want to continue operation.
6397 [ + - ]: 3 : this->ResetChainstates();
6398 [ - + - + ]: 3 : assert(this->m_chainstates.size() == 0);
6399 : :
6400 [ - + + - ]: 6 : LogInfo("[snapshot] deleting background chainstate directory (now unnecessary) (%s)",
6401 : : fs::PathToString(validated_path));
6402 : :
6403 : 3 : auto rename_failed_abort = [this](
6404 : : fs::path p_old,
6405 : : fs::path p_new,
6406 : : const fs::filesystem_error& err) {
6407 [ # # # # : 0 : LogError("[snapshot] Error renaming path (%s) -> (%s): %s\n",
# # ]
6408 : : fs::PathToString(p_old), fs::PathToString(p_new), err.what());
6409 [ # # # # ]: 0 : GetNotifications().fatalError(strprintf(_(
6410 : : "Rename of '%s' -> '%s' failed. "
6411 : : "Cannot clean up the background chainstate leveldb directory."),
6412 [ # # # # ]: 0 : fs::PathToString(p_old), fs::PathToString(p_new)));
6413 : 0 : };
6414 : :
6415 : 3 : try {
6416 [ + - ]: 3 : fs::rename(validated_path, delete_path);
6417 [ - - ]: 0 : } catch (const fs::filesystem_error& e) {
6418 [ - - - - : 0 : rename_failed_abort(validated_path, delete_path, e);
- - ]
6419 : 0 : throw;
6420 : 0 : }
6421 : :
6422 [ - + - + : 9 : LogInfo("[snapshot] moving snapshot chainstate (%s) to "
+ - ]
6423 : : "default chainstate directory (%s)",
6424 : : fs::PathToString(assumed_valid_path), fs::PathToString(validated_path));
6425 : :
6426 : 3 : try {
6427 [ + - ]: 3 : fs::rename(assumed_valid_path, validated_path);
6428 [ - - ]: 0 : } catch (const fs::filesystem_error& e) {
6429 [ - - - - : 0 : rename_failed_abort(assumed_valid_path, validated_path, e);
- - ]
6430 : 0 : throw;
6431 : 0 : }
6432 : :
6433 [ + - + - : 6 : if (!DeleteCoinsDBFromDisk(delete_path, /*is_snapshot=*/false)) {
- + ]
6434 : : // No need to FatalError because once the unneeded bg chainstate data is
6435 : : // moved, it will not interfere with subsequent initialization.
6436 [ # # # # ]: 0 : LogWarning("Deletion of %s failed. Please remove it manually, as the "
6437 : : "directory is now unnecessary.",
6438 : : fs::PathToString(delete_path));
6439 : : } else {
6440 [ - + + - ]: 6 : LogInfo("[snapshot] deleted background chainstate directory (%s)",
6441 : : fs::PathToString(validated_path));
6442 : : }
6443 : 3 : return true;
6444 : 9 : }
6445 : :
6446 : 537 : std::pair<int, int> Chainstate::GetPruneRange(int last_height_can_prune) const
6447 : : {
6448 [ - + - + ]: 537 : if (m_chain.Height() <= 0) {
6449 : 0 : return {0, 0};
6450 : : }
6451 : 537 : int prune_start{0};
6452 : :
6453 [ + + + + ]: 537 : if (m_from_snapshot_blockhash && m_assumeutxo != Assumeutxo::VALIDATED) {
6454 : : // Only prune blocks _after_ the snapshot if this is a snapshot chain
6455 : : // that has not been fully validated yet. The earlier blocks need to be
6456 : : // kept to validate the snapshot
6457 : 12 : prune_start = Assert(SnapshotBase())->nHeight + 1;
6458 : : }
6459 : :
6460 : 1074 : int max_prune = std::max<int>(
6461 [ - + + + ]: 537 : 0, m_chain.Height() - static_cast<int>(MIN_BLOCKS_TO_KEEP));
6462 : :
6463 : : // last block to prune is the lesser of (caller-specified height, MIN_BLOCKS_TO_KEEP from the tip)
6464 : : //
6465 : : // While you might be tempted to prune the background chainstate more
6466 : : // aggressively (i.e. fewer MIN_BLOCKS_TO_KEEP), this won't work with index
6467 : : // building - specifically blockfilterindex requires undo data, and if
6468 : : // we don't maintain this trailing window, we hit indexing failures.
6469 [ + + ]: 537 : int prune_end = std::min(last_height_can_prune, max_prune);
6470 : :
6471 : 537 : return {prune_start, prune_end};
6472 : : }
6473 : :
6474 : 345658 : std::optional<std::pair<const CBlockIndex*, const CBlockIndex*>> ChainstateManager::GetHistoricalBlockRange() const
6475 : : {
6476 : 345658 : const Chainstate* chainstate{HistoricalChainstate()};
6477 [ + + ]: 345658 : if (!chainstate) return {};
6478 [ - + ]: 3138 : return std::make_pair(chainstate->m_chain.Tip(), chainstate->TargetBlock());
6479 : : }
6480 : :
6481 : 1175 : util::Result<void> ChainstateManager::ActivateBestChains()
6482 : : {
6483 : : // We can't hold cs_main during ActivateBestChain even though we're accessing
6484 : : // the chainman unique_ptrs since ABC requires us not to be holding cs_main, so retrieve
6485 : : // the relevant pointers before the ABC call.
6486 : 1175 : AssertLockNotHeld(cs_main);
6487 : 1175 : std::vector<Chainstate*> chainstates;
6488 : 1175 : {
6489 [ + - ]: 1175 : LOCK(GetMutex());
6490 [ - + + - ]: 1175 : chainstates.reserve(m_chainstates.size());
6491 [ + + ]: 2352 : for (const auto& chainstate : m_chainstates) {
6492 [ + - + - : 1177 : if (chainstate && chainstate->m_assumeutxo != Assumeutxo::INVALID && !chainstate->m_target_utxohash) {
+ - ]
6493 [ + - ]: 1177 : chainstates.push_back(chainstate.get());
6494 : : }
6495 : : }
6496 : 0 : }
6497 [ + + ]: 2352 : for (Chainstate* chainstate : chainstates) {
6498 [ + - ]: 1177 : BlockValidationState state;
6499 [ + - - + : 1177 : if (!chainstate->ActivateBestChain(state, nullptr)) {
- + ]
6500 [ # # ]: 0 : LOCK(GetMutex());
6501 [ # # # # : 0 : return util::Error{Untranslated(strprintf("%s Failed to connect best block (%s)", chainstate->ToString(), state.ToString()))};
# # # # #
# ]
6502 : 0 : }
6503 : 1177 : }
6504 : 1175 : return {};
6505 : 1175 : }
|