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