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