Bitcoin Core 32.99.0
P2P Digital Currency
validation_chainstatemanager_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2019-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4//
5#include <chainparams.h>
11#include <node/utxo_snapshot.h>
12#include <random.h>
13#include <rpc/blockchain.h>
14#include <sync.h>
16#include <test/util/common.h>
17#include <test/util/logging.h>
18#include <test/util/random.h>
21#include <uint256.h>
22#include <util/byte_units.h>
23#include <util/result.h>
24#include <util/vector.h>
25#include <validation.h>
26#include <validationinterface.h>
27
28#include <tinyformat.h>
29
30#include <vector>
31
32#include <boost/test/unit_test.hpp>
33
37
38BOOST_FIXTURE_TEST_SUITE(validation_chainstatemanager_tests, TestingSetup)
39
40
44{
46
48
49 // Create a legacy (IBD) chainstate.
50 //
51 Chainstate& c1 = manager.ActiveChainstate();
52
54 {
55 LOCK(manager.GetMutex());
56 BOOST_CHECK_EQUAL(manager.m_chainstates.size(), 1);
57 BOOST_CHECK_EQUAL(manager.m_chainstates[0].get(), &c1);
58 }
59
60 auto& active_chain = WITH_LOCK(manager.GetMutex(), return manager.ActiveChain());
61 BOOST_CHECK_EQUAL(&active_chain, &c1.m_chain);
62
63 // Get to a valid assumeutxo tip (per chainparams);
64 mineBlocks(10);
65 BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 110);
66 auto active_tip = WITH_LOCK(manager.GetMutex(), return manager.ActiveTip());
67 auto exp_tip = c1.m_chain.Tip();
68 BOOST_CHECK_EQUAL(active_tip, exp_tip);
69
71
72 // Create a snapshot-based chainstate.
73 //
74 const uint256 snapshot_blockhash = active_tip->GetBlockHash();
75 Chainstate& c2{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, snapshot_blockhash)))};
76 c2.InitCoinsDB(
77 /*cache_size_bytes=*/8_MiB, /*in_memory=*/true, /*should_wipe=*/false);
78 {
80 c2.InitCoinsCache(8_MiB);
81 c2.CoinsTip().SetBestBlock(active_tip->GetBlockHash());
82 for (const auto& cs : manager.m_chainstates) {
83 cs->ClearBlockIndexCandidates();
84 }
85 c2.LoadChainTip();
86 for (const auto& cs : manager.m_chainstates) {
87 cs->PopulateBlockIndexCandidates();
88 }
89 }
91 BOOST_CHECK(c2.ActivateBestChain(_, nullptr));
92
95 BOOST_CHECK_EQUAL(&c2, &manager.ActiveChainstate());
96 BOOST_CHECK(&c1 != &manager.ActiveChainstate());
97 {
98 LOCK(manager.GetMutex());
99 BOOST_CHECK_EQUAL(manager.m_chainstates.size(), 2);
100 BOOST_CHECK_EQUAL(manager.m_chainstates[0].get(), &c1);
101 BOOST_CHECK_EQUAL(manager.m_chainstates[1].get(), &c2);
102 }
103
104 auto& active_chain2 = WITH_LOCK(manager.GetMutex(), return manager.ActiveChain());
105 BOOST_CHECK_EQUAL(&active_chain2, &c2.m_chain);
106
107 BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 110);
108 mineBlocks(1);
109 BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 111);
110 BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return c1.m_chain.Height()), 110);
111
112 auto active_tip2 = WITH_LOCK(manager.GetMutex(), return manager.ActiveTip());
113 BOOST_CHECK_EQUAL(active_tip, active_tip2->pprev);
114 BOOST_CHECK_EQUAL(active_tip, c1.m_chain.Tip());
115 BOOST_CHECK_EQUAL(active_tip2, c2.m_chain.Tip());
116
117 // Let scheduler events finish running to avoid accessing memory that is going to be unloaded
118 m_node.validation_signals->SyncWithValidationInterfaceQueue();
119}
120
121BOOST_FIXTURE_TEST_CASE(chainstatemanager_delete_chainstate_no_mempool, ChainTestingSetup)
122{
123 auto& manager{*Assert(m_node.chainman)};
124 auto& validated{WITH_LOCK(::cs_main, return manager.InitializeChainstate(/*mempool=*/nullptr))};
125 auto& snapshot{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, uint256::ONE)))};
126 WITH_LOCK(::cs_main, validated.SetTargetBlock(nullptr));
127 BOOST_CHECK(WITH_LOCK(::cs_main, return manager.DeleteChainstate(snapshot))); // Accept Kernel's null mempool
128}
129
131BOOST_FIXTURE_TEST_CASE(chainstatemanager_rebalance_caches, TestChain100Setup)
132{
134
135 size_t max_cache = 10000;
136 manager.m_total_coinsdb_cache = max_cache;
137 manager.m_total_coinstip_cache = max_cache;
138
139 std::vector<Chainstate*> chainstates;
140
141 // Create a legacy (IBD) chainstate.
142 //
143 Chainstate& c1 = manager.ActiveChainstate();
144 chainstates.push_back(&c1);
145 {
147 c1.InitCoinsCache(8_MiB);
148 manager.MaybeRebalanceCaches();
149 }
150
153
154 // Create a snapshot-based chainstate.
155 //
156 CBlockIndex* snapshot_base{WITH_LOCK(manager.GetMutex(), return manager.ActiveChain()[manager.ActiveChain().Height() / 2])};
157 Chainstate& c2{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, *snapshot_base->phashBlock)))};
158 chainstates.push_back(&c2);
159 c2.InitCoinsDB(
160 /*cache_size_bytes=*/8_MiB, /*in_memory=*/true, /*should_wipe=*/false);
161
162 // Reset IBD state so IsInitialBlockDownload() returns true and causes
163 // MaybeRebalanceCaches() to prioritize the snapshot chainstate, giving it
164 // more cache space than the snapshot chainstate. Calling ResetIbd() is
165 // necessary because m_cached_is_ibd is already latched to false before
166 // the test starts due to the test setup. After ResetIbd() is called,
167 // IsInitialBlockDownload() will return true because at this point the active
168 // chainstate has a null chain tip.
169 static_cast<TestChainstateManager&>(manager).ResetIbd();
170
171 {
173 c2.InitCoinsCache(8_MiB);
174 manager.MaybeRebalanceCaches();
175 }
176
177 BOOST_CHECK_EQUAL(c1.m_coinstip_cache_size_bytes, size_t(max_cache * 0.05));
178 BOOST_CHECK_EQUAL(c1.m_coinsdb_cache_size_bytes, size_t(max_cache * 0.05));
179 BOOST_CHECK_EQUAL(c2.m_coinstip_cache_size_bytes, size_t(max_cache * 0.95));
180 BOOST_CHECK_EQUAL(c2.m_coinsdb_cache_size_bytes, size_t(max_cache * 0.95));
181}
182
183BOOST_FIXTURE_TEST_CASE(chainstatemanager_ibd_exit_after_loading_blocks, ChainTestingSetup)
184{
185 CBlockIndex tip;
187 auto apply{[&](bool cached_is_ibd, bool loading_blocks, bool tip_exists, bool enough_work, bool tip_recent) {
189 chainman.ResetChainstates();
190 chainman.InitializeChainstate(m_node.mempool.get());
191
192 const auto recent_time{Now<NodeSeconds>() - chainman.m_options.max_tip_age};
193
194 chainman.m_cached_is_ibd.store(cached_is_ibd, std::memory_order_relaxed);
195 chainman.m_blockman.m_importing = loading_blocks;
196 if (tip_exists) {
197 tip.nChainWork = chainman.MinimumChainWork() - (enough_work ? 0 : 1);
198 tip.nTime = (recent_time - (tip_recent ? 0h : 100h)).time_since_epoch().count();
199 chainman.ActiveChain().SetTip(tip);
200 } else {
201 assert(!chainman.ActiveChain().Tip());
202 }
203 chainman.UpdateIBDStatus();
204 }};
205
206 for (const bool cached_is_ibd : {false, true}) {
207 for (const bool loading_blocks : {false, true}) {
208 for (const bool tip_exists : {false, true}) {
209 for (const bool enough_work : {false, true}) {
210 for (const bool tip_recent : {false, true}) {
211 apply(cached_is_ibd, loading_blocks, tip_exists, enough_work, tip_recent);
212 const bool expected_ibd = cached_is_ibd && (loading_blocks || !tip_exists || !enough_work || !tip_recent);
213 BOOST_CHECK_EQUAL(chainman.IsInitialBlockDownload(), expected_ibd);
214 }
215 }
216 }
217 }
218 }
219}
220
222 // Run with coinsdb on the filesystem to support, e.g., moving invalidated
223 // chainstate dirs to "*_invalid".
224 //
225 // Note that this means the tests run considerably slower than in-memory DB
226 // tests, but we can't otherwise test this functionality since it relies on
227 // destructive filesystem operations.
229 {},
230 {
231 .coins_db_in_memory = false,
232 .block_tree_db_in_memory = false,
233 },
234 }
235 {
236 }
237
238 std::tuple<Chainstate*, Chainstate*> SetupSnapshot()
239 {
241
242 {
246 }
247
248 size_t initial_size;
249 size_t initial_total_coins{100};
250
251 // Make some initial assertions about the contents of the chainstate.
252 {
254 CCoinsViewCache& ibd_coinscache = chainman.ActiveChainstate().CoinsTip();
255 initial_size = ibd_coinscache.GetCacheSize();
256 size_t total_coins{0};
257
258 for (CTransactionRef& txn : m_coinbase_txns) {
259 COutPoint op{txn->GetHash(), 0};
260 BOOST_CHECK(ibd_coinscache.HaveCoin(op));
261 total_coins++;
262 }
263
264 BOOST_CHECK_EQUAL(total_coins, initial_total_coins);
265 BOOST_CHECK_EQUAL(initial_size, initial_total_coins);
266 }
267
268 Chainstate& validation_chainstate = chainman.ActiveChainstate();
269
270 // Snapshot should refuse to load at this height.
271 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(this));
273
274 // Mine 10 more blocks, putting at us height 110 where a valid assumeutxo value can
275 // be found.
276 constexpr int snapshot_height = 110;
277 mineBlocks(10);
278 initial_size += 10;
279 initial_total_coins += 10;
280
281 // Should not load malleated snapshots
282 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
283 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
284 // A UTXO is missing but count is correct
285 metadata.m_coins_count -= 1;
286
287 Txid txid;
288 auto_infile >> txid;
289 // coins size
290 (void)ReadCompactSize(auto_infile);
291 // vout index
292 (void)ReadCompactSize(auto_infile);
293 Coin coin;
294 auto_infile >> coin;
295 }));
296
298
299 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
300 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
301 // Coins count is larger than coins in file
302 metadata.m_coins_count += 1;
303 }));
304 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
305 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
306 // Coins count is smaller than coins in file
307 metadata.m_coins_count -= 1;
308 }));
309 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
310 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
311 // Wrong hash
313 }));
314 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
315 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
316 // Wrong hash
318 }));
319
320 BOOST_REQUIRE(CreateAndActivateUTXOSnapshot(this));
322
323 // Ensure our active chain is the snapshot chainstate.
325
326 Chainstate& snapshot_chainstate = chainman.ActiveChainstate();
327
328 {
330
331 fs::path found = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
332
333 // Note: WriteSnapshotBaseBlockhash() is implicitly tested above.
337 }
338
339 const auto& au_data = ::Params().AssumeutxoForHeight(snapshot_height);
340 const CBlockIndex* tip = WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip());
341
342 BOOST_CHECK_EQUAL(tip->m_chain_tx_count, au_data->m_chain_tx_count);
343
344 // To be checked against later when we try loading a subsequent snapshot.
345 uint256 loaded_snapshot_blockhash{*Assert(WITH_LOCK(chainman.GetMutex(), return chainman.CurrentChainstate().m_from_snapshot_blockhash))};
346
347 // Make some assertions about the both chainstates. These checks ensure the
348 // legacy chainstate hasn't changed and that the newly created chainstate
349 // reflects the expected content.
350 {
352 int chains_tested{0};
353
354 for (const auto& chainstate : chainman.m_chainstates) {
355 BOOST_TEST_MESSAGE("Checking coins in " << chainstate->ToString());
356 CCoinsViewCache& coinscache = chainstate->CoinsTip();
357
358 // Both caches will be empty initially.
359 BOOST_CHECK_EQUAL((unsigned int)0, coinscache.GetCacheSize());
360
361 size_t total_coins{0};
362
363 for (CTransactionRef& txn : m_coinbase_txns) {
364 COutPoint op{txn->GetHash(), 0};
365 BOOST_CHECK(coinscache.HaveCoin(op));
366 total_coins++;
367 }
368
369 BOOST_CHECK_EQUAL(initial_size , coinscache.GetCacheSize());
370 BOOST_CHECK_EQUAL(total_coins, initial_total_coins);
371 chains_tested++;
372 }
373
374 BOOST_CHECK_EQUAL(chains_tested, 2);
375 }
376
377 // Mine some new blocks on top of the activated snapshot chainstate.
378 constexpr size_t new_coins{100};
379 mineBlocks(new_coins); // Defined in TestChain100Setup.
380
381 {
383 size_t coins_in_active{0};
384 size_t coins_in_background{0};
385 size_t coins_missing_from_background{0};
386
387 for (const auto& chainstate : chainman.m_chainstates) {
388 BOOST_TEST_MESSAGE("Checking coins in " << chainstate->ToString());
389 CCoinsViewCache& coinscache = chainstate->CoinsTip();
390 bool is_background = chainstate.get() != &chainman.ActiveChainstate();
391
392 for (CTransactionRef& txn : m_coinbase_txns) {
393 COutPoint op{txn->GetHash(), 0};
394 if (coinscache.HaveCoin(op)) {
395 (is_background ? coins_in_background : coins_in_active)++;
396 } else if (is_background) {
397 coins_missing_from_background++;
398 }
399 }
400 }
401
402 BOOST_CHECK_EQUAL(coins_in_active, initial_total_coins + new_coins);
403 BOOST_CHECK_EQUAL(coins_in_background, initial_total_coins);
404 BOOST_CHECK_EQUAL(coins_missing_from_background, new_coins);
405 }
406
407 // Snapshot should refuse to load after one has already loaded.
408 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(this));
409
410 // Snapshot blockhash should be unchanged.
413 loaded_snapshot_blockhash);
414 return std::make_tuple(&validation_chainstate, &snapshot_chainstate);
415 }
416
417 // Simulate a restart of the node by flushing all state to disk, clearing the
418 // existing ChainstateManager, and unloading the block index.
419 //
420 // @returns a reference to the "restarted" ChainstateManager
422 {
424
425 BOOST_TEST_MESSAGE("Simulating node restart");
426 {
427 LOCK(chainman.GetMutex());
428 for (const auto& cs : chainman.m_chainstates) {
429 if (cs->CanFlushToDisk()) cs->ForceFlushStateToDisk();
430 }
431 }
432 {
433 // Process all callbacks referring to the old manager before wiping it.
434 m_node.validation_signals->SyncWithValidationInterfaceQueue();
437 chainman.ResetChainstates();
438 BOOST_CHECK_EQUAL(chainman.m_chainstates.size(), 0);
439 m_node.notifications = std::make_unique<KernelNotifications>(Assert(m_node.shutdown_request), m_node.exit_status, *Assert(m_node.warnings));
440 const ChainstateManager::Options chainman_opts{
442 .datadir = chainman.m_options.datadir,
443 .notifications = *m_node.notifications,
444 .signals = m_node.validation_signals.get(),
445 };
446 const BlockManager::Options blockman_opts{
447 .chainparams = chainman_opts.chainparams,
448 .blocks_dir = m_args.GetBlocksDirPath(),
449 .notifications = chainman_opts.notifications,
450 .block_tree_db_params = DBParams{
451 .path = chainman.m_options.datadir / "blocks" / "index",
452 .cache_bytes = m_kernel_cache_sizes.block_tree_db,
453 .memory_only = m_block_tree_db_in_memory,
454 },
455 };
456 // For robustness, ensure the old manager is destroyed before creating a
457 // new one.
458 m_node.chainman.reset();
459 m_node.chainman = std::make_unique<ChainstateManager>(*Assert(m_node.shutdown_signal), chainman_opts, blockman_opts);
460 CreateBlockTemplateManager();
461 }
462 return *Assert(m_node.chainman);
463 }
464};
465
467BOOST_FIXTURE_TEST_CASE(chainstatemanager_activate_snapshot, SnapshotTestSetup)
468{
469 this->SetupSnapshot();
470}
471
482BOOST_FIXTURE_TEST_CASE(chainstatemanager_loadblockindex, TestChain100Setup)
483{
485 Chainstate& cs1 = chainman.ActiveChainstate();
486
487 int num_indexes{0};
488 // Blocks in range [assumed_valid_start_idx, last_assumed_valid_idx) will be
489 // marked as assumed-valid and not having data.
490 const int expected_assumed_valid{20};
491 const int last_assumed_valid_idx{111};
492 const int assumed_valid_start_idx = last_assumed_valid_idx - expected_assumed_valid;
493
494 // Mine to height 120, past the hardcoded regtest assumeutxo snapshot at
495 // height 110
496 mineBlocks(20);
497
498 CBlockIndex* validated_tip{nullptr};
499 CBlockIndex* assumed_base{nullptr};
500 CBlockIndex* assumed_tip{WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip())};
501 BOOST_CHECK_EQUAL(assumed_tip->nHeight, 120);
502
503 auto reload_all_block_indexes = [&]() {
504 LOCK(chainman.GetMutex());
505 // For completeness, we also reset the block sequence counters to
506 // ensure that no state which affects the ranking of tip-candidates is
507 // retained (even though this isn't strictly necessary).
509 for (const auto& cs : chainman.m_chainstates) {
510 cs->ClearBlockIndexCandidates();
511 BOOST_CHECK(cs->setBlockIndexCandidates.empty());
512 }
513 chainman.LoadBlockIndex();
514 for (const auto& cs : chainman.m_chainstates) {
515 cs->PopulateBlockIndexCandidates();
516 }
517 };
518
519 // Ensure that without any assumed-valid BlockIndex entries, only the current tip is
520 // considered as a candidate.
521 reload_all_block_indexes();
523
524 // Reset some region of the chain's nStatus, removing the HAVE_DATA flag.
525 for (int i = 0; i <= cs1.m_chain.Height(); ++i) {
527 auto index = cs1.m_chain[i];
528
529 // Blocks with heights in range [91, 110] are marked as missing data.
530 if (i < last_assumed_valid_idx && i >= assumed_valid_start_idx) {
531 index->nStatus = BlockStatus::BLOCK_VALID_TREE;
532 index->nTx = 0;
533 index->m_chain_tx_count = 0;
534 }
535
536 ++num_indexes;
537
538 // Note the last fully-validated block as the expected validated tip.
539 if (i == (assumed_valid_start_idx - 1)) {
540 validated_tip = index;
541 }
542 // Note the last assumed valid block as the snapshot base
543 if (i == last_assumed_valid_idx - 1) {
544 assumed_base = index;
545 }
546 }
547
548 // Note: cs2's tip is not set when ActivateExistingSnapshot is called.
549 Chainstate& cs2{WITH_LOCK(::cs_main, return chainman.AddChainstate(std::make_unique<Chainstate>(nullptr, chainman.m_blockman, chainman, *assumed_base->phashBlock)))};
550
551 // Set tip of the fully validated chain to be the validated tip
552 cs1.m_chain.SetTip(*validated_tip);
553
554 // Set tip of the assume-valid-based chain to the assume-valid block
555 cs2.m_chain.SetTip(*assumed_base);
556
557 // Sanity check test variables.
558 BOOST_CHECK_EQUAL(num_indexes, 121); // 121 total blocks, including genesis
559 BOOST_CHECK_EQUAL(assumed_tip->nHeight, 120); // original chain has height 120
560 BOOST_CHECK_EQUAL(validated_tip->nHeight, 90); // current cs1 chain has height 90
561 BOOST_CHECK_EQUAL(assumed_base->nHeight, 110); // current cs2 chain has height 110
562
563 // Regenerate cs1.setBlockIndexCandidates and cs2.setBlockIndexCandidate and
564 // check contents below.
565 reload_all_block_indexes();
566
567 // The fully validated chain should only have the current validated tip
568 // as a candidate (block 90). Specifically:
569 //
570 // - It does not have blocks 0-89 because they contain less work than the
571 // chain tip.
572 //
573 // - It has block 90 because it has data and equal work to the chain tip,
574 // (since it is the chain tip).
575 //
576 // - It does not have blocks 91-110 because they do not contain data.
577 //
578 // - It does not have any blocks after height 110 because cs1 is a background
579 // chainstate, and only blocks that are ancestors of the snapshot block
580 // are added as candidates for the background chainstate.
582 BOOST_CHECK_EQUAL(cs1.setBlockIndexCandidates.count(validated_tip), 1);
583
584 // The assumed-valid tolerant chain has the assumed valid base as a
585 // candidate, but otherwise has none of the assumed-valid (which do not
586 // HAVE_DATA) blocks as candidates.
587 //
588 // Specifically:
589 // - All blocks below height 110 are not candidates, because cs2 chain tip
590 // has height 110 and they have less work than it does.
591 //
592 // - Block 110 is a candidate even though it does not have data, because it
593 // is the snapshot block, which is assumed valid.
594 //
595 // - Blocks 111-120 are added because they have data.
596
597 // Check that block 90 is absent
598 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(validated_tip), 0);
599 // Check that block 109 is absent
600 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_base->pprev), 0);
601 // Check that block 110 is present
602 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_base), 1);
603 // Check that block 120 is present
604 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_tip), 1);
605 // Check that 11 blocks total are present.
606 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.size(), num_indexes - last_assumed_valid_idx + 1);
607}
608
609BOOST_FIXTURE_TEST_CASE(loadblockindex_invalid_descendants, TestChain100Setup)
610{
611 LOCK(Assert(m_node.chainman)->GetMutex());
612 // consider the chain of blocks grand_parent <- parent <- child
613 // intentionally mark:
614 // - grand_parent: BLOCK_FAILED_VALID
615 // - parent: BLOCK_FAILED_CHILD
616 // - child: not invalid
617 // Test that when the block index is loaded, all blocks are marked as BLOCK_FAILED_VALID
618 auto* child{m_node.chainman->ActiveChain().Tip()};
619 auto* parent{child->pprev};
620 auto* grand_parent{parent->pprev};
621 grand_parent->nStatus = (grand_parent->nStatus | BLOCK_FAILED_VALID);
622 parent->nStatus = (parent->nStatus & ~BLOCK_FAILED_VALID) | BLOCK_FAILED_CHILD;
623 child->nStatus = (child->nStatus & ~BLOCK_FAILED_VALID);
624
625 // Reload block index to recompute block status validity flags.
626 m_node.chainman->LoadBlockIndex();
627
628 // check grand_parent, parent, child is marked as BLOCK_FAILED_VALID after reloading the block index
629 BOOST_CHECK(grand_parent->nStatus & BLOCK_FAILED_VALID);
630 BOOST_CHECK(parent->nStatus & BLOCK_FAILED_VALID);
631 BOOST_CHECK(child->nStatus & BLOCK_FAILED_VALID);
632}
633
636BOOST_FIXTURE_TEST_CASE(invalidate_block_and_reconsider_fork, TestChain100Setup)
637{
639 Chainstate& chainstate = chainman.ActiveChainstate();
640
641 // we have a chain of 100 blocks: genesis(0) <- ... <- block98 <- block99 <- block100
642 CBlockIndex* block98;
643 CBlockIndex* block99;
644 CBlockIndex* block100;
645 {
646 LOCK(chainman.GetMutex());
647 block98 = chainman.ActiveChain()[98];
648 block99 = chainman.ActiveChain()[99];
649 block100 = chainman.ActiveChain()[100];
650 }
651
652 // create the following block constellation:
653 // genesis(0) <- ... <- block98 <- block99 <- block100
654 // <- block99' <- block100'
655 // by temporarily invalidating block99. the chain tip now falls to block98,
656 // mine 2 new blocks on top of block 98 (block99' and block100') and then restore block99 and block 100.
658 BOOST_REQUIRE(chainstate.InvalidateBlock(state, block99));
659 BOOST_REQUIRE(WITH_LOCK(cs_main, return chainman.ActiveChain().Tip()) == block98);
660 CScript coinbase_script = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
661 for (int i = 0; i < 2; ++i) {
662 CreateAndProcessBlock({}, coinbase_script);
663 }
664 const CBlockIndex* fork_block99;
665 const CBlockIndex* fork_block100;
666 {
667 LOCK(chainman.GetMutex());
668 fork_block99 = chainman.ActiveChain()[99];
669 BOOST_REQUIRE(fork_block99->pprev == block98);
670 fork_block100 = chainman.ActiveChain()[100];
671 BOOST_REQUIRE(fork_block100->pprev == fork_block99);
672 }
673 // Restore original block99 and block100
674 {
675 LOCK(chainman.GetMutex());
676 chainstate.ResetBlockFailureFlags(block99);
677 chainman.RecalculateBestHeader();
678 }
679 chainstate.ActivateBestChain(state);
680 BOOST_REQUIRE(WITH_LOCK(cs_main, return chainman.ActiveChain().Tip()) == block100);
681
682 {
683 LOCK(chainman.GetMutex());
684 BOOST_CHECK(!(block100->nStatus & BLOCK_FAILED_VALID));
685 BOOST_CHECK(!(block99->nStatus & BLOCK_FAILED_VALID));
686 BOOST_CHECK(!(fork_block100->nStatus & BLOCK_FAILED_VALID));
687 BOOST_CHECK(!(fork_block99->nStatus & BLOCK_FAILED_VALID));
688 }
689
690 // Invalidate block98
691 BOOST_REQUIRE(chainstate.InvalidateBlock(state, block98));
692
693 {
694 LOCK(chainman.GetMutex());
695 // block98 and all descendants of block98 are marked BLOCK_FAILED_VALID
696 BOOST_CHECK(block98->nStatus & BLOCK_FAILED_VALID);
697 BOOST_CHECK(block99->nStatus & BLOCK_FAILED_VALID);
698 BOOST_CHECK(block100->nStatus & BLOCK_FAILED_VALID);
699 BOOST_CHECK(fork_block99->nStatus & BLOCK_FAILED_VALID);
700 BOOST_CHECK(fork_block100->nStatus & BLOCK_FAILED_VALID);
701 }
702
703 // Reconsider block99. ResetBlockFailureFlags clears BLOCK_FAILED_VALID from
704 // block99 and its ancestors (block98) and descendants (block100)
705 // but NOT from block99' and block100' (not a direct ancestor/descendant)
706 {
707 LOCK(chainman.GetMutex());
708 chainstate.ResetBlockFailureFlags(block99);
709 chainman.RecalculateBestHeader();
710 }
711 chainstate.ActivateBestChain(state);
712 {
713 LOCK(chainman.GetMutex());
714 BOOST_CHECK(!(block98->nStatus & BLOCK_FAILED_VALID));
715 BOOST_CHECK(!(block99->nStatus & BLOCK_FAILED_VALID));
716 BOOST_CHECK(!(block100->nStatus & BLOCK_FAILED_VALID));
717 BOOST_CHECK(fork_block99->nStatus & BLOCK_FAILED_VALID);
718 BOOST_CHECK(fork_block100->nStatus & BLOCK_FAILED_VALID);
719 }
720}
721
724BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_init, SnapshotTestSetup)
725{
727 Chainstate& bg_chainstate = chainman.ActiveChainstate();
728
729 this->SetupSnapshot();
730
731 fs::path snapshot_chainstate_dir = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
732 BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
733 BOOST_CHECK_EQUAL(snapshot_chainstate_dir, gArgs.GetDataDirNet() / "chainstate_snapshot");
734
736 const uint256 snapshot_tip_hash = WITH_LOCK(chainman.GetMutex(),
737 return chainman.ActiveTip()->GetBlockHash());
738
739 BOOST_CHECK_EQUAL(WITH_LOCK(chainman.GetMutex(), return chainman.m_chainstates.size()), 2);
740
741 // "Rewind" the background chainstate so that its tip is not at the
742 // base block of the snapshot - this is so after simulating a node restart,
743 // it will initialize instead of attempting to complete validation.
744 //
745 // Note that this is not a realistic use of DisconnectTip().
747 BlockValidationState unused_state;
748 {
749 LOCK2(::cs_main, bg_chainstate.MempoolMutex());
750 BOOST_CHECK(bg_chainstate.DisconnectTip(unused_state, &unused_pool));
751 unused_pool.clear(); // to avoid queuedTx assertion errors on teardown
752 }
753 BOOST_CHECK_EQUAL(bg_chainstate.m_chain.Height(), 109);
754
755 // Test that simulating a shutdown (resetting ChainstateManager) and then performing
756 // chainstate reinitializing successfully reloads both chainstates.
757 ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
758
759 BOOST_TEST_MESSAGE("Performing Load/Verify/Activate of chainstate");
760
761 // This call reinitializes the chainstates.
762 this->LoadVerifyActivateChainstate();
763
764 {
765 LOCK(chainman_restarted.GetMutex());
766 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 2);
767 // Background chainstate has height of 109 not 110 here due to a quirk
768 // of the LoadVerifyActivate only calling ActivateBestChain on one
769 // chainstate. The height would be 110 after a real restart, but it's
770 // fine for this test which is focused on the snapshot chainstate.
771 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[0]->m_chain.Height(), 109);
772 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[1]->m_chain.Height(), 210);
773
775 BOOST_CHECK(chainman_restarted.CurrentChainstate().m_assumeutxo == Assumeutxo::UNVALIDATED);
776
777 BOOST_CHECK_EQUAL(chainman_restarted.ActiveTip()->GetBlockHash(), snapshot_tip_hash);
778 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
779 BOOST_CHECK_EQUAL(chainman_restarted.HistoricalChainstate()->m_chain.Height(), 109);
780 }
781
782 BOOST_TEST_MESSAGE(
783 "Ensure we can mine blocks on top of the initialized snapshot chainstate");
784 mineBlocks(10);
785 {
786 LOCK(chainman_restarted.GetMutex());
787 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
788
789 // Background chainstate should be unaware of new blocks on the snapshot
790 // chainstate, but the block disconnected above is now reattached.
791 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 2);
792 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[0]->m_chain.Height(), 110);
793 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[1]->m_chain.Height(), 220);
794 BOOST_CHECK_EQUAL(chainman_restarted.HistoricalChainstate(), nullptr);
795 }
796}
797
798BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_completion, SnapshotTestSetup)
799{
800 this->SetupSnapshot();
801
803 Chainstate& active_cs = chainman.ActiveChainstate();
804 Chainstate& validated_cs{*Assert(WITH_LOCK(cs_main, return chainman.HistoricalChainstate()))};
805 auto tip_cache_before_complete = active_cs.m_coinstip_cache_size_bytes;
806 auto db_cache_before_complete = active_cs.m_coinsdb_cache_size_bytes;
807
809 m_node.notifications->m_shutdown_on_fatal_error = false;
810
811 fs::path snapshot_chainstate_dir = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
812 BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
813 BOOST_CHECK_EQUAL(snapshot_chainstate_dir, gArgs.GetDataDirNet() / "chainstate_snapshot");
814
816 const uint256 snapshot_tip_hash = WITH_LOCK(chainman.GetMutex(),
817 return chainman.ActiveTip()->GetBlockHash());
818
819 res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validated_cs, active_cs));
821
822 BOOST_CHECK(WITH_LOCK(::cs_main, return chainman.CurrentChainstate().m_assumeutxo == Assumeutxo::VALIDATED));
824 BOOST_CHECK_EQUAL(WITH_LOCK(chainman.GetMutex(), return chainman.HistoricalChainstate()), nullptr);
825
826 // Cache should have been rebalanced and reallocated to the "only" remaining
827 // chainstate.
828 BOOST_CHECK(active_cs.m_coinstip_cache_size_bytes > tip_cache_before_complete);
829 BOOST_CHECK(active_cs.m_coinsdb_cache_size_bytes > db_cache_before_complete);
830
831 // Trying completion again should return false.
832 res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validated_cs, active_cs));
834
835 // The invalid snapshot path should not have been used.
836 fs::path snapshot_invalid_dir = gArgs.GetDataDirNet() / "chainstate_snapshot_INVALID";
837 BOOST_CHECK(!fs::exists(snapshot_invalid_dir));
838 // chainstate_snapshot should still exist.
839 BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
840
841 // Test that simulating a shutdown (resetting ChainstateManager) and then performing
842 // chainstate reinitializing successfully cleans up the background-validation
843 // chainstate data, and we end up with a single chainstate that is at tip.
844 ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
845
846 BOOST_TEST_MESSAGE("Performing Load/Verify/Activate of chainstate");
847
848 // This call reinitializes the chainstates, and should clean up the now unnecessary
849 // background-validation leveldb contents.
850 this->LoadVerifyActivateChainstate();
851
852 BOOST_CHECK(!fs::exists(snapshot_invalid_dir));
853 // chainstate_snapshot should now *not* exist.
854 BOOST_CHECK(!fs::exists(snapshot_chainstate_dir));
855
856 const Chainstate& active_cs2 = chainman_restarted.ActiveChainstate();
857
858 {
859 LOCK(chainman_restarted.GetMutex());
860 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 1);
862 BOOST_CHECK(active_cs2.m_coinstip_cache_size_bytes > tip_cache_before_complete);
863 BOOST_CHECK(active_cs2.m_coinsdb_cache_size_bytes > db_cache_before_complete);
864
865 BOOST_CHECK_EQUAL(chainman_restarted.ActiveTip()->GetBlockHash(), snapshot_tip_hash);
866 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
867 }
868
869 BOOST_TEST_MESSAGE(
870 "Ensure we can mine blocks on top of the \"new\" IBD chainstate");
871 mineBlocks(10);
872 {
873 LOCK(chainman_restarted.GetMutex());
874 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
875 }
876}
877
878BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_completion_hash_mismatch, SnapshotTestSetup)
879{
880 auto chainstates = this->SetupSnapshot();
881 Chainstate& validation_chainstate = *std::get<0>(chainstates);
882 Chainstate& unvalidated_cs = *std::get<1>(chainstates);
885 m_node.notifications->m_shutdown_on_fatal_error = false;
886
887 // Test tampering with the IBD UTXO set with an extra coin to ensure it causes
888 // snapshot completion to fail.
890 return validation_chainstate.CoinsTip());
891 Coin badcoin;
892 badcoin.out.nValue = m_rng.rand32();
893 badcoin.nHeight = 1;
894 badcoin.out.scriptPubKey.assign(m_rng.randbits(6), 0);
895 Txid txid = Txid::FromUint256(m_rng.rand256());
896 ibd_coins.AddCoin(COutPoint(txid, 0), std::move(badcoin), false);
897
898 fs::path snapshot_chainstate_dir = gArgs.GetDataDirNet() / "chainstate_snapshot";
899 BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
900
901 {
902 ASSERT_DEBUG_LOG("failed to validate the -assumeutxo snapshot state");
903 res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validation_chainstate, unvalidated_cs));
905 }
906
907 {
908 LOCK(chainman.GetMutex());
909 BOOST_CHECK_EQUAL(chainman.m_chainstates.size(), 2);
910 BOOST_CHECK(chainman.m_chainstates[0]->m_assumeutxo == Assumeutxo::VALIDATED);
911 BOOST_CHECK(!chainman.m_chainstates[0]->SnapshotBase());
912 BOOST_CHECK(chainman.m_chainstates[1]->m_assumeutxo == Assumeutxo::INVALID);
913 BOOST_CHECK(chainman.m_chainstates[1]->SnapshotBase());
914 }
915
916 fs::path snapshot_invalid_dir = gArgs.GetDataDirNet() / "chainstate_snapshot_INVALID";
917 BOOST_CHECK(fs::exists(snapshot_invalid_dir));
918
919 // Test that simulating a shutdown (resetting ChainstateManager) and then performing
920 // chainstate reinitializing successfully loads only the fully-validated
921 // chainstate data, and we end up with a single chainstate that is at tip.
922 ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
923
924 BOOST_TEST_MESSAGE("Performing Load/Verify/Activate of chainstate");
925
926 // This call reinitializes the chainstates, and should clean up the now unnecessary
927 // background-validation leveldb contents.
928 this->LoadVerifyActivateChainstate();
929
930 BOOST_CHECK(fs::exists(snapshot_invalid_dir));
931 BOOST_CHECK(!fs::exists(snapshot_chainstate_dir));
932
933 {
935 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 1);
937 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
938 }
939
940 BOOST_TEST_MESSAGE(
941 "Ensure we can mine blocks on top of the \"new\" IBD chainstate");
942 mineBlocks(10);
943 {
945 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
946 }
947}
948
950template <typename Options>
952 const std::vector<const char*>& args)
953{
954 const auto argv{Cat({"ignore"}, args)};
955 std::string error{};
956 if (!args_man.ParseParameters(argv.size(), argv.data(), error)) {
957 return util::Error{Untranslated("ParseParameters failed with error: " + error)};
958 }
959 const auto result{node::ApplyArgsManOptions(args_man, opts)};
960 if (!result) return util::Error{util::ErrorString(result)};
961 return opts;
962}
963
965{
967 auto get_opts = [&](const std::vector<const char*>& args) {
968 static kernel::Notifications notifications{};
969 static const ChainstateManager::Options options{
971 .datadir = {},
972 .notifications = notifications};
973 return SetOptsFromArgs(*this->m_node.args, options, args);
974 };
976 auto get_valid_opts = [&](const std::vector<const char*>& args) {
977 const auto result{get_opts(args)};
978 BOOST_REQUIRE_MESSAGE(result, util::ErrorString(result).original);
979 return *result;
980 };
981
982 // test -assumevalid
983 BOOST_CHECK(!get_valid_opts({}).assumed_valid_block);
984 BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid="}).assumed_valid_block, uint256::ZERO);
985 BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid=0"}).assumed_valid_block, uint256::ZERO);
986 BOOST_CHECK_EQUAL(get_valid_opts({"-noassumevalid"}).assumed_valid_block, uint256::ZERO);
987 BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid=0x12"}).assumed_valid_block, uint256{0x12});
988
989 std::string assume_valid{"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"};
990 BOOST_CHECK_EQUAL(get_valid_opts({("-assumevalid=" + assume_valid).c_str()}).assumed_valid_block, uint256::FromHex(assume_valid));
991
992 BOOST_CHECK(!get_opts({"-assumevalid=xyz"})); // invalid hex characters
993 BOOST_CHECK(!get_opts({"-assumevalid=01234567890123456789012345678901234567890123456789012345678901234"})); // > 64 hex chars
994
995 // test -minimumchainwork
996 BOOST_CHECK(!get_valid_opts({}).minimum_chain_work);
997 BOOST_CHECK_EQUAL(get_valid_opts({"-minimumchainwork=0"}).minimum_chain_work, arith_uint256());
998 BOOST_CHECK_EQUAL(get_valid_opts({"-nominimumchainwork"}).minimum_chain_work, arith_uint256());
999 BOOST_CHECK_EQUAL(get_valid_opts({"-minimumchainwork=0x1234"}).minimum_chain_work, arith_uint256{0x1234});
1000
1001 std::string minimum_chainwork{"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"};
1002 BOOST_CHECK_EQUAL(get_valid_opts({("-minimumchainwork=" + minimum_chainwork).c_str()}).minimum_chain_work, UintToArith256(uint256::FromHex(minimum_chainwork).value()));
1003
1004 BOOST_CHECK(!get_opts({"-minimumchainwork=xyz"})); // invalid hex characters
1005 BOOST_CHECK(!get_opts({"-minimumchainwork=01234567890123456789012345678901234567890123456789012345678901234"})); // > 64 hex chars
1006
1007 BOOST_CHECK_EQUAL(get_valid_opts({}).prevoutfetch_threads_num, DEFAULT_PREVOUTFETCH_THREADS);
1008 BOOST_CHECK_EQUAL(get_valid_opts({"-prevoutfetchthreads=0"}).prevoutfetch_threads_num, 0);
1009 BOOST_CHECK_EQUAL(get_valid_opts({"-prevoutfetchthreads=3"}).prevoutfetch_threads_num, 3);
1010 BOOST_CHECK_EQUAL(get_valid_opts({"-prevoutfetchthreads=100"}).prevoutfetch_threads_num, MAX_PREVOUTFETCH_THREADS);
1011 BOOST_CHECK(!get_opts({"-prevoutfetchthreads=-1"}));
1012}
1013
ArgsManager gArgs
Definition: args.cpp:38
arith_uint256 UintToArith256(const uint256 &a)
static void pool cs
node::NodeContext m_node
Definition: bitcoin-gui.cpp:48
ArgsManager & args
Definition: bitcoind.cpp:280
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous.
Definition: chain.h:51
@ BLOCK_FAILED_CHILD
Unused flag that was previously set when descending from failed block.
Definition: chain.h:80
@ BLOCK_FAILED_VALID
stage after last reached validness failed
Definition: chain.h:79
const CChainParams & Params()
Return the currently selected parameters.
constexpr int32_t DEFAULT_PREVOUTFETCH_THREADS
#define Assert(val)
Identity function.
Definition: check.h:116
bool ParseParameters(int argc, const char *const argv[], std::string &error) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Definition: args.cpp:175
fs::path GetDataDirNet() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get data directory path with appended network identifier.
Definition: args.cpp:328
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:395
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:100
uint64_t m_chain_tx_count
(memory only) Number of transactions in the chain up to and including this block.
Definition: chain.h:129
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:118
uint32_t nTime
Definition: chain.h:142
uint256 GetBlockHash() const
Definition: chain.h:198
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:396
void SetTip(CBlockIndex &block)
Set/initialize a chain with a given tip.
Definition: chain.cpp:16
int Height() const
Return the maximal height in the chain.
Definition: chain.h:425
std::optional< AssumeutxoData > AssumeutxoForHeight(int height) const
Definition: chainparams.h:120
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:437
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:80
unsigned int GetCacheSize() const
Size of the cache (in number of transaction outputs)
Definition: coins.cpp:318
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:179
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:30
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
CScript scriptPubKey
Definition: transaction.h:144
CAmount nValue
Definition: transaction.h:143
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:550
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:630
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition: validation.h:729
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:694
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition: validation.h:726
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(void SetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(voi ResetBlockFailureFlags)(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as precious and reorganize.
Definition: validation.h:813
const std::optional< uint256 > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
Definition: validation.h:642
bool DisconnectTip(BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain's tip.
std::set< CBlockIndex *, node::CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries that have as much work as our current tip or more,...
Definition: validation.h:691
RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Indirection necessary to make lock annotations work with an optional mempool.
Definition: validation.h:852
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Definition: validation.h:950
Chainstate * HistoricalChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return historical chainstate targeting a specific block, if any.
Definition: validation.h:1141
size_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
Definition: validation.h:1092
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1042
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1180
Chainstate & ActiveChainstate() const
Alternatives to CurrentChainstate() used by older code to query latest chainstate information without...
SnapshotCompletionResult MaybeValidateSnapshot(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & CurrentChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Try to validate an assumeutxo snapshot by using a validated historical chainstate targeted at the sna...
Definition: validation.h:1132
size_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:1096
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1179
const Options m_options
Definition: validation.h:1045
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1178
void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1076
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1048
A UTXO entry.
Definition: coins.h:46
CTxOut out
unspent transaction output
Definition: coins.h:49
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:55
DisconnectedBlockTransactions.
256-bit unsigned big integer.
A base class defining functions for notifying about certain kernel events.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:194
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:38
uint256 m_base_blockhash
The hash of the block that reflects the tip of the chain for the UTXO set contained in this snapshot.
Definition: utxo_snapshot.h:45
uint64_t m_coins_count
The number of coins in the UTXO set contained in this snapshot.
Definition: utxo_snapshot.h:50
void assign(size_type n, const T &val)
Definition: prevector.h:176
static transaction_identifier FromUint256(const uint256 &id)
256-bit opaque blob.
Definition: uint256.h:196
static const uint256 ONE
Definition: uint256.h:205
static const uint256 ZERO
Definition: uint256.h:204
static std::optional< uint256 > FromHex(std::string_view str)
Definition: uint256.h:198
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
constexpr unsigned int MAX_DISCONNECTED_TX_POOL_BYTES
Maximum bytes for transactions to store for processing during reorg.
static bool exists(const path &p)
Definition: fs.h:94
BOOST_CHECK_EQUAL(headers.FindFirst("key"), "value")
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
std::optional< fs::path > FindAssumeutxoChainstateDir(const fs::path &data_dir)
Return a path to the snapshot-based chainstate dir, if one exists.
std::optional< uint256 > ReadSnapshotBaseBlockhash(fs::path chaindir)
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:93
#define BOOST_CHECK(expr)
Definition: object.cpp:16
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:417
@ OP_CHECKSIG
Definition: script.h:191
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:68
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:333
Basic testing setup.
Definition: setup_common.h:58
Testing setup that performs all steps up until right before ChainstateManager gets initialized.
Definition: setup_common.h:100
Application-specific storage settings.
Definition: dbwrapper.h:43
fs::path path
Location in the filesystem where leveldb data will be stored.
Definition: dbwrapper.h:45
std::tuple< Chainstate *, Chainstate * > SetupSnapshot()
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:143
Testing setup that configures a complete environment.
Definition: setup_common.h:119
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
std::unique_ptr< ValidationSignals > validation_signals
Issues calls about blocks and transactions.
Definition: context.h:89
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:69
std::unique_ptr< BlockTemplateManager > block_template_manager
Must be destroyed before its dependencies (holds references to them).
Definition: context.h:87
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:74
std::unique_ptr< node::Warnings > warnings
Manages all the node warnings.
Definition: context.h:92
std::function< bool()> shutdown_request
Function to request a shutdown.
Definition: context.h:64
std::unique_ptr< KernelNotifications > notifications
Issues blocking calls about sync status, errors and warnings.
Definition: context.h:85
util::SignalInterrupt * shutdown_signal
Interrupt object used to track whether node shutdown was requested.
Definition: context.h:66
ArgsManager * args
Definition: context.h:76
std::atomic< int > exit_status
Definition: context.h:90
#define LOCK2(cs1, cs2)
Definition: sync.h:269
#define LOCK(cs)
Definition: sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:299
static bool CreateAndActivateUTXOSnapshot(TestingSetup *fixture, F malleation=NoMalleation, bool reset_chainstate=false, bool in_memory_chainstate=false)
Create and activate a UTXO snapshot, optionally providing a function to malleate the snapshot.
Definition: chainstate.h:34
#define ASSERT_DEBUG_LOG(message)
Definition: logging.h:42
consteval auto _(util::TranslatedLiteral str)
Definition: translation.h:79
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:82
assert(!tx.IsCoinBase())
SnapshotCompletionResult
Definition: validation.h:912
@ VALIDATED
Every block in the chain has been validated.
@ UNVALIDATED
Blocks after an assumeutxo snapshot have been validated but the snapshot itself has not been validate...
@ INVALID
The assumeutxo snapshot failed validation.
constexpr int32_t MAX_PREVOUTFETCH_THREADS
Maximum number of dedicated threads allowed for prefetching block input prevouts.
Definition: validation.h:93
BOOST_FIXTURE_TEST_CASE(chainstatemanager, TestChain100Setup)
Basic tests for ChainstateManager.
util::Result< Options > SetOptsFromArgs(ArgsManager &args_man, Options opts, const std::vector< const char * > &args)
Helper function to parse args into args_man and return the result of applying them to opts.
V Cat(V v1, V &&v2)
Concatenate two vectors, moving elements.
Definition: vector.h:34