Bitcoin Core 31.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>
10#include <node/utxo_snapshot.h>
11#include <random.h>
12#include <rpc/blockchain.h>
13#include <sync.h>
15#include <test/util/common.h>
16#include <test/util/logging.h>
17#include <test/util/random.h>
20#include <uint256.h>
21#include <util/byte_units.h>
22#include <util/result.h>
23#include <util/vector.h>
24#include <validation.h>
25#include <validationinterface.h>
26
27#include <tinyformat.h>
28
29#include <vector>
30
31#include <boost/test/unit_test.hpp>
32
36
37BOOST_FIXTURE_TEST_SUITE(validation_chainstatemanager_tests, TestingSetup)
38
39
43{
45
47
48 // Create a legacy (IBD) chainstate.
49 //
50 Chainstate& c1 = manager.ActiveChainstate();
51
53 {
54 LOCK(manager.GetMutex());
55 BOOST_CHECK_EQUAL(manager.m_chainstates.size(), 1);
56 BOOST_CHECK_EQUAL(manager.m_chainstates[0].get(), &c1);
57 }
58
59 auto& active_chain = WITH_LOCK(manager.GetMutex(), return manager.ActiveChain());
60 BOOST_CHECK_EQUAL(&active_chain, &c1.m_chain);
61
62 // Get to a valid assumeutxo tip (per chainparams);
63 mineBlocks(10);
64 BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 110);
65 auto active_tip = WITH_LOCK(manager.GetMutex(), return manager.ActiveTip());
66 auto exp_tip = c1.m_chain.Tip();
67 BOOST_CHECK_EQUAL(active_tip, exp_tip);
68
70
71 // Create a snapshot-based chainstate.
72 //
73 const uint256 snapshot_blockhash = active_tip->GetBlockHash();
74 Chainstate& c2{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, snapshot_blockhash)))};
75 c2.InitCoinsDB(
76 /*cache_size_bytes=*/8_MiB, /*in_memory=*/true, /*should_wipe=*/false);
77 {
79 c2.InitCoinsCache(8_MiB);
80 c2.CoinsTip().SetBestBlock(active_tip->GetBlockHash());
81 for (const auto& cs : manager.m_chainstates) {
82 cs->ClearBlockIndexCandidates();
83 }
84 c2.LoadChainTip();
85 for (const auto& cs : manager.m_chainstates) {
86 cs->PopulateBlockIndexCandidates();
87 }
88 }
90 BOOST_CHECK(c2.ActivateBestChain(_, nullptr));
91
94 BOOST_CHECK_EQUAL(&c2, &manager.ActiveChainstate());
95 BOOST_CHECK(&c1 != &manager.ActiveChainstate());
96 {
97 LOCK(manager.GetMutex());
98 BOOST_CHECK_EQUAL(manager.m_chainstates.size(), 2);
99 BOOST_CHECK_EQUAL(manager.m_chainstates[0].get(), &c1);
100 BOOST_CHECK_EQUAL(manager.m_chainstates[1].get(), &c2);
101 }
102
103 auto& active_chain2 = WITH_LOCK(manager.GetMutex(), return manager.ActiveChain());
104 BOOST_CHECK_EQUAL(&active_chain2, &c2.m_chain);
105
106 BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 110);
107 mineBlocks(1);
108 BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 111);
109 BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return c1.m_chain.Height()), 110);
110
111 auto active_tip2 = WITH_LOCK(manager.GetMutex(), return manager.ActiveTip());
112 BOOST_CHECK_EQUAL(active_tip, active_tip2->pprev);
113 BOOST_CHECK_EQUAL(active_tip, c1.m_chain.Tip());
114 BOOST_CHECK_EQUAL(active_tip2, c2.m_chain.Tip());
115
116 // Let scheduler events finish running to avoid accessing memory that is going to be unloaded
117 m_node.validation_signals->SyncWithValidationInterfaceQueue();
118}
119
120BOOST_FIXTURE_TEST_CASE(chainstatemanager_delete_chainstate_no_mempool, ChainTestingSetup)
121{
122 auto& manager{*Assert(m_node.chainman)};
123 auto& validated{WITH_LOCK(::cs_main, return manager.InitializeChainstate(/*mempool=*/nullptr))};
124 auto& snapshot{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, uint256::ONE)))};
125 WITH_LOCK(::cs_main, validated.SetTargetBlock(nullptr));
126 BOOST_CHECK(WITH_LOCK(::cs_main, return manager.DeleteChainstate(snapshot))); // Accept Kernel's null mempool
127}
128
130BOOST_FIXTURE_TEST_CASE(chainstatemanager_rebalance_caches, TestChain100Setup)
131{
133
134 size_t max_cache = 10000;
135 manager.m_total_coinsdb_cache = max_cache;
136 manager.m_total_coinstip_cache = max_cache;
137
138 std::vector<Chainstate*> chainstates;
139
140 // Create a legacy (IBD) chainstate.
141 //
142 Chainstate& c1 = manager.ActiveChainstate();
143 chainstates.push_back(&c1);
144 {
146 c1.InitCoinsCache(8_MiB);
147 manager.MaybeRebalanceCaches();
148 }
149
152
153 // Create a snapshot-based chainstate.
154 //
155 CBlockIndex* snapshot_base{WITH_LOCK(manager.GetMutex(), return manager.ActiveChain()[manager.ActiveChain().Height() / 2])};
156 Chainstate& c2{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, *snapshot_base->phashBlock)))};
157 chainstates.push_back(&c2);
158 c2.InitCoinsDB(
159 /*cache_size_bytes=*/8_MiB, /*in_memory=*/true, /*should_wipe=*/false);
160
161 // Reset IBD state so IsInitialBlockDownload() returns true and causes
162 // MaybeRebalanceCaches() to prioritize the snapshot chainstate, giving it
163 // more cache space than the snapshot chainstate. Calling ResetIbd() is
164 // necessary because m_cached_is_ibd is already latched to false before
165 // the test starts due to the test setup. After ResetIbd() is called,
166 // IsInitialBlockDownload() will return true because at this point the active
167 // chainstate has a null chain tip.
168 static_cast<TestChainstateManager&>(manager).ResetIbd();
169
170 {
172 c2.InitCoinsCache(8_MiB);
173 manager.MaybeRebalanceCaches();
174 }
175
176 BOOST_CHECK_CLOSE(double(c1.m_coinstip_cache_size_bytes), max_cache * 0.05, 1);
177 BOOST_CHECK_CLOSE(double(c1.m_coinsdb_cache_size_bytes), max_cache * 0.05, 1);
178 BOOST_CHECK_CLOSE(double(c2.m_coinstip_cache_size_bytes), max_cache * 0.95, 1);
179 BOOST_CHECK_CLOSE(double(c2.m_coinsdb_cache_size_bytes), max_cache * 0.95, 1);
180}
181
182BOOST_FIXTURE_TEST_CASE(chainstatemanager_ibd_exit_after_loading_blocks, ChainTestingSetup)
183{
184 CBlockIndex tip;
186 auto apply{[&](bool cached_is_ibd, bool loading_blocks, bool tip_exists, bool enough_work, bool tip_recent) {
188 chainman.ResetChainstates();
189 chainman.InitializeChainstate(m_node.mempool.get());
190
191 const auto recent_time{Now<NodeSeconds>() - chainman.m_options.max_tip_age};
192
193 chainman.m_cached_is_ibd.store(cached_is_ibd, std::memory_order_relaxed);
194 chainman.m_blockman.m_importing = loading_blocks;
195 if (tip_exists) {
196 tip.nChainWork = chainman.MinimumChainWork() - (enough_work ? 0 : 1);
197 tip.nTime = (recent_time - (tip_recent ? 0h : 100h)).time_since_epoch().count();
198 chainman.ActiveChain().SetTip(tip);
199 } else {
200 assert(!chainman.ActiveChain().Tip());
201 }
202 chainman.UpdateIBDStatus();
203 }};
204
205 for (const bool cached_is_ibd : {false, true}) {
206 for (const bool loading_blocks : {false, true}) {
207 for (const bool tip_exists : {false, true}) {
208 for (const bool enough_work : {false, true}) {
209 for (const bool tip_recent : {false, true}) {
210 apply(cached_is_ibd, loading_blocks, tip_exists, enough_work, tip_recent);
211 const bool expected_ibd = cached_is_ibd && (loading_blocks || !tip_exists || !enough_work || !tip_recent);
212 BOOST_CHECK_EQUAL(chainman.IsInitialBlockDownload(), expected_ibd);
213 }
214 }
215 }
216 }
217 }
218}
219
221 // Run with coinsdb on the filesystem to support, e.g., moving invalidated
222 // chainstate dirs to "*_invalid".
223 //
224 // Note that this means the tests run considerably slower than in-memory DB
225 // tests, but we can't otherwise test this functionality since it relies on
226 // destructive filesystem operations.
228 {},
229 {
230 .coins_db_in_memory = false,
231 .block_tree_db_in_memory = false,
232 },
233 }
234 {
235 }
236
237 std::tuple<Chainstate*, Chainstate*> SetupSnapshot()
238 {
240
241 {
245 }
246
247 size_t initial_size;
248 size_t initial_total_coins{100};
249
250 // Make some initial assertions about the contents of the chainstate.
251 {
253 CCoinsViewCache& ibd_coinscache = chainman.ActiveChainstate().CoinsTip();
254 initial_size = ibd_coinscache.GetCacheSize();
255 size_t total_coins{0};
256
257 for (CTransactionRef& txn : m_coinbase_txns) {
258 COutPoint op{txn->GetHash(), 0};
259 BOOST_CHECK(ibd_coinscache.HaveCoin(op));
260 total_coins++;
261 }
262
263 BOOST_CHECK_EQUAL(total_coins, initial_total_coins);
264 BOOST_CHECK_EQUAL(initial_size, initial_total_coins);
265 }
266
267 Chainstate& validation_chainstate = chainman.ActiveChainstate();
268
269 // Snapshot should refuse to load at this height.
270 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(this));
272
273 // Mine 10 more blocks, putting at us height 110 where a valid assumeutxo value can
274 // be found.
275 constexpr int snapshot_height = 110;
276 mineBlocks(10);
277 initial_size += 10;
278 initial_total_coins += 10;
279
280 // Should not load malleated snapshots
281 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
282 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
283 // A UTXO is missing but count is correct
284 metadata.m_coins_count -= 1;
285
286 Txid txid;
287 auto_infile >> txid;
288 // coins size
289 (void)ReadCompactSize(auto_infile);
290 // vout index
291 (void)ReadCompactSize(auto_infile);
292 Coin coin;
293 auto_infile >> coin;
294 }));
295
297
298 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
299 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
300 // Coins count is larger than coins in file
301 metadata.m_coins_count += 1;
302 }));
303 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
304 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
305 // Coins count is smaller than coins in file
306 metadata.m_coins_count -= 1;
307 }));
308 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
309 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
310 // Wrong hash
312 }));
313 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
314 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
315 // Wrong hash
317 }));
318
319 BOOST_REQUIRE(CreateAndActivateUTXOSnapshot(this));
321
322 // Ensure our active chain is the snapshot chainstate.
324
325 Chainstate& snapshot_chainstate = chainman.ActiveChainstate();
326
327 {
329
330 fs::path found = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
331
332 // Note: WriteSnapshotBaseBlockhash() is implicitly tested above.
336 }
337
338 const auto& au_data = ::Params().AssumeutxoForHeight(snapshot_height);
339 const CBlockIndex* tip = WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip());
340
341 BOOST_CHECK_EQUAL(tip->m_chain_tx_count, au_data->m_chain_tx_count);
342
343 // To be checked against later when we try loading a subsequent snapshot.
344 uint256 loaded_snapshot_blockhash{*Assert(WITH_LOCK(chainman.GetMutex(), return chainman.CurrentChainstate().m_from_snapshot_blockhash))};
345
346 // Make some assertions about the both chainstates. These checks ensure the
347 // legacy chainstate hasn't changed and that the newly created chainstate
348 // reflects the expected content.
349 {
351 int chains_tested{0};
352
353 for (const auto& chainstate : chainman.m_chainstates) {
354 BOOST_TEST_MESSAGE("Checking coins in " << chainstate->ToString());
355 CCoinsViewCache& coinscache = chainstate->CoinsTip();
356
357 // Both caches will be empty initially.
358 BOOST_CHECK_EQUAL((unsigned int)0, coinscache.GetCacheSize());
359
360 size_t total_coins{0};
361
362 for (CTransactionRef& txn : m_coinbase_txns) {
363 COutPoint op{txn->GetHash(), 0};
364 BOOST_CHECK(coinscache.HaveCoin(op));
365 total_coins++;
366 }
367
368 BOOST_CHECK_EQUAL(initial_size , coinscache.GetCacheSize());
369 BOOST_CHECK_EQUAL(total_coins, initial_total_coins);
370 chains_tested++;
371 }
372
373 BOOST_CHECK_EQUAL(chains_tested, 2);
374 }
375
376 // Mine some new blocks on top of the activated snapshot chainstate.
377 constexpr size_t new_coins{100};
378 mineBlocks(new_coins); // Defined in TestChain100Setup.
379
380 {
382 size_t coins_in_active{0};
383 size_t coins_in_background{0};
384 size_t coins_missing_from_background{0};
385
386 for (const auto& chainstate : chainman.m_chainstates) {
387 BOOST_TEST_MESSAGE("Checking coins in " << chainstate->ToString());
388 CCoinsViewCache& coinscache = chainstate->CoinsTip();
389 bool is_background = chainstate.get() != &chainman.ActiveChainstate();
390
391 for (CTransactionRef& txn : m_coinbase_txns) {
392 COutPoint op{txn->GetHash(), 0};
393 if (coinscache.HaveCoin(op)) {
394 (is_background ? coins_in_background : coins_in_active)++;
395 } else if (is_background) {
396 coins_missing_from_background++;
397 }
398 }
399 }
400
401 BOOST_CHECK_EQUAL(coins_in_active, initial_total_coins + new_coins);
402 BOOST_CHECK_EQUAL(coins_in_background, initial_total_coins);
403 BOOST_CHECK_EQUAL(coins_missing_from_background, new_coins);
404 }
405
406 // Snapshot should refuse to load after one has already loaded.
407 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(this));
408
409 // Snapshot blockhash should be unchanged.
412 loaded_snapshot_blockhash);
413 return std::make_tuple(&validation_chainstate, &snapshot_chainstate);
414 }
415
416 // Simulate a restart of the node by flushing all state to disk, clearing the
417 // existing ChainstateManager, and unloading the block index.
418 //
419 // @returns a reference to the "restarted" ChainstateManager
421 {
423
424 BOOST_TEST_MESSAGE("Simulating node restart");
425 {
426 LOCK(chainman.GetMutex());
427 for (const auto& cs : chainman.m_chainstates) {
428 if (cs->CanFlushToDisk()) cs->ForceFlushStateToDisk();
429 }
430 }
431 {
432 // Process all callbacks referring to the old manager before wiping it.
433 m_node.validation_signals->SyncWithValidationInterfaceQueue();
435 chainman.ResetChainstates();
436 BOOST_CHECK_EQUAL(chainman.m_chainstates.size(), 0);
437 m_node.notifications = std::make_unique<KernelNotifications>(Assert(m_node.shutdown_request), m_node.exit_status, *Assert(m_node.warnings));
438 const ChainstateManager::Options chainman_opts{
440 .datadir = chainman.m_options.datadir,
441 .notifications = *m_node.notifications,
442 .signals = m_node.validation_signals.get(),
443 };
444 const BlockManager::Options blockman_opts{
445 .chainparams = chainman_opts.chainparams,
446 .blocks_dir = m_args.GetBlocksDirPath(),
447 .notifications = chainman_opts.notifications,
448 .block_tree_db_params = DBParams{
449 .path = chainman.m_options.datadir / "blocks" / "index",
450 .cache_bytes = m_kernel_cache_sizes.block_tree_db,
451 .memory_only = m_block_tree_db_in_memory,
452 },
453 };
454 // For robustness, ensure the old manager is destroyed before creating a
455 // new one.
456 m_node.chainman.reset();
457 m_node.chainman = std::make_unique<ChainstateManager>(*Assert(m_node.shutdown_signal), chainman_opts, blockman_opts);
458 }
459 return *Assert(m_node.chainman);
460 }
461};
462
464BOOST_FIXTURE_TEST_CASE(chainstatemanager_activate_snapshot, SnapshotTestSetup)
465{
466 this->SetupSnapshot();
467}
468
479BOOST_FIXTURE_TEST_CASE(chainstatemanager_loadblockindex, TestChain100Setup)
480{
482 Chainstate& cs1 = chainman.ActiveChainstate();
483
484 int num_indexes{0};
485 // Blocks in range [assumed_valid_start_idx, last_assumed_valid_idx) will be
486 // marked as assumed-valid and not having data.
487 const int expected_assumed_valid{20};
488 const int last_assumed_valid_idx{111};
489 const int assumed_valid_start_idx = last_assumed_valid_idx - expected_assumed_valid;
490
491 // Mine to height 120, past the hardcoded regtest assumeutxo snapshot at
492 // height 110
493 mineBlocks(20);
494
495 CBlockIndex* validated_tip{nullptr};
496 CBlockIndex* assumed_base{nullptr};
497 CBlockIndex* assumed_tip{WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip())};
498 BOOST_CHECK_EQUAL(assumed_tip->nHeight, 120);
499
500 auto reload_all_block_indexes = [&]() {
501 LOCK(chainman.GetMutex());
502 // For completeness, we also reset the block sequence counters to
503 // ensure that no state which affects the ranking of tip-candidates is
504 // retained (even though this isn't strictly necessary).
506 for (const auto& cs : chainman.m_chainstates) {
507 cs->ClearBlockIndexCandidates();
508 BOOST_CHECK(cs->setBlockIndexCandidates.empty());
509 }
510 chainman.LoadBlockIndex();
511 for (const auto& cs : chainman.m_chainstates) {
512 cs->PopulateBlockIndexCandidates();
513 }
514 };
515
516 // Ensure that without any assumed-valid BlockIndex entries, only the current tip is
517 // considered as a candidate.
518 reload_all_block_indexes();
520
521 // Reset some region of the chain's nStatus, removing the HAVE_DATA flag.
522 for (int i = 0; i <= cs1.m_chain.Height(); ++i) {
524 auto index = cs1.m_chain[i];
525
526 // Blocks with heights in range [91, 110] are marked as missing data.
527 if (i < last_assumed_valid_idx && i >= assumed_valid_start_idx) {
528 index->nStatus = BlockStatus::BLOCK_VALID_TREE;
529 index->nTx = 0;
530 index->m_chain_tx_count = 0;
531 }
532
533 ++num_indexes;
534
535 // Note the last fully-validated block as the expected validated tip.
536 if (i == (assumed_valid_start_idx - 1)) {
537 validated_tip = index;
538 }
539 // Note the last assumed valid block as the snapshot base
540 if (i == last_assumed_valid_idx - 1) {
541 assumed_base = index;
542 }
543 }
544
545 // Note: cs2's tip is not set when ActivateExistingSnapshot is called.
546 Chainstate& cs2{WITH_LOCK(::cs_main, return chainman.AddChainstate(std::make_unique<Chainstate>(nullptr, chainman.m_blockman, chainman, *assumed_base->phashBlock)))};
547
548 // Set tip of the fully validated chain to be the validated tip
549 cs1.m_chain.SetTip(*validated_tip);
550
551 // Set tip of the assume-valid-based chain to the assume-valid block
552 cs2.m_chain.SetTip(*assumed_base);
553
554 // Sanity check test variables.
555 BOOST_CHECK_EQUAL(num_indexes, 121); // 121 total blocks, including genesis
556 BOOST_CHECK_EQUAL(assumed_tip->nHeight, 120); // original chain has height 120
557 BOOST_CHECK_EQUAL(validated_tip->nHeight, 90); // current cs1 chain has height 90
558 BOOST_CHECK_EQUAL(assumed_base->nHeight, 110); // current cs2 chain has height 110
559
560 // Regenerate cs1.setBlockIndexCandidates and cs2.setBlockIndexCandidate and
561 // check contents below.
562 reload_all_block_indexes();
563
564 // The fully validated chain should only have the current validated tip
565 // as a candidate (block 90). Specifically:
566 //
567 // - It does not have blocks 0-89 because they contain less work than the
568 // chain tip.
569 //
570 // - It has block 90 because it has data and equal work to the chain tip,
571 // (since it is the chain tip).
572 //
573 // - It does not have blocks 91-110 because they do not contain data.
574 //
575 // - It does not have any blocks after height 110 because cs1 is a background
576 // chainstate, and only blocks that are ancestors of the snapshot block
577 // are added as candidates for the background chainstate.
579 BOOST_CHECK_EQUAL(cs1.setBlockIndexCandidates.count(validated_tip), 1);
580
581 // The assumed-valid tolerant chain has the assumed valid base as a
582 // candidate, but otherwise has none of the assumed-valid (which do not
583 // HAVE_DATA) blocks as candidates.
584 //
585 // Specifically:
586 // - All blocks below height 110 are not candidates, because cs2 chain tip
587 // has height 110 and they have less work than it does.
588 //
589 // - Block 110 is a candidate even though it does not have data, because it
590 // is the snapshot block, which is assumed valid.
591 //
592 // - Blocks 111-120 are added because they have data.
593
594 // Check that block 90 is absent
595 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(validated_tip), 0);
596 // Check that block 109 is absent
597 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_base->pprev), 0);
598 // Check that block 110 is present
599 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_base), 1);
600 // Check that block 120 is present
601 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_tip), 1);
602 // Check that 11 blocks total are present.
603 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.size(), num_indexes - last_assumed_valid_idx + 1);
604}
605
606BOOST_FIXTURE_TEST_CASE(loadblockindex_invalid_descendants, TestChain100Setup)
607{
608 LOCK(Assert(m_node.chainman)->GetMutex());
609 // consider the chain of blocks grand_parent <- parent <- child
610 // intentionally mark:
611 // - grand_parent: BLOCK_FAILED_VALID
612 // - parent: BLOCK_FAILED_CHILD
613 // - child: not invalid
614 // Test that when the block index is loaded, all blocks are marked as BLOCK_FAILED_VALID
615 auto* child{m_node.chainman->ActiveChain().Tip()};
616 auto* parent{child->pprev};
617 auto* grand_parent{parent->pprev};
618 grand_parent->nStatus = (grand_parent->nStatus | BLOCK_FAILED_VALID);
619 parent->nStatus = (parent->nStatus & ~BLOCK_FAILED_VALID) | BLOCK_FAILED_CHILD;
620 child->nStatus = (child->nStatus & ~BLOCK_FAILED_VALID);
621
622 // Reload block index to recompute block status validity flags.
623 m_node.chainman->LoadBlockIndex();
624
625 // check grand_parent, parent, child is marked as BLOCK_FAILED_VALID after reloading the block index
626 BOOST_CHECK(grand_parent->nStatus & BLOCK_FAILED_VALID);
627 BOOST_CHECK(parent->nStatus & BLOCK_FAILED_VALID);
628 BOOST_CHECK(child->nStatus & BLOCK_FAILED_VALID);
629}
630
633BOOST_FIXTURE_TEST_CASE(invalidate_block_and_reconsider_fork, TestChain100Setup)
634{
636 Chainstate& chainstate = chainman.ActiveChainstate();
637
638 // we have a chain of 100 blocks: genesis(0) <- ... <- block98 <- block99 <- block100
639 CBlockIndex* block98;
640 CBlockIndex* block99;
641 CBlockIndex* block100;
642 {
643 LOCK(chainman.GetMutex());
644 block98 = chainman.ActiveChain()[98];
645 block99 = chainman.ActiveChain()[99];
646 block100 = chainman.ActiveChain()[100];
647 }
648
649 // create the following block constellation:
650 // genesis(0) <- ... <- block98 <- block99 <- block100
651 // <- block99' <- block100'
652 // by temporarily invalidating block99. the chain tip now falls to block98,
653 // mine 2 new blocks on top of block 98 (block99' and block100') and then restore block99 and block 100.
655 BOOST_REQUIRE(chainstate.InvalidateBlock(state, block99));
656 BOOST_REQUIRE(WITH_LOCK(cs_main, return chainman.ActiveChain().Tip()) == block98);
657 CScript coinbase_script = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
658 for (int i = 0; i < 2; ++i) {
659 CreateAndProcessBlock({}, coinbase_script);
660 }
661 const CBlockIndex* fork_block99;
662 const CBlockIndex* fork_block100;
663 {
664 LOCK(chainman.GetMutex());
665 fork_block99 = chainman.ActiveChain()[99];
666 BOOST_REQUIRE(fork_block99->pprev == block98);
667 fork_block100 = chainman.ActiveChain()[100];
668 BOOST_REQUIRE(fork_block100->pprev == fork_block99);
669 }
670 // Restore original block99 and block100
671 {
672 LOCK(chainman.GetMutex());
673 chainstate.ResetBlockFailureFlags(block99);
674 chainman.RecalculateBestHeader();
675 }
676 chainstate.ActivateBestChain(state);
677 BOOST_REQUIRE(WITH_LOCK(cs_main, return chainman.ActiveChain().Tip()) == block100);
678
679 {
680 LOCK(chainman.GetMutex());
681 BOOST_CHECK(!(block100->nStatus & BLOCK_FAILED_VALID));
682 BOOST_CHECK(!(block99->nStatus & BLOCK_FAILED_VALID));
683 BOOST_CHECK(!(fork_block100->nStatus & BLOCK_FAILED_VALID));
684 BOOST_CHECK(!(fork_block99->nStatus & BLOCK_FAILED_VALID));
685 }
686
687 // Invalidate block98
688 BOOST_REQUIRE(chainstate.InvalidateBlock(state, block98));
689
690 {
691 LOCK(chainman.GetMutex());
692 // block98 and all descendants of block98 are marked BLOCK_FAILED_VALID
693 BOOST_CHECK(block98->nStatus & BLOCK_FAILED_VALID);
694 BOOST_CHECK(block99->nStatus & BLOCK_FAILED_VALID);
695 BOOST_CHECK(block100->nStatus & BLOCK_FAILED_VALID);
696 BOOST_CHECK(fork_block99->nStatus & BLOCK_FAILED_VALID);
697 BOOST_CHECK(fork_block100->nStatus & BLOCK_FAILED_VALID);
698 }
699
700 // Reconsider block99. ResetBlockFailureFlags clears BLOCK_FAILED_VALID from
701 // block99 and its ancestors (block98) and descendants (block100)
702 // but NOT from block99' and block100' (not a direct ancestor/descendant)
703 {
704 LOCK(chainman.GetMutex());
705 chainstate.ResetBlockFailureFlags(block99);
706 chainman.RecalculateBestHeader();
707 }
708 chainstate.ActivateBestChain(state);
709 {
710 LOCK(chainman.GetMutex());
711 BOOST_CHECK(!(block98->nStatus & BLOCK_FAILED_VALID));
712 BOOST_CHECK(!(block99->nStatus & BLOCK_FAILED_VALID));
713 BOOST_CHECK(!(block100->nStatus & BLOCK_FAILED_VALID));
714 BOOST_CHECK(fork_block99->nStatus & BLOCK_FAILED_VALID);
715 BOOST_CHECK(fork_block100->nStatus & BLOCK_FAILED_VALID);
716 }
717}
718
721BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_init, SnapshotTestSetup)
722{
724 Chainstate& bg_chainstate = chainman.ActiveChainstate();
725
726 this->SetupSnapshot();
727
728 fs::path snapshot_chainstate_dir = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
729 BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
730 BOOST_CHECK_EQUAL(snapshot_chainstate_dir, gArgs.GetDataDirNet() / "chainstate_snapshot");
731
733 const uint256 snapshot_tip_hash = WITH_LOCK(chainman.GetMutex(),
734 return chainman.ActiveTip()->GetBlockHash());
735
736 BOOST_CHECK_EQUAL(WITH_LOCK(chainman.GetMutex(), return chainman.m_chainstates.size()), 2);
737
738 // "Rewind" the background chainstate so that its tip is not at the
739 // base block of the snapshot - this is so after simulating a node restart,
740 // it will initialize instead of attempting to complete validation.
741 //
742 // Note that this is not a realistic use of DisconnectTip().
744 BlockValidationState unused_state;
745 {
746 LOCK2(::cs_main, bg_chainstate.MempoolMutex());
747 BOOST_CHECK(bg_chainstate.DisconnectTip(unused_state, &unused_pool));
748 unused_pool.clear(); // to avoid queuedTx assertion errors on teardown
749 }
750 BOOST_CHECK_EQUAL(bg_chainstate.m_chain.Height(), 109);
751
752 // Test that simulating a shutdown (resetting ChainstateManager) and then performing
753 // chainstate reinitializing successfully reloads both chainstates.
754 ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
755
756 BOOST_TEST_MESSAGE("Performing Load/Verify/Activate of chainstate");
757
758 // This call reinitializes the chainstates.
759 this->LoadVerifyActivateChainstate();
760
761 {
762 LOCK(chainman_restarted.GetMutex());
763 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 2);
764 // Background chainstate has height of 109 not 110 here due to a quirk
765 // of the LoadVerifyActivate only calling ActivateBestChain on one
766 // chainstate. The height would be 110 after a real restart, but it's
767 // fine for this test which is focused on the snapshot chainstate.
768 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[0]->m_chain.Height(), 109);
769 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[1]->m_chain.Height(), 210);
770
772 BOOST_CHECK(chainman_restarted.CurrentChainstate().m_assumeutxo == Assumeutxo::UNVALIDATED);
773
774 BOOST_CHECK_EQUAL(chainman_restarted.ActiveTip()->GetBlockHash(), snapshot_tip_hash);
775 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
776 BOOST_CHECK_EQUAL(chainman_restarted.HistoricalChainstate()->m_chain.Height(), 109);
777 }
778
779 BOOST_TEST_MESSAGE(
780 "Ensure we can mine blocks on top of the initialized snapshot chainstate");
781 mineBlocks(10);
782 {
783 LOCK(chainman_restarted.GetMutex());
784 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
785
786 // Background chainstate should be unaware of new blocks on the snapshot
787 // chainstate, but the block disconnected above is now reattached.
788 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 2);
789 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[0]->m_chain.Height(), 110);
790 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[1]->m_chain.Height(), 220);
791 BOOST_CHECK_EQUAL(chainman_restarted.HistoricalChainstate(), nullptr);
792 }
793}
794
795BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_completion, SnapshotTestSetup)
796{
797 this->SetupSnapshot();
798
800 Chainstate& active_cs = chainman.ActiveChainstate();
801 Chainstate& validated_cs{*Assert(WITH_LOCK(cs_main, return chainman.HistoricalChainstate()))};
802 auto tip_cache_before_complete = active_cs.m_coinstip_cache_size_bytes;
803 auto db_cache_before_complete = active_cs.m_coinsdb_cache_size_bytes;
804
806 m_node.notifications->m_shutdown_on_fatal_error = false;
807
808 fs::path snapshot_chainstate_dir = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
809 BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
810 BOOST_CHECK_EQUAL(snapshot_chainstate_dir, gArgs.GetDataDirNet() / "chainstate_snapshot");
811
813 const uint256 snapshot_tip_hash = WITH_LOCK(chainman.GetMutex(),
814 return chainman.ActiveTip()->GetBlockHash());
815
816 res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validated_cs, active_cs));
818
819 BOOST_CHECK(WITH_LOCK(::cs_main, return chainman.CurrentChainstate().m_assumeutxo == Assumeutxo::VALIDATED));
821 BOOST_CHECK_EQUAL(WITH_LOCK(chainman.GetMutex(), return chainman.HistoricalChainstate()), nullptr);
822
823 // Cache should have been rebalanced and reallocated to the "only" remaining
824 // chainstate.
825 BOOST_CHECK(active_cs.m_coinstip_cache_size_bytes > tip_cache_before_complete);
826 BOOST_CHECK(active_cs.m_coinsdb_cache_size_bytes > db_cache_before_complete);
827
828 // Trying completion again should return false.
829 res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validated_cs, active_cs));
831
832 // The invalid snapshot path should not have been used.
833 fs::path snapshot_invalid_dir = gArgs.GetDataDirNet() / "chainstate_snapshot_INVALID";
834 BOOST_CHECK(!fs::exists(snapshot_invalid_dir));
835 // chainstate_snapshot should still exist.
836 BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
837
838 // Test that simulating a shutdown (resetting ChainstateManager) and then performing
839 // chainstate reinitializing successfully cleans up the background-validation
840 // chainstate data, and we end up with a single chainstate that is at tip.
841 ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
842
843 BOOST_TEST_MESSAGE("Performing Load/Verify/Activate of chainstate");
844
845 // This call reinitializes the chainstates, and should clean up the now unnecessary
846 // background-validation leveldb contents.
847 this->LoadVerifyActivateChainstate();
848
849 BOOST_CHECK(!fs::exists(snapshot_invalid_dir));
850 // chainstate_snapshot should now *not* exist.
851 BOOST_CHECK(!fs::exists(snapshot_chainstate_dir));
852
853 const Chainstate& active_cs2 = chainman_restarted.ActiveChainstate();
854
855 {
856 LOCK(chainman_restarted.GetMutex());
857 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 1);
859 BOOST_CHECK(active_cs2.m_coinstip_cache_size_bytes > tip_cache_before_complete);
860 BOOST_CHECK(active_cs2.m_coinsdb_cache_size_bytes > db_cache_before_complete);
861
862 BOOST_CHECK_EQUAL(chainman_restarted.ActiveTip()->GetBlockHash(), snapshot_tip_hash);
863 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
864 }
865
866 BOOST_TEST_MESSAGE(
867 "Ensure we can mine blocks on top of the \"new\" IBD chainstate");
868 mineBlocks(10);
869 {
870 LOCK(chainman_restarted.GetMutex());
871 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
872 }
873}
874
875BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_completion_hash_mismatch, SnapshotTestSetup)
876{
877 auto chainstates = this->SetupSnapshot();
878 Chainstate& validation_chainstate = *std::get<0>(chainstates);
879 Chainstate& unvalidated_cs = *std::get<1>(chainstates);
882 m_node.notifications->m_shutdown_on_fatal_error = false;
883
884 // Test tampering with the IBD UTXO set with an extra coin to ensure it causes
885 // snapshot completion to fail.
887 return validation_chainstate.CoinsTip());
888 Coin badcoin;
889 badcoin.out.nValue = m_rng.rand32();
890 badcoin.nHeight = 1;
891 badcoin.out.scriptPubKey.assign(m_rng.randbits(6), 0);
892 Txid txid = Txid::FromUint256(m_rng.rand256());
893 ibd_coins.AddCoin(COutPoint(txid, 0), std::move(badcoin), false);
894
895 fs::path snapshot_chainstate_dir = gArgs.GetDataDirNet() / "chainstate_snapshot";
896 BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
897
898 {
899 ASSERT_DEBUG_LOG("failed to validate the -assumeutxo snapshot state");
900 res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validation_chainstate, unvalidated_cs));
902 }
903
904 {
905 LOCK(chainman.GetMutex());
906 BOOST_CHECK_EQUAL(chainman.m_chainstates.size(), 2);
907 BOOST_CHECK(chainman.m_chainstates[0]->m_assumeutxo == Assumeutxo::VALIDATED);
908 BOOST_CHECK(!chainman.m_chainstates[0]->SnapshotBase());
909 BOOST_CHECK(chainman.m_chainstates[1]->m_assumeutxo == Assumeutxo::INVALID);
910 BOOST_CHECK(chainman.m_chainstates[1]->SnapshotBase());
911 }
912
913 fs::path snapshot_invalid_dir = gArgs.GetDataDirNet() / "chainstate_snapshot_INVALID";
914 BOOST_CHECK(fs::exists(snapshot_invalid_dir));
915
916 // Test that simulating a shutdown (resetting ChainstateManager) and then performing
917 // chainstate reinitializing successfully loads only the fully-validated
918 // chainstate data, and we end up with a single chainstate that is at tip.
919 ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
920
921 BOOST_TEST_MESSAGE("Performing Load/Verify/Activate of chainstate");
922
923 // This call reinitializes the chainstates, and should clean up the now unnecessary
924 // background-validation leveldb contents.
925 this->LoadVerifyActivateChainstate();
926
927 BOOST_CHECK(fs::exists(snapshot_invalid_dir));
928 BOOST_CHECK(!fs::exists(snapshot_chainstate_dir));
929
930 {
932 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 1);
934 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
935 }
936
937 BOOST_TEST_MESSAGE(
938 "Ensure we can mine blocks on top of the \"new\" IBD chainstate");
939 mineBlocks(10);
940 {
942 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
943 }
944}
945
947template <typename Options>
949 const std::vector<const char*>& args)
950{
951 const auto argv{Cat({"ignore"}, args)};
952 std::string error{};
953 if (!args_man.ParseParameters(argv.size(), argv.data(), error)) {
954 return util::Error{Untranslated("ParseParameters failed with error: " + error)};
955 }
956 const auto result{node::ApplyArgsManOptions(args_man, opts)};
957 if (!result) return util::Error{util::ErrorString(result)};
958 return opts;
959}
960
962{
964 auto get_opts = [&](const std::vector<const char*>& args) {
965 static kernel::Notifications notifications{};
966 static const ChainstateManager::Options options{
968 .datadir = {},
969 .notifications = notifications};
970 return SetOptsFromArgs(*this->m_node.args, options, args);
971 };
973 auto get_valid_opts = [&](const std::vector<const char*>& args) {
974 const auto result{get_opts(args)};
975 BOOST_REQUIRE_MESSAGE(result, util::ErrorString(result).original);
976 return *result;
977 };
978
979 // test -assumevalid
980 BOOST_CHECK(!get_valid_opts({}).assumed_valid_block);
981 BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid="}).assumed_valid_block, uint256::ZERO);
982 BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid=0"}).assumed_valid_block, uint256::ZERO);
983 BOOST_CHECK_EQUAL(get_valid_opts({"-noassumevalid"}).assumed_valid_block, uint256::ZERO);
984 BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid=0x12"}).assumed_valid_block, uint256{0x12});
985
986 std::string assume_valid{"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"};
987 BOOST_CHECK_EQUAL(get_valid_opts({("-assumevalid=" + assume_valid).c_str()}).assumed_valid_block, uint256::FromHex(assume_valid));
988
989 BOOST_CHECK(!get_opts({"-assumevalid=xyz"})); // invalid hex characters
990 BOOST_CHECK(!get_opts({"-assumevalid=01234567890123456789012345678901234567890123456789012345678901234"})); // > 64 hex chars
991
992 // test -minimumchainwork
993 BOOST_CHECK(!get_valid_opts({}).minimum_chain_work);
994 BOOST_CHECK_EQUAL(get_valid_opts({"-minimumchainwork=0"}).minimum_chain_work, arith_uint256());
995 BOOST_CHECK_EQUAL(get_valid_opts({"-nominimumchainwork"}).minimum_chain_work, arith_uint256());
996 BOOST_CHECK_EQUAL(get_valid_opts({"-minimumchainwork=0x1234"}).minimum_chain_work, arith_uint256{0x1234});
997
998 std::string minimum_chainwork{"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"};
999 BOOST_CHECK_EQUAL(get_valid_opts({("-minimumchainwork=" + minimum_chainwork).c_str()}).minimum_chain_work, UintToArith256(uint256::FromHex(minimum_chainwork).value()));
1000
1001 BOOST_CHECK(!get_opts({"-minimumchainwork=xyz"})); // invalid hex characters
1002 BOOST_CHECK(!get_opts({"-minimumchainwork=01234567890123456789012345678901234567890123456789012345678901234"})); // > 64 hex chars
1003
1004 BOOST_CHECK_EQUAL(get_valid_opts({}).prevoutfetch_threads_num, DEFAULT_PREVOUTFETCH_THREADS);
1005 BOOST_CHECK_EQUAL(get_valid_opts({"-prevoutfetchthreads=0"}).prevoutfetch_threads_num, 0);
1006 BOOST_CHECK_EQUAL(get_valid_opts({"-prevoutfetchthreads=3"}).prevoutfetch_threads_num, 3);
1007 BOOST_CHECK_EQUAL(get_valid_opts({"-prevoutfetchthreads=100"}).prevoutfetch_threads_num, MAX_PREVOUTFETCH_THREADS);
1008 BOOST_CHECK(!get_opts({"-prevoutfetchthreads=-1"}));
1009}
1010
ArgsManager gArgs
Definition: args.cpp:38
arith_uint256 UintToArith256(const uint256 &a)
static void pool cs
node::NodeContext m_node
Definition: bitcoin-gui.cpp:47
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.
static 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:119
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:29
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
CScript scriptPubKey
Definition: transaction.h:143
CAmount nValue
Definition: transaction.h:142
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:554
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:628
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition: validation.h:724
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:689
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition: validation.h:721
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:808
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:640
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:686
RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Indirection necessary to make lock annotations work with an optional mempool.
Definition: validation.h:847
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Definition: validation.h:945
Chainstate * HistoricalChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return historical chainstate targeting a specific block, if any.
Definition: validation.h:1136
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:1087
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1037
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1175
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:1127
size_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:1091
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1174
const Options m_options
Definition: validation.h:1040
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:1173
void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1071
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1043
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:196
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()
static const 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:96
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:403
@ 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:41
fs::path path
Location in the filesystem where leveldb data will be stored.
Definition: dbwrapper.h:43
std::tuple< Chainstate *, Chainstate * > SetupSnapshot()
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:139
Testing setup that configures a complete environment.
Definition: setup_common.h:115
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:97
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:71
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:76
std::unique_ptr< node::Warnings > warnings
Manages all the node warnings.
Definition: context.h:100
std::function< bool()> shutdown_request
Function to request a shutdown.
Definition: context.h:66
std::unique_ptr< KernelNotifications > notifications
Issues blocking calls about sync status, errors and warnings.
Definition: context.h:95
util::SignalInterrupt * shutdown_signal
Interrupt object used to track whether node shutdown was requested.
Definition: context.h:68
ArgsManager * args
Definition: context.h:78
std::atomic< int > exit_status
Definition: context.h:98
#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:907
@ 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.
static 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