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