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