Bitcoin Core 30.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/logging.h>
16#include <test/util/random.h>
19#include <uint256.h>
20#include <util/result.h>
21#include <util/vector.h>
22#include <validation.h>
23#include <validationinterface.h>
24
25#include <tinyformat.h>
26
27#include <vector>
28
29#include <boost/test/unit_test.hpp>
30
34
35BOOST_FIXTURE_TEST_SUITE(validation_chainstatemanager_tests, TestingSetup)
36
37
41{
43
45
46 // Create a legacy (IBD) chainstate.
47 //
48 Chainstate& c1 = manager.ActiveChainstate();
49
51 {
52 LOCK(manager.GetMutex());
53 BOOST_CHECK_EQUAL(manager.m_chainstates.size(), 1);
54 BOOST_CHECK_EQUAL(manager.m_chainstates[0].get(), &c1);
55 }
56
57 auto& active_chain = WITH_LOCK(manager.GetMutex(), return manager.ActiveChain());
58 BOOST_CHECK_EQUAL(&active_chain, &c1.m_chain);
59
60 // Get to a valid assumeutxo tip (per chainparams);
61 mineBlocks(10);
62 BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 110);
63 auto active_tip = WITH_LOCK(manager.GetMutex(), return manager.ActiveTip());
64 auto exp_tip = c1.m_chain.Tip();
65 BOOST_CHECK_EQUAL(active_tip, exp_tip);
66
68
69 // Create a snapshot-based chainstate.
70 //
71 const uint256 snapshot_blockhash = active_tip->GetBlockHash();
72 Chainstate& c2{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, snapshot_blockhash)))};
73 c2.InitCoinsDB(
74 /*cache_size_bytes=*/1 << 23, /*in_memory=*/true, /*should_wipe=*/false);
75 {
77 c2.InitCoinsCache(1 << 23);
78 c2.CoinsTip().SetBestBlock(active_tip->GetBlockHash());
79 c2.setBlockIndexCandidates.insert(manager.m_blockman.LookupBlockIndex(active_tip->GetBlockHash()));
80 c2.LoadChainTip();
81 }
83 BOOST_CHECK(c2.ActivateBestChain(_, nullptr));
84
87 BOOST_CHECK_EQUAL(&c2, &manager.ActiveChainstate());
88 BOOST_CHECK(&c1 != &manager.ActiveChainstate());
89 {
90 LOCK(manager.GetMutex());
91 BOOST_CHECK_EQUAL(manager.m_chainstates.size(), 2);
92 BOOST_CHECK_EQUAL(manager.m_chainstates[0].get(), &c1);
93 BOOST_CHECK_EQUAL(manager.m_chainstates[1].get(), &c2);
94 }
95
96 auto& active_chain2 = WITH_LOCK(manager.GetMutex(), return manager.ActiveChain());
97 BOOST_CHECK_EQUAL(&active_chain2, &c2.m_chain);
98
99 BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 110);
100 mineBlocks(1);
101 BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 111);
102 BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return c1.m_chain.Height()), 110);
103
104 auto active_tip2 = WITH_LOCK(manager.GetMutex(), return manager.ActiveTip());
105 BOOST_CHECK_EQUAL(active_tip, active_tip2->pprev);
106 BOOST_CHECK_EQUAL(active_tip, c1.m_chain.Tip());
107 BOOST_CHECK_EQUAL(active_tip2, c2.m_chain.Tip());
108
109 // Let scheduler events finish running to avoid accessing memory that is going to be unloaded
110 m_node.validation_signals->SyncWithValidationInterfaceQueue();
111}
112
114BOOST_FIXTURE_TEST_CASE(chainstatemanager_rebalance_caches, TestChain100Setup)
115{
117
118 size_t max_cache = 10000;
119 manager.m_total_coinsdb_cache = max_cache;
120 manager.m_total_coinstip_cache = max_cache;
121
122 std::vector<Chainstate*> chainstates;
123
124 // Create a legacy (IBD) chainstate.
125 //
126 Chainstate& c1 = manager.ActiveChainstate();
127 chainstates.push_back(&c1);
128 {
130 c1.InitCoinsCache(1 << 23);
131 manager.MaybeRebalanceCaches();
132 }
133
136
137 // Create a snapshot-based chainstate.
138 //
139 CBlockIndex* snapshot_base{WITH_LOCK(manager.GetMutex(), return manager.ActiveChain()[manager.ActiveChain().Height() / 2])};
140 Chainstate& c2{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, *snapshot_base->phashBlock)))};
141 chainstates.push_back(&c2);
142 c2.InitCoinsDB(
143 /*cache_size_bytes=*/1 << 23, /*in_memory=*/true, /*should_wipe=*/false);
144
145 // Reset IBD state so IsInitialBlockDownload() returns true and causes
146 // MaybeRebalancesCaches() to prioritize the snapshot chainstate, giving it
147 // more cache space than the snapshot chainstate. Calling ResetIbd() is
148 // necessary because m_cached_finished_ibd is already latched to true before
149 // the test starts due to the test setup. After ResetIbd() is called.
150 // IsInitialBlockDownload will return true because at this point the active
151 // chainstate has a null chain tip.
152 static_cast<TestChainstateManager&>(manager).ResetIbd();
153
154 {
156 c2.InitCoinsCache(1 << 23);
157 manager.MaybeRebalanceCaches();
158 }
159
160 BOOST_CHECK_CLOSE(double(c1.m_coinstip_cache_size_bytes), max_cache * 0.05, 1);
161 BOOST_CHECK_CLOSE(double(c1.m_coinsdb_cache_size_bytes), max_cache * 0.05, 1);
162 BOOST_CHECK_CLOSE(double(c2.m_coinstip_cache_size_bytes), max_cache * 0.95, 1);
163 BOOST_CHECK_CLOSE(double(c2.m_coinsdb_cache_size_bytes), max_cache * 0.95, 1);
164}
165
167 // Run with coinsdb on the filesystem to support, e.g., moving invalidated
168 // chainstate dirs to "*_invalid".
169 //
170 // Note that this means the tests run considerably slower than in-memory DB
171 // tests, but we can't otherwise test this functionality since it relies on
172 // destructive filesystem operations.
174 {},
175 {
176 .coins_db_in_memory = false,
177 .block_tree_db_in_memory = false,
178 },
179 }
180 {
181 }
182
183 std::tuple<Chainstate*, Chainstate*> SetupSnapshot()
184 {
186
187 {
191 }
192
193 size_t initial_size;
194 size_t initial_total_coins{100};
195
196 // Make some initial assertions about the contents of the chainstate.
197 {
199 CCoinsViewCache& ibd_coinscache = chainman.ActiveChainstate().CoinsTip();
200 initial_size = ibd_coinscache.GetCacheSize();
201 size_t total_coins{0};
202
203 for (CTransactionRef& txn : m_coinbase_txns) {
204 COutPoint op{txn->GetHash(), 0};
205 BOOST_CHECK(ibd_coinscache.HaveCoin(op));
206 total_coins++;
207 }
208
209 BOOST_CHECK_EQUAL(total_coins, initial_total_coins);
210 BOOST_CHECK_EQUAL(initial_size, initial_total_coins);
211 }
212
213 Chainstate& validation_chainstate = chainman.ActiveChainstate();
214
215 // Snapshot should refuse to load at this height.
216 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(this));
218
219 // Mine 10 more blocks, putting at us height 110 where a valid assumeutxo value can
220 // be found.
221 constexpr int snapshot_height = 110;
222 mineBlocks(10);
223 initial_size += 10;
224 initial_total_coins += 10;
225
226 // Should not load malleated snapshots
227 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
228 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
229 // A UTXO is missing but count is correct
230 metadata.m_coins_count -= 1;
231
232 Txid txid;
233 auto_infile >> txid;
234 // coins size
235 (void)ReadCompactSize(auto_infile);
236 // vout index
237 (void)ReadCompactSize(auto_infile);
238 Coin coin;
239 auto_infile >> coin;
240 }));
241
243
244 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
245 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
246 // Coins count is larger than coins in file
247 metadata.m_coins_count += 1;
248 }));
249 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
250 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
251 // Coins count is smaller than coins in file
252 metadata.m_coins_count -= 1;
253 }));
254 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
255 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
256 // Wrong hash
258 }));
259 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
260 this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
261 // Wrong hash
263 }));
264
265 BOOST_REQUIRE(CreateAndActivateUTXOSnapshot(this));
267
268 // Ensure our active chain is the snapshot chainstate.
270
271 Chainstate& snapshot_chainstate = chainman.ActiveChainstate();
272
273 {
275
276 fs::path found = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
277
278 // Note: WriteSnapshotBaseBlockhash() is implicitly tested above.
282 }
283
284 const auto& au_data = ::Params().AssumeutxoForHeight(snapshot_height);
285 const CBlockIndex* tip = WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip());
286
287 BOOST_CHECK_EQUAL(tip->m_chain_tx_count, au_data->m_chain_tx_count);
288
289 // To be checked against later when we try loading a subsequent snapshot.
290 uint256 loaded_snapshot_blockhash{*Assert(WITH_LOCK(chainman.GetMutex(), return chainman.CurrentChainstate().m_from_snapshot_blockhash))};
291
292 // Make some assertions about the both chainstates. These checks ensure the
293 // legacy chainstate hasn't changed and that the newly created chainstate
294 // reflects the expected content.
295 {
297 int chains_tested{0};
298
299 for (const auto& chainstate : chainman.m_chainstates) {
300 BOOST_TEST_MESSAGE("Checking coins in " << chainstate->ToString());
301 CCoinsViewCache& coinscache = chainstate->CoinsTip();
302
303 // Both caches will be empty initially.
304 BOOST_CHECK_EQUAL((unsigned int)0, coinscache.GetCacheSize());
305
306 size_t total_coins{0};
307
308 for (CTransactionRef& txn : m_coinbase_txns) {
309 COutPoint op{txn->GetHash(), 0};
310 BOOST_CHECK(coinscache.HaveCoin(op));
311 total_coins++;
312 }
313
314 BOOST_CHECK_EQUAL(initial_size , coinscache.GetCacheSize());
315 BOOST_CHECK_EQUAL(total_coins, initial_total_coins);
316 chains_tested++;
317 }
318
319 BOOST_CHECK_EQUAL(chains_tested, 2);
320 }
321
322 // Mine some new blocks on top of the activated snapshot chainstate.
323 constexpr size_t new_coins{100};
324 mineBlocks(new_coins); // Defined in TestChain100Setup.
325
326 {
328 size_t coins_in_active{0};
329 size_t coins_in_background{0};
330 size_t coins_missing_from_background{0};
331
332 for (const auto& chainstate : chainman.m_chainstates) {
333 BOOST_TEST_MESSAGE("Checking coins in " << chainstate->ToString());
334 CCoinsViewCache& coinscache = chainstate->CoinsTip();
335 bool is_background = chainstate.get() != &chainman.ActiveChainstate();
336
337 for (CTransactionRef& txn : m_coinbase_txns) {
338 COutPoint op{txn->GetHash(), 0};
339 if (coinscache.HaveCoin(op)) {
340 (is_background ? coins_in_background : coins_in_active)++;
341 } else if (is_background) {
342 coins_missing_from_background++;
343 }
344 }
345 }
346
347 BOOST_CHECK_EQUAL(coins_in_active, initial_total_coins + new_coins);
348 BOOST_CHECK_EQUAL(coins_in_background, initial_total_coins);
349 BOOST_CHECK_EQUAL(coins_missing_from_background, new_coins);
350 }
351
352 // Snapshot should refuse to load after one has already loaded.
353 BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(this));
354
355 // Snapshot blockhash should be unchanged.
358 loaded_snapshot_blockhash);
359 return std::make_tuple(&validation_chainstate, &snapshot_chainstate);
360 }
361
362 // Simulate a restart of the node by flushing all state to disk, clearing the
363 // existing ChainstateManager, and unloading the block index.
364 //
365 // @returns a reference to the "restarted" ChainstateManager
367 {
369
370 BOOST_TEST_MESSAGE("Simulating node restart");
371 {
372 LOCK(chainman.GetMutex());
373 for (const auto& cs : chainman.m_chainstates) {
374 if (cs->CanFlushToDisk()) cs->ForceFlushStateToDisk();
375 }
376 }
377 {
378 // Process all callbacks referring to the old manager before wiping it.
379 m_node.validation_signals->SyncWithValidationInterfaceQueue();
381 chainman.ResetChainstates();
382 BOOST_CHECK_EQUAL(chainman.m_chainstates.size(), 0);
383 m_node.notifications = std::make_unique<KernelNotifications>(Assert(m_node.shutdown_request), m_node.exit_status, *Assert(m_node.warnings));
384 const ChainstateManager::Options chainman_opts{
386 .datadir = chainman.m_options.datadir,
387 .notifications = *m_node.notifications,
388 .signals = m_node.validation_signals.get(),
389 };
390 const BlockManager::Options blockman_opts{
391 .chainparams = chainman_opts.chainparams,
392 .blocks_dir = m_args.GetBlocksDirPath(),
393 .notifications = chainman_opts.notifications,
394 .block_tree_db_params = DBParams{
395 .path = chainman.m_options.datadir / "blocks" / "index",
396 .cache_bytes = m_kernel_cache_sizes.block_tree_db,
397 .memory_only = m_block_tree_db_in_memory,
398 },
399 };
400 // For robustness, ensure the old manager is destroyed before creating a
401 // new one.
402 m_node.chainman.reset();
403 m_node.chainman = std::make_unique<ChainstateManager>(*Assert(m_node.shutdown_signal), chainman_opts, blockman_opts);
404 }
405 return *Assert(m_node.chainman);
406 }
407};
408
410BOOST_FIXTURE_TEST_CASE(chainstatemanager_activate_snapshot, SnapshotTestSetup)
411{
412 this->SetupSnapshot();
413}
414
425BOOST_FIXTURE_TEST_CASE(chainstatemanager_loadblockindex, TestChain100Setup)
426{
428 Chainstate& cs1 = chainman.ActiveChainstate();
429
430 int num_indexes{0};
431 // Blocks in range [assumed_valid_start_idx, last_assumed_valid_idx) will be
432 // marked as assumed-valid and not having data.
433 const int expected_assumed_valid{20};
434 const int last_assumed_valid_idx{111};
435 const int assumed_valid_start_idx = last_assumed_valid_idx - expected_assumed_valid;
436
437 // Mine to height 120, past the hardcoded regtest assumeutxo snapshot at
438 // height 110
439 mineBlocks(20);
440
441 CBlockIndex* validated_tip{nullptr};
442 CBlockIndex* assumed_base{nullptr};
443 CBlockIndex* assumed_tip{WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip())};
444 BOOST_CHECK_EQUAL(assumed_tip->nHeight, 120);
445
446 auto reload_all_block_indexes = [&]() {
447 LOCK(chainman.GetMutex());
448 // For completeness, we also reset the block sequence counters to
449 // ensure that no state which affects the ranking of tip-candidates is
450 // retained (even though this isn't strictly necessary).
452 for (const auto& cs : chainman.m_chainstates) {
453 cs->ClearBlockIndexCandidates();
454 BOOST_CHECK(cs->setBlockIndexCandidates.empty());
455 }
456 chainman.LoadBlockIndex();
457 };
458
459 // Ensure that without any assumed-valid BlockIndex entries, only the current tip is
460 // considered as a candidate.
461 reload_all_block_indexes();
463
464 // Reset some region of the chain's nStatus, removing the HAVE_DATA flag.
465 for (int i = 0; i <= cs1.m_chain.Height(); ++i) {
467 auto index = cs1.m_chain[i];
468
469 // Blocks with heights in range [91, 110] are marked as missing data.
470 if (i < last_assumed_valid_idx && i >= assumed_valid_start_idx) {
471 index->nStatus = BlockStatus::BLOCK_VALID_TREE;
472 index->nTx = 0;
473 index->m_chain_tx_count = 0;
474 }
475
476 ++num_indexes;
477
478 // Note the last fully-validated block as the expected validated tip.
479 if (i == (assumed_valid_start_idx - 1)) {
480 validated_tip = index;
481 }
482 // Note the last assumed valid block as the snapshot base
483 if (i == last_assumed_valid_idx - 1) {
484 assumed_base = index;
485 }
486 }
487
488 // Note: cs2's tip is not set when ActivateExistingSnapshot is called.
489 Chainstate& cs2{WITH_LOCK(::cs_main, return chainman.AddChainstate(std::make_unique<Chainstate>(nullptr, chainman.m_blockman, chainman, *assumed_base->phashBlock)))};
490
491 // Set tip of the fully validated chain to be the validated tip
492 cs1.m_chain.SetTip(*validated_tip);
493
494 // Set tip of the assume-valid-based chain to the assume-valid block
495 cs2.m_chain.SetTip(*assumed_base);
496
497 // Sanity check test variables.
498 BOOST_CHECK_EQUAL(num_indexes, 121); // 121 total blocks, including genesis
499 BOOST_CHECK_EQUAL(assumed_tip->nHeight, 120); // original chain has height 120
500 BOOST_CHECK_EQUAL(validated_tip->nHeight, 90); // current cs1 chain has height 90
501 BOOST_CHECK_EQUAL(assumed_base->nHeight, 110); // current cs2 chain has height 110
502
503 // Regenerate cs1.setBlockIndexCandidates and cs2.setBlockIndexCandidate and
504 // check contents below.
505 reload_all_block_indexes();
506
507 // The fully validated chain should only have the current validated tip and
508 // the assumed valid base as candidates, blocks 90 and 110. Specifically:
509 //
510 // - It does not have blocks 0-89 because they contain less work than the
511 // chain tip.
512 //
513 // - It has block 90 because it has data and equal work to the chain tip,
514 // (since it is the chain tip).
515 //
516 // - It does not have blocks 91-109 because they do not contain data.
517 //
518 // - It has block 110 even though it does not have data, because
519 // LoadBlockIndex has a special case to always add the snapshot block as a
520 // candidate. The special case is only actually intended to apply to the
521 // snapshot chainstate cs2, not the background chainstate cs1, but it is
522 // written broadly and applies to both.
523 //
524 // - It does not have any blocks after height 110 because cs1 is a background
525 // chainstate, and only blocks where are ancestors of the snapshot block
526 // are added as candidates for the background chainstate.
528 BOOST_CHECK_EQUAL(cs1.setBlockIndexCandidates.count(validated_tip), 1);
529 BOOST_CHECK_EQUAL(cs1.setBlockIndexCandidates.count(assumed_base), 1);
530
531 // The assumed-valid tolerant chain has the assumed valid base as a
532 // candidate, but otherwise has none of the assumed-valid (which do not
533 // HAVE_DATA) blocks as candidates.
534 //
535 // Specifically:
536 // - All blocks below height 110 are not candidates, because cs2 chain tip
537 // has height 110 and they have less work than it does.
538 //
539 // - Block 110 is a candidate even though it does not have data, because it
540 // is the snapshot block, which is assumed valid.
541 //
542 // - Blocks 111-120 are added because they have data.
543
544 // Check that block 90 is absent
545 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(validated_tip), 0);
546 // Check that block 109 is absent
547 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_base->pprev), 0);
548 // Check that block 110 is present
549 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_base), 1);
550 // Check that block 120 is present
551 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_tip), 1);
552 // Check that 11 blocks total are present.
553 BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.size(), num_indexes - last_assumed_valid_idx + 1);
554}
555
558BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_init, SnapshotTestSetup)
559{
561 Chainstate& bg_chainstate = chainman.ActiveChainstate();
562
563 this->SetupSnapshot();
564
565 fs::path snapshot_chainstate_dir = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
566 BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
567 BOOST_CHECK_EQUAL(snapshot_chainstate_dir, gArgs.GetDataDirNet() / "chainstate_snapshot");
568
570 const uint256 snapshot_tip_hash = WITH_LOCK(chainman.GetMutex(),
571 return chainman.ActiveTip()->GetBlockHash());
572
573 BOOST_CHECK_EQUAL(WITH_LOCK(chainman.GetMutex(), return chainman.m_chainstates.size()), 2);
574
575 // "Rewind" the background chainstate so that its tip is not at the
576 // base block of the snapshot - this is so after simulating a node restart,
577 // it will initialize instead of attempting to complete validation.
578 //
579 // Note that this is not a realistic use of DisconnectTip().
581 BlockValidationState unused_state;
582 {
583 LOCK2(::cs_main, bg_chainstate.MempoolMutex());
584 BOOST_CHECK(bg_chainstate.DisconnectTip(unused_state, &unused_pool));
585 unused_pool.clear(); // to avoid queuedTx assertion errors on teardown
586 }
587 BOOST_CHECK_EQUAL(bg_chainstate.m_chain.Height(), 109);
588
589 // Test that simulating a shutdown (resetting ChainstateManager) and then performing
590 // chainstate reinitializing successfully reloads both chainstates.
591 ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
592
593 BOOST_TEST_MESSAGE("Performing Load/Verify/Activate of chainstate");
594
595 // This call reinitializes the chainstates.
596 this->LoadVerifyActivateChainstate();
597
598 {
599 LOCK(chainman_restarted.GetMutex());
600 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 2);
601 // Background chainstate has height of 109 not 110 here due to a quirk
602 // of the LoadVerifyActivate only calling ActivateBestChain on one
603 // chainstate. The height would be 110 after a real restart, but it's
604 // fine for this test which is focused on the snapshot chainstate.
605 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[0]->m_chain.Height(), 109);
606 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[1]->m_chain.Height(), 210);
607
609 BOOST_CHECK(chainman_restarted.CurrentChainstate().m_assumeutxo == Assumeutxo::UNVALIDATED);
610
611 BOOST_CHECK_EQUAL(chainman_restarted.ActiveTip()->GetBlockHash(), snapshot_tip_hash);
612 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
613 BOOST_CHECK_EQUAL(chainman_restarted.HistoricalChainstate()->m_chain.Height(), 109);
614 }
615
616 BOOST_TEST_MESSAGE(
617 "Ensure we can mine blocks on top of the initialized snapshot chainstate");
618 mineBlocks(10);
619 {
620 LOCK(chainman_restarted.GetMutex());
621 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
622
623 // Background chainstate should be unaware of new blocks on the snapshot
624 // chainstate, but the block disconnected above is now reattached.
625 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 2);
626 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[0]->m_chain.Height(), 110);
627 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[1]->m_chain.Height(), 220);
628 BOOST_CHECK_EQUAL(chainman_restarted.HistoricalChainstate(), nullptr);
629 }
630}
631
632BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_completion, SnapshotTestSetup)
633{
634 this->SetupSnapshot();
635
637 Chainstate& active_cs = chainman.ActiveChainstate();
638 Chainstate& validated_cs{*Assert(WITH_LOCK(cs_main, return chainman.HistoricalChainstate()))};
639 auto tip_cache_before_complete = active_cs.m_coinstip_cache_size_bytes;
640 auto db_cache_before_complete = active_cs.m_coinsdb_cache_size_bytes;
641
643 m_node.notifications->m_shutdown_on_fatal_error = false;
644
645 fs::path snapshot_chainstate_dir = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
646 BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
647 BOOST_CHECK_EQUAL(snapshot_chainstate_dir, gArgs.GetDataDirNet() / "chainstate_snapshot");
648
650 const uint256 snapshot_tip_hash = WITH_LOCK(chainman.GetMutex(),
651 return chainman.ActiveTip()->GetBlockHash());
652
653 res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validated_cs, active_cs));
655
656 BOOST_CHECK(WITH_LOCK(::cs_main, return chainman.CurrentChainstate().m_assumeutxo == Assumeutxo::VALIDATED));
658 BOOST_CHECK_EQUAL(WITH_LOCK(chainman.GetMutex(), return chainman.HistoricalChainstate()), nullptr);
659
660 // Cache should have been rebalanced and reallocated to the "only" remaining
661 // chainstate.
662 BOOST_CHECK(active_cs.m_coinstip_cache_size_bytes > tip_cache_before_complete);
663 BOOST_CHECK(active_cs.m_coinsdb_cache_size_bytes > db_cache_before_complete);
664
665 // Trying completion again should return false.
666 res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validated_cs, active_cs));
668
669 // The invalid snapshot path should not have been used.
670 fs::path snapshot_invalid_dir = gArgs.GetDataDirNet() / "chainstate_snapshot_INVALID";
671 BOOST_CHECK(!fs::exists(snapshot_invalid_dir));
672 // chainstate_snapshot should still exist.
673 BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
674
675 // Test that simulating a shutdown (resetting ChainstateManager) and then performing
676 // chainstate reinitializing successfully cleans up the background-validation
677 // chainstate data, and we end up with a single chainstate that is at tip.
678 ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
679
680 BOOST_TEST_MESSAGE("Performing Load/Verify/Activate of chainstate");
681
682 // This call reinitializes the chainstates, and should clean up the now unnecessary
683 // background-validation leveldb contents.
684 this->LoadVerifyActivateChainstate();
685
686 BOOST_CHECK(!fs::exists(snapshot_invalid_dir));
687 // chainstate_snapshot should now *not* exist.
688 BOOST_CHECK(!fs::exists(snapshot_chainstate_dir));
689
690 const Chainstate& active_cs2 = chainman_restarted.ActiveChainstate();
691
692 {
693 LOCK(chainman_restarted.GetMutex());
694 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 1);
696 BOOST_CHECK(active_cs2.m_coinstip_cache_size_bytes > tip_cache_before_complete);
697 BOOST_CHECK(active_cs2.m_coinsdb_cache_size_bytes > db_cache_before_complete);
698
699 BOOST_CHECK_EQUAL(chainman_restarted.ActiveTip()->GetBlockHash(), snapshot_tip_hash);
700 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
701 }
702
703 BOOST_TEST_MESSAGE(
704 "Ensure we can mine blocks on top of the \"new\" IBD chainstate");
705 mineBlocks(10);
706 {
707 LOCK(chainman_restarted.GetMutex());
708 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
709 }
710}
711
712BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_completion_hash_mismatch, SnapshotTestSetup)
713{
714 auto chainstates = this->SetupSnapshot();
715 Chainstate& validation_chainstate = *std::get<0>(chainstates);
716 Chainstate& unvalidated_cs = *std::get<1>(chainstates);
719 m_node.notifications->m_shutdown_on_fatal_error = false;
720
721 // Test tampering with the IBD UTXO set with an extra coin to ensure it causes
722 // snapshot completion to fail.
724 return validation_chainstate.CoinsTip());
725 Coin badcoin;
726 badcoin.out.nValue = m_rng.rand32();
727 badcoin.nHeight = 1;
728 badcoin.out.scriptPubKey.assign(m_rng.randbits(6), 0);
729 Txid txid = Txid::FromUint256(m_rng.rand256());
730 ibd_coins.AddCoin(COutPoint(txid, 0), std::move(badcoin), false);
731
732 fs::path snapshot_chainstate_dir = gArgs.GetDataDirNet() / "chainstate_snapshot";
733 BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
734
735 {
736 ASSERT_DEBUG_LOG("failed to validate the -assumeutxo snapshot state");
737 res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validation_chainstate, unvalidated_cs));
739 }
740
741 {
742 LOCK(chainman.GetMutex());
743 BOOST_CHECK_EQUAL(chainman.m_chainstates.size(), 2);
744 BOOST_CHECK(chainman.m_chainstates[0]->m_assumeutxo == Assumeutxo::VALIDATED);
745 BOOST_CHECK(!chainman.m_chainstates[0]->SnapshotBase());
746 BOOST_CHECK(chainman.m_chainstates[1]->m_assumeutxo == Assumeutxo::INVALID);
747 BOOST_CHECK(chainman.m_chainstates[1]->SnapshotBase());
748 }
749
750 fs::path snapshot_invalid_dir = gArgs.GetDataDirNet() / "chainstate_snapshot_INVALID";
751 BOOST_CHECK(fs::exists(snapshot_invalid_dir));
752
753 // Test that simulating a shutdown (resetting ChainstateManager) and then performing
754 // chainstate reinitializing successfully loads only the fully-validated
755 // chainstate data, and we end up with a single chainstate that is at tip.
756 ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
757
758 BOOST_TEST_MESSAGE("Performing Load/Verify/Activate of chainstate");
759
760 // This call reinitializes the chainstates, and should clean up the now unnecessary
761 // background-validation leveldb contents.
762 this->LoadVerifyActivateChainstate();
763
764 BOOST_CHECK(fs::exists(snapshot_invalid_dir));
765 BOOST_CHECK(!fs::exists(snapshot_chainstate_dir));
766
767 {
769 BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 1);
771 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
772 }
773
774 BOOST_TEST_MESSAGE(
775 "Ensure we can mine blocks on top of the \"new\" IBD chainstate");
776 mineBlocks(10);
777 {
779 BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
780 }
781}
782
784template <typename Options>
786 const std::vector<const char*>& args)
787{
788 const auto argv{Cat({"ignore"}, args)};
789 std::string error{};
790 if (!args_man.ParseParameters(argv.size(), argv.data(), error)) {
791 return util::Error{Untranslated("ParseParameters failed with error: " + error)};
792 }
793 const auto result{node::ApplyArgsManOptions(args_man, opts)};
794 if (!result) return util::Error{util::ErrorString(result)};
795 return opts;
796}
797
799{
801 auto get_opts = [&](const std::vector<const char*>& args) {
802 static kernel::Notifications notifications{};
803 static const ChainstateManager::Options options{
805 .datadir = {},
806 .notifications = notifications};
807 return SetOptsFromArgs(*this->m_node.args, options, args);
808 };
810 auto get_valid_opts = [&](const std::vector<const char*>& args) {
811 const auto result{get_opts(args)};
812 BOOST_REQUIRE_MESSAGE(result, util::ErrorString(result).original);
813 return *result;
814 };
815
816 // test -assumevalid
817 BOOST_CHECK(!get_valid_opts({}).assumed_valid_block);
818 BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid="}).assumed_valid_block, uint256::ZERO);
819 BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid=0"}).assumed_valid_block, uint256::ZERO);
820 BOOST_CHECK_EQUAL(get_valid_opts({"-noassumevalid"}).assumed_valid_block, uint256::ZERO);
821 BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid=0x12"}).assumed_valid_block, uint256{0x12});
822
823 std::string assume_valid{"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"};
824 BOOST_CHECK_EQUAL(get_valid_opts({("-assumevalid=" + assume_valid).c_str()}).assumed_valid_block, uint256::FromHex(assume_valid));
825
826 BOOST_CHECK(!get_opts({"-assumevalid=xyz"})); // invalid hex characters
827 BOOST_CHECK(!get_opts({"-assumevalid=01234567890123456789012345678901234567890123456789012345678901234"})); // > 64 hex chars
828
829 // test -minimumchainwork
830 BOOST_CHECK(!get_valid_opts({}).minimum_chain_work);
831 BOOST_CHECK_EQUAL(get_valid_opts({"-minimumchainwork=0"}).minimum_chain_work, arith_uint256());
832 BOOST_CHECK_EQUAL(get_valid_opts({"-nominimumchainwork"}).minimum_chain_work, arith_uint256());
833 BOOST_CHECK_EQUAL(get_valid_opts({"-minimumchainwork=0x1234"}).minimum_chain_work, arith_uint256{0x1234});
834
835 std::string minimum_chainwork{"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"};
836 BOOST_CHECK_EQUAL(get_valid_opts({("-minimumchainwork=" + minimum_chainwork).c_str()}).minimum_chain_work, UintToArith256(uint256::FromHex(minimum_chainwork).value()));
837
838 BOOST_CHECK(!get_opts({"-minimumchainwork=xyz"})); // invalid hex characters
839 BOOST_CHECK(!get_opts({"-minimumchainwork=01234567890123456789012345678901234567890123456789012345678901234"})); // > 64 hex chars
840}
841
ArgsManager gArgs
Definition: args.cpp:40
arith_uint256 UintToArith256(const uint256 &a)
static void pool cs
node::NodeContext m_node
Definition: bitcoin-gui.cpp:43
ArgsManager & args
Definition: bitcoind.cpp:277
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous.
Definition: chain.h:51
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:113
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: args.cpp:177
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:235
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:371
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:95
uint64_t m_chain_tx_count
(memory only) Number of transactions in the chain up to and including this block.
Definition: chain.h:130
uint256 GetBlockHash() const
Definition: chain.h:199
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:389
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:418
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:361
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:72
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:293
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:166
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
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:545
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:619
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition: validation.h:715
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:680
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition: validation.h:712
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:631
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:677
CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(CoinsCacheSizeState GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes, size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Dictates whether we need to flush the cache to disk or not.
Definition: validation.h:833
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Definition: validation.h:930
Chainstate * HistoricalChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return historical chainstate targeting a specific block, if any.
Definition: validation.h:1118
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:1072
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1022
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1157
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:1109
size_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:1076
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1156
const Options m_options
Definition: validation.h:1025
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:1155
void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1056
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1028
A UTXO entry.
Definition: coins.h:33
CTxOut out
unspent transaction output
Definition: coins.h:36
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:42
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:191
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
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:195
static const uint256 ONE
Definition: uint256.h:204
static const uint256 ZERO
Definition: uint256.h:203
static std::optional< uint256 > FromHex(std::string_view str)
Definition: uint256.h:197
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:95
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_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:330
Basic testing setup.
Definition: setup_common.h:64
Application-specific storage settings.
Definition: dbwrapper.h:33
fs::path path
Location in the filesystem where leveldb data will be stored.
Definition: dbwrapper.h:35
std::tuple< Chainstate *, Chainstate * > SetupSnapshot()
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:146
Testing setup that configures a complete environment.
Definition: setup_common.h:121
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:88
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:72
std::unique_ptr< node::Warnings > warnings
Manages all the node warnings.
Definition: context.h:91
std::function< bool()> shutdown_request
Function to request a shutdown.
Definition: context.h:63
std::unique_ptr< KernelNotifications > notifications
Issues blocking calls about sync status, errors and warnings.
Definition: context.h:86
util::SignalInterrupt * shutdown_signal
Interrupt object used to track whether node shutdown was requested.
Definition: context.h:65
ArgsManager * args
Definition: context.h:74
std::atomic< int > exit_status
Definition: context.h:89
#define LOCK2(cs1, cs2)
Definition: sync.h:260
#define LOCK(cs)
Definition: sync.h:259
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:290
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:33
#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
SnapshotCompletionResult
Definition: validation.h:892
@ 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.
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