LCOV - code coverage report
Current view: top level - src/test - validation_chainstatemanager_tests.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 96.2 % 560 539
Test Date: 2026-08-07 06:33:33 Functions: 100.0 % 72 72
Branches: 51.5 % 2412 1243

             Branch data     Line data    Source code
       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>
       6                 :             : #include <consensus/validation.h>
       7                 :             : #include <kernel/disconnected_transactions.h>
       8                 :             : #include <node/chainstatemanager_args.h>
       9                 :             : #include <node/kernel_notifications.h>
      10                 :             : #include <node/utxo_snapshot.h>
      11                 :             : #include <random.h>
      12                 :             : #include <rpc/blockchain.h>
      13                 :             : #include <sync.h>
      14                 :             : #include <test/util/chainstate.h>
      15                 :             : #include <test/util/common.h>
      16                 :             : #include <test/util/logging.h>
      17                 :             : #include <test/util/random.h>
      18                 :             : #include <test/util/setup_common.h>
      19                 :             : #include <test/util/validation.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                 :             : 
      33                 :             : using node::BlockManager;
      34                 :             : using node::KernelNotifications;
      35                 :             : using node::SnapshotMetadata;
      36                 :             : 
      37                 :             : BOOST_FIXTURE_TEST_SUITE(validation_chainstatemanager_tests, TestingSetup)
      38                 :             : 
      39                 :             : //! Basic tests for ChainstateManager.
      40                 :             : //!
      41                 :             : //! First create a legacy (IBD) chainstate, then create a snapshot chainstate.
      42   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager, TestChain100Setup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
      43                 :             : {
      44                 :           1 :     ChainstateManager& manager = *m_node.chainman;
      45                 :             : 
      46   [ +  -  +  - ]:           3 :     BOOST_CHECK(WITH_LOCK(::cs_main, return !manager.CurrentChainstate().m_from_snapshot_blockhash));
      47                 :             : 
      48                 :             :     // Create a legacy (IBD) chainstate.
      49                 :             :     //
      50                 :           1 :     Chainstate& c1 = manager.ActiveChainstate();
      51                 :             : 
      52   [ +  -  +  - ]:           3 :     BOOST_CHECK(WITH_LOCK(::cs_main, return !manager.CurrentChainstate().m_from_snapshot_blockhash));
      53                 :           1 :     {
      54                 :           1 :         LOCK(manager.GetMutex());
      55   [ +  -  -  +  :           1 :         BOOST_CHECK_EQUAL(manager.m_chainstates.size(), 1);
                   +  - ]
      56   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(manager.m_chainstates[0].get(), &c1);
                   +  - ]
      57                 :           0 :     }
      58                 :             : 
      59   [ +  -  +  - ]:           3 :     auto& active_chain = WITH_LOCK(manager.GetMutex(), return manager.ActiveChain());
      60         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(&active_chain, &c1.m_chain);
      61                 :             : 
      62                 :             :     // Get to a valid assumeutxo tip (per chainparams);
      63                 :           1 :     mineBlocks(10);
      64   [ +  -  +  - ]:           3 :     BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 110);
      65   [ +  -  +  - ]:           3 :     auto active_tip = WITH_LOCK(manager.GetMutex(), return manager.ActiveTip());
      66         [ -  + ]:           1 :     auto exp_tip = c1.m_chain.Tip();
      67         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(active_tip, exp_tip);
      68                 :             : 
      69   [ +  -  +  - ]:           3 :     BOOST_CHECK(WITH_LOCK(::cs_main, return !manager.CurrentChainstate().m_from_snapshot_blockhash));
      70                 :             : 
      71                 :             :     // Create a snapshot-based chainstate.
      72                 :             :     //
      73                 :           1 :     const uint256 snapshot_blockhash = active_tip->GetBlockHash();
      74   [ +  -  +  -  :           3 :     Chainstate& c2{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, snapshot_blockhash)))};
                   +  - ]
      75                 :           1 :     c2.InitCoinsDB(
      76                 :             :         /*cache_size_bytes=*/8_MiB, /*in_memory=*/true, /*should_wipe=*/false);
      77                 :           1 :     {
      78                 :           1 :         LOCK(::cs_main);
      79         [ +  - ]:           1 :         c2.InitCoinsCache(8_MiB);
      80   [ +  -  +  - ]:           1 :         c2.CoinsTip().SetBestBlock(active_tip->GetBlockHash());
      81         [ +  + ]:           3 :         for (const auto& cs : manager.m_chainstates) {
      82         [ +  - ]:           2 :             cs->ClearBlockIndexCandidates();
      83                 :             :         }
      84         [ +  - ]:           1 :         c2.LoadChainTip();
      85         [ +  + ]:           3 :         for (const auto& cs : manager.m_chainstates) {
      86         [ +  - ]:           2 :             cs->PopulateBlockIndexCandidates();
      87                 :             :         }
      88                 :           0 :     }
      89         [ +  - ]:           1 :     BlockValidationState _;
      90   [ +  -  +  -  :           2 :     BOOST_CHECK(c2.ActivateBestChain(_, nullptr));
          +  -  -  +  +  
                      - ]
      91                 :             : 
      92   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return *manager.CurrentChainstate().m_from_snapshot_blockhash), snapshot_blockhash);
                   +  - ]
      93   [ +  -  +  -  :           3 :     BOOST_CHECK(WITH_LOCK(::cs_main, return manager.CurrentChainstate().m_assumeutxo == Assumeutxo::UNVALIDATED));
             +  -  +  - ]
      94   [ +  -  +  -  :           1 :     BOOST_CHECK_EQUAL(&c2, &manager.ActiveChainstate());
                   +  - ]
      95   [ +  -  +  -  :           2 :     BOOST_CHECK(&c1 != &manager.ActiveChainstate());
             +  -  +  - ]
      96                 :           1 :     {
      97         [ +  - ]:           1 :         LOCK(manager.GetMutex());
      98   [ +  -  -  +  :           1 :         BOOST_CHECK_EQUAL(manager.m_chainstates.size(), 2);
                   +  - ]
      99   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(manager.m_chainstates[0].get(), &c1);
     100   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(manager.m_chainstates[1].get(), &c2);
                   +  - ]
     101                 :           0 :     }
     102                 :             : 
     103   [ +  -  +  - ]:           3 :     auto& active_chain2 = WITH_LOCK(manager.GetMutex(), return manager.ActiveChain());
     104   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(&active_chain2, &c2.m_chain);
     105                 :             : 
     106   [ +  -  +  -  :           3 :     BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 110);
                   +  - ]
     107         [ +  - ]:           1 :     mineBlocks(1);
     108   [ +  -  +  -  :           3 :     BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 111);
                   +  - ]
     109   [ +  +  +  -  :           2 :     BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return c1.m_chain.Height()), 110);
                   +  - ]
     110                 :             : 
     111   [ +  -  +  - ]:           3 :     auto active_tip2 = WITH_LOCK(manager.GetMutex(), return manager.ActiveTip());
     112   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(active_tip, active_tip2->pprev);
     113   [ +  -  -  +  :           2 :     BOOST_CHECK_EQUAL(active_tip, c1.m_chain.Tip());
                   +  - ]
     114   [ +  -  -  +  :           2 :     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         [ +  - ]:           1 :     m_node.validation_signals->SyncWithValidationInterfaceQueue();
     118                 :           1 : }
     119                 :             : 
     120   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_delete_chainstate_no_mempool, ChainTestingSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     121                 :             : {
     122         [ -  + ]:           1 :     auto& manager{*Assert(m_node.chainman)};
     123   [ +  -  +  - ]:           3 :     auto& validated{WITH_LOCK(::cs_main, return manager.InitializeChainstate(/*mempool=*/nullptr))};
     124   [ +  -  +  -  :           3 :     auto& snapshot{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, uint256::ONE)))};
                   +  - ]
     125         [ +  - ]:           3 :     WITH_LOCK(::cs_main, validated.SetTargetBlock(nullptr));
     126   [ +  -  +  - ]:           4 :     BOOST_CHECK(WITH_LOCK(::cs_main, return manager.DeleteChainstate(snapshot))); // Accept Kernel's null mempool
     127                 :           1 : }
     128                 :             : 
     129                 :             : //! Test rebalancing the caches associated with each chainstate.
     130   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_rebalance_caches, TestChain100Setup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     131                 :             : {
     132         [ +  - ]:           1 :     ChainstateManager& manager = *m_node.chainman;
     133                 :             : 
     134                 :           1 :     size_t max_cache = 10000;
     135                 :           1 :     manager.m_total_coinsdb_cache = max_cache;
     136                 :           1 :     manager.m_total_coinstip_cache = max_cache;
     137                 :             : 
     138                 :           1 :     std::vector<Chainstate*> chainstates;
     139                 :             : 
     140                 :             :     // Create a legacy (IBD) chainstate.
     141                 :             :     //
     142         [ +  - ]:           1 :     Chainstate& c1 = manager.ActiveChainstate();
     143         [ +  - ]:           1 :     chainstates.push_back(&c1);
     144                 :           1 :     {
     145         [ +  - ]:           1 :         LOCK(::cs_main);
     146         [ +  - ]:           1 :         c1.InitCoinsCache(8_MiB);
     147         [ +  - ]:           1 :         manager.MaybeRebalanceCaches();
     148                 :           0 :     }
     149                 :             : 
     150   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(c1.m_coinstip_cache_size_bytes, max_cache);
     151   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(c1.m_coinsdb_cache_size_bytes, max_cache);
     152                 :             : 
     153                 :             :     // Create a snapshot-based chainstate.
     154                 :             :     //
     155   [ +  -  +  -  :           4 :     CBlockIndex* snapshot_base{WITH_LOCK(manager.GetMutex(), return manager.ActiveChain()[manager.ActiveChain().Height() / 2])};
          -  +  +  -  +  
                      - ]
     156   [ +  -  +  -  :           3 :     Chainstate& c2{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, *snapshot_base->phashBlock)))};
                   +  - ]
     157         [ +  - ]:           1 :     chainstates.push_back(&c2);
     158         [ +  - ]:           1 :     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         [ +  - ]:           1 :     static_cast<TestChainstateManager&>(manager).ResetIbd();
     169                 :             : 
     170                 :           1 :     {
     171         [ +  - ]:           1 :         LOCK(::cs_main);
     172         [ +  - ]:           1 :         c2.InitCoinsCache(8_MiB);
     173         [ +  - ]:           1 :         manager.MaybeRebalanceCaches();
     174                 :           0 :     }
     175                 :             : 
     176   [ +  -  +  - ]:           1 :     BOOST_CHECK_CLOSE(double(c1.m_coinstip_cache_size_bytes), max_cache * 0.05, 1);
     177   [ +  -  +  - ]:           1 :     BOOST_CHECK_CLOSE(double(c1.m_coinsdb_cache_size_bytes), max_cache * 0.05, 1);
     178   [ +  -  +  - ]:           1 :     BOOST_CHECK_CLOSE(double(c2.m_coinstip_cache_size_bytes), max_cache * 0.95, 1);
     179   [ +  -  +  - ]:           1 :     BOOST_CHECK_CLOSE(double(c2.m_coinsdb_cache_size_bytes), max_cache * 0.95, 1);
     180                 :           1 : }
     181                 :             : 
     182   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_ibd_exit_after_loading_blocks, ChainTestingSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     183                 :             : {
     184                 :           1 :     CBlockIndex tip;
     185         [ -  + ]:           1 :     ChainstateManager& chainman{*Assert(m_node.chainman)};
     186                 :          33 :     auto apply{[&](bool cached_is_ibd, bool loading_blocks, bool tip_exists, bool enough_work, bool tip_recent) {
     187                 :          32 :         LOCK(::cs_main);
     188         [ +  - ]:          32 :         chainman.ResetChainstates();
     189         [ +  - ]:          32 :         chainman.InitializeChainstate(m_node.mempool.get());
     190                 :             : 
     191                 :          32 :         const auto recent_time{Now<NodeSeconds>() - chainman.m_options.max_tip_age};
     192                 :             : 
     193         [ +  + ]:          32 :         chainman.m_cached_is_ibd.store(cached_is_ibd, std::memory_order_relaxed);
     194         [ +  + ]:          32 :         chainman.m_blockman.m_importing = loading_blocks;
     195         [ +  + ]:          32 :         if (tip_exists) {
     196   [ +  +  +  -  :          32 :             tip.nChainWork = chainman.MinimumChainWork() - (enough_work ? 0 : 1);
                   +  + ]
     197   [ +  +  +  - ]:          16 :             tip.nTime = (recent_time - (tip_recent ? 0h : 100h)).time_since_epoch().count();
     198   [ +  -  +  - ]:          16 :             chainman.ActiveChain().SetTip(tip);
     199                 :             :         } else {
     200   [ +  -  -  +  :          16 :             assert(!chainman.ActiveChain().Tip());
                   -  - ]
     201                 :             :         }
     202         [ +  - ]:          32 :         chainman.UpdateIBDStatus();
     203                 :          33 :     }};
     204                 :             : 
     205         [ +  + ]:           3 :     for (const bool cached_is_ibd : {false, true}) {
     206         [ +  + ]:           6 :         for (const bool loading_blocks : {false, true}) {
     207         [ +  + ]:          12 :             for (const bool tip_exists : {false, true}) {
     208         [ +  + ]:          24 :                 for (const bool enough_work : {false, true}) {
     209         [ +  + ]:          48 :                     for (const bool tip_recent : {false, true}) {
     210                 :          32 :                         apply(cached_is_ibd, loading_blocks, tip_exists, enough_work, tip_recent);
     211   [ +  +  +  +  :          32 :                         const bool expected_ibd = cached_is_ibd && (loading_blocks || !tip_exists || !enough_work || !tip_recent);
                   +  + ]
     212         [ +  - ]:          32 :                         BOOST_CHECK_EQUAL(chainman.IsInitialBlockDownload(), expected_ibd);
     213                 :             :                     }
     214                 :             :                 }
     215                 :             :             }
     216                 :             :         }
     217                 :             :     }
     218                 :           1 : }
     219                 :             : 
     220                 :           8 : struct SnapshotTestSetup : TestChain100Setup {
     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.
     227                 :           4 :     SnapshotTestSetup() : TestChain100Setup{
     228                 :             :                               {},
     229                 :             :                               {
     230                 :             :                                   .coins_db_in_memory = false,
     231                 :             :                                   .block_tree_db_in_memory = false,
     232                 :             :                               },
     233         [ +  - ]:           4 :                           }
     234                 :             :     {
     235                 :           4 :     }
     236                 :             : 
     237                 :           4 :     std::tuple<Chainstate*, Chainstate*> SetupSnapshot()
     238                 :             :     {
     239         [ -  + ]:           4 :         ChainstateManager& chainman = *Assert(m_node.chainman);
     240                 :             : 
     241                 :           4 :         {
     242                 :           4 :             LOCK(::cs_main);
     243   [ +  -  +  -  :           8 :             BOOST_CHECK(!chainman.CurrentChainstate().m_from_snapshot_blockhash);
                   +  - ]
     244   [ +  -  +  -  :          12 :             BOOST_CHECK(!node::FindAssumeutxoChainstateDir(chainman.m_options.datadir));
          +  -  -  +  +  
                      - ]
     245                 :           0 :         }
     246                 :             : 
     247                 :           4 :         size_t initial_size;
     248                 :           4 :         size_t initial_total_coins{100};
     249                 :             : 
     250                 :             :         // Make some initial assertions about the contents of the chainstate.
     251                 :           4 :         {
     252                 :           4 :             LOCK(::cs_main);
     253   [ +  -  +  - ]:           4 :             CCoinsViewCache& ibd_coinscache = chainman.ActiveChainstate().CoinsTip();
     254         [ +  - ]:           4 :             initial_size = ibd_coinscache.GetCacheSize();
     255                 :           4 :             size_t total_coins{0};
     256                 :             : 
     257         [ +  + ]:         404 :             for (CTransactionRef& txn : m_coinbase_txns) {
     258         [ +  - ]:         400 :                 COutPoint op{txn->GetHash(), 0};
     259   [ +  -  +  -  :         800 :                 BOOST_CHECK(ibd_coinscache.HaveCoin(op));
                   +  - ]
     260                 :         400 :                 total_coins++;
     261                 :             :             }
     262                 :             : 
     263   [ +  -  +  - ]:           4 :             BOOST_CHECK_EQUAL(total_coins, initial_total_coins);
     264   [ +  -  +  -  :           4 :             BOOST_CHECK_EQUAL(initial_size, initial_total_coins);
                   +  - ]
     265                 :           0 :         }
     266                 :             : 
     267                 :           4 :         Chainstate& validation_chainstate = chainman.ActiveChainstate();
     268                 :             : 
     269                 :             :         // Snapshot should refuse to load at this height.
     270   [ +  -  +  - ]:           8 :         BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(this));
     271   [ +  -  +  - ]:           8 :         BOOST_CHECK(!chainman.ActiveChainstate().m_from_snapshot_blockhash);
     272                 :             : 
     273                 :             :         // Mine 10 more blocks, putting at us height 110 where a valid assumeutxo value can
     274                 :             :         // be found.
     275                 :           4 :         constexpr int snapshot_height = 110;
     276                 :           4 :         mineBlocks(10);
     277                 :           4 :         initial_size += 10;
     278                 :           4 :         initial_total_coins += 10;
     279                 :             : 
     280                 :             :         // Should not load malleated snapshots
     281   [ +  -  +  -  :          16 :         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                 :             : 
     296   [ +  -  +  -  :          12 :         BOOST_CHECK(!node::FindAssumeutxoChainstateDir(chainman.m_options.datadir));
                   -  + ]
     297                 :             : 
     298   [ -  +  +  -  :          12 :         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   [ -  +  +  -  :          12 :         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   [ -  +  +  -  :          12 :         BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
                   +  - ]
     309                 :             :             this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
     310                 :             :                 // Wrong hash
     311                 :             :                 metadata.m_base_blockhash = uint256::ZERO;
     312                 :             :         }));
     313   [ -  +  +  -  :          12 :         BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
                   +  - ]
     314                 :             :             this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
     315                 :             :                 // Wrong hash
     316                 :             :                 metadata.m_base_blockhash = uint256::ONE;
     317                 :             :         }));
     318                 :             : 
     319   [ +  -  +  - ]:           8 :         BOOST_REQUIRE(CreateAndActivateUTXOSnapshot(this));
     320   [ +  -  +  -  :          12 :         BOOST_CHECK(fs::exists(*node::FindAssumeutxoChainstateDir(chainman.m_options.datadir)));
             +  -  +  - ]
     321                 :             : 
     322                 :             :         // Ensure our active chain is the snapshot chainstate.
     323   [ +  -  +  - ]:          12 :         BOOST_CHECK(!chainman.ActiveChainstate().m_from_snapshot_blockhash->IsNull());
     324                 :             : 
     325                 :           4 :         Chainstate& snapshot_chainstate = chainman.ActiveChainstate();
     326                 :             : 
     327                 :           4 :         {
     328                 :           4 :             LOCK(::cs_main);
     329                 :             : 
     330   [ +  -  +  - ]:           4 :             fs::path found = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
     331                 :             : 
     332                 :             :             // Note: WriteSnapshotBaseBlockhash() is implicitly tested above.
     333   [ +  -  -  +  :           8 :             BOOST_CHECK_EQUAL(
          +  -  +  -  +  
                      - ]
     334                 :             :                 *node::ReadSnapshotBaseBlockhash(found),
     335                 :             :                 *Assert(chainman.CurrentChainstate().m_from_snapshot_blockhash));
     336         [ +  - ]:           4 :         }
     337                 :             : 
     338                 :           4 :         const auto& au_data = ::Params().AssumeutxoForHeight(snapshot_height);
     339   [ +  -  +  - ]:          12 :         const CBlockIndex* tip = WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip());
     340                 :             : 
     341         [ +  - ]:           4 :         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   [ -  +  +  - ]:           8 :         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                 :           4 :         {
     350                 :           4 :             LOCK(::cs_main);
     351                 :           4 :             int chains_tested{0};
     352                 :             : 
     353         [ +  + ]:          12 :             for (const auto& chainstate : chainman.m_chainstates) {
     354   [ +  -  +  -  :           8 :                 BOOST_TEST_MESSAGE("Checking coins in " << chainstate->ToString());
             +  -  +  - ]
     355         [ +  - ]:           8 :                 CCoinsViewCache& coinscache = chainstate->CoinsTip();
     356                 :             : 
     357                 :             :                 // Both caches will be empty initially.
     358   [ +  -  +  -  :           8 :                 BOOST_CHECK_EQUAL((unsigned int)0, coinscache.GetCacheSize());
                   +  - ]
     359                 :             : 
     360                 :           8 :                 size_t total_coins{0};
     361                 :             : 
     362         [ +  + ]:         888 :                 for (CTransactionRef& txn : m_coinbase_txns) {
     363         [ +  - ]:         880 :                     COutPoint op{txn->GetHash(), 0};
     364   [ +  -  +  -  :        1760 :                     BOOST_CHECK(coinscache.HaveCoin(op));
                   +  - ]
     365                 :         880 :                     total_coins++;
     366                 :             :                 }
     367                 :             : 
     368   [ +  -  +  -  :           8 :                 BOOST_CHECK_EQUAL(initial_size , coinscache.GetCacheSize());
                   +  - ]
     369   [ +  -  +  - ]:           8 :                 BOOST_CHECK_EQUAL(total_coins, initial_total_coins);
     370                 :           8 :                 chains_tested++;
     371                 :             :             }
     372                 :             : 
     373   [ +  -  +  -  :           4 :             BOOST_CHECK_EQUAL(chains_tested, 2);
                   +  - ]
     374                 :           0 :         }
     375                 :             : 
     376                 :             :         // Mine some new blocks on top of the activated snapshot chainstate.
     377                 :           4 :         constexpr size_t new_coins{100};
     378                 :           4 :         mineBlocks(new_coins);  // Defined in TestChain100Setup.
     379                 :             : 
     380                 :           4 :         {
     381                 :           4 :             LOCK(::cs_main);
     382                 :           4 :             size_t coins_in_active{0};
     383                 :           4 :             size_t coins_in_background{0};
     384                 :           4 :             size_t coins_missing_from_background{0};
     385                 :             : 
     386         [ +  + ]:          12 :             for (const auto& chainstate : chainman.m_chainstates) {
     387   [ +  -  +  -  :           8 :                 BOOST_TEST_MESSAGE("Checking coins in " << chainstate->ToString());
             +  -  +  - ]
     388         [ +  - ]:           8 :                 CCoinsViewCache& coinscache = chainstate->CoinsTip();
     389         [ +  - ]:           8 :                 bool is_background = chainstate.get() != &chainman.ActiveChainstate();
     390                 :             : 
     391         [ +  + ]:        1688 :                 for (CTransactionRef& txn : m_coinbase_txns) {
     392         [ +  - ]:        1680 :                     COutPoint op{txn->GetHash(), 0};
     393   [ +  -  +  + ]:        1680 :                     if (coinscache.HaveCoin(op)) {
     394         [ +  + ]:        1280 :                         (is_background ? coins_in_background : coins_in_active)++;
     395         [ +  - ]:         400 :                     } else if (is_background) {
     396                 :         400 :                         coins_missing_from_background++;
     397                 :             :                     }
     398                 :             :                 }
     399                 :             :             }
     400                 :             : 
     401   [ +  -  +  - ]:           4 :             BOOST_CHECK_EQUAL(coins_in_active, initial_total_coins + new_coins);
     402   [ +  -  +  - ]:           4 :             BOOST_CHECK_EQUAL(coins_in_background, initial_total_coins);
     403   [ +  -  +  -  :           4 :             BOOST_CHECK_EQUAL(coins_missing_from_background, new_coins);
                   +  - ]
     404                 :           0 :         }
     405                 :             : 
     406                 :             :         // Snapshot should refuse to load after one has already loaded.
     407   [ +  -  +  - ]:           8 :         BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(this));
     408                 :             : 
     409                 :             :         // Snapshot blockhash should be unchanged.
     410         [ +  - ]:           4 :         BOOST_CHECK_EQUAL(
     411                 :             :             *chainman.ActiveChainstate().m_from_snapshot_blockhash,
     412                 :             :             loaded_snapshot_blockhash);
     413                 :           4 :         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
     420                 :           3 :     ChainstateManager& SimulateNodeRestart()
     421                 :             :     {
     422         [ -  + ]:           3 :         ChainstateManager& chainman = *Assert(m_node.chainman);
     423                 :             : 
     424         [ +  - ]:           3 :         BOOST_TEST_MESSAGE("Simulating node restart");
     425                 :           3 :         {
     426                 :           3 :             LOCK(chainman.GetMutex());
     427         [ +  + ]:           9 :             for (const auto& cs : chainman.m_chainstates) {
     428   [ +  +  +  - ]:          11 :                 if (cs->CanFlushToDisk()) cs->ForceFlushStateToDisk();
     429                 :             :             }
     430                 :           0 :         }
     431                 :           3 :         {
     432                 :             :             // Process all callbacks referring to the old manager before wiping it.
     433                 :           3 :             m_node.validation_signals->SyncWithValidationInterfaceQueue();
     434                 :           3 :             LOCK(::cs_main);
     435         [ +  - ]:           3 :             chainman.ResetChainstates();
     436   [ +  -  -  +  :           3 :             BOOST_CHECK_EQUAL(chainman.m_chainstates.size(), 0);
                   +  - ]
     437   [ -  +  -  +  :           3 :             m_node.notifications = std::make_unique<KernelNotifications>(Assert(m_node.shutdown_request), m_node.exit_status, *Assert(m_node.warnings));
                   +  - ]
     438                 :           3 :             const ChainstateManager::Options chainman_opts{
     439         [ +  - ]:           3 :                 .chainparams = ::Params(),
     440                 :           3 :                 .datadir = chainman.m_options.datadir,
     441                 :           3 :                 .notifications = *m_node.notifications,
     442                 :           3 :                 .signals = m_node.validation_signals.get(),
     443   [ +  -  +  - ]:           3 :             };
     444                 :           3 :             const BlockManager::Options blockman_opts{
     445                 :           3 :                 .chainparams = chainman_opts.chainparams,
     446                 :             :                 .blocks_dir = m_args.GetBlocksDirPath(),
     447                 :           3 :                 .notifications = chainman_opts.notifications,
     448                 :             :                 .block_tree_db_params = DBParams{
     449   [ +  -  +  - ]:           9 :                     .path = chainman.m_options.datadir / "blocks" / "index",
     450                 :           3 :                     .cache_bytes = m_kernel_cache_sizes.block_tree_db,
     451                 :           3 :                     .memory_only = m_block_tree_db_in_memory,
     452                 :             :                 },
     453   [ +  -  +  - ]:           6 :             };
     454                 :             :             // For robustness, ensure the old manager is destroyed before creating a
     455                 :             :             // new one.
     456         [ +  - ]:           3 :             m_node.chainman.reset();
     457   [ -  +  +  - ]:           3 :             m_node.chainman = std::make_unique<ChainstateManager>(*Assert(m_node.shutdown_signal), chainman_opts, blockman_opts);
     458         [ +  - ]:           6 :         }
     459         [ -  + ]:           3 :         return *Assert(m_node.chainman);
     460                 :             :     }
     461                 :             : };
     462                 :             : 
     463                 :             : //! Test basic snapshot activation.
     464   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_activate_snapshot, SnapshotTestSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     465                 :             : {
     466                 :           1 :     this->SetupSnapshot();
     467                 :           1 : }
     468                 :             : 
     469                 :             : //! Test LoadBlockIndex behavior when multiple chainstates are in use.
     470                 :             : //!
     471                 :             : //! - First, verify that setBlockIndexCandidates is as expected when using a single,
     472                 :             : //!   fully-validating chainstate.
     473                 :             : //!
     474                 :             : //! - Then mark a region of the chain as missing data and introduce a second chainstate
     475                 :             : //!   that will tolerate assumed-valid blocks. Run LoadBlockIndex() and ensure that the first
     476                 :             : //!   chainstate only contains fully validated blocks and the other chainstate contains all blocks,
     477                 :             : //!   except those marked assume-valid, because those entries don't HAVE_DATA.
     478                 :             : //!
     479   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_loadblockindex, TestChain100Setup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     480                 :             : {
     481         [ -  + ]:           1 :     ChainstateManager& chainman = *Assert(m_node.chainman);
     482                 :           1 :     Chainstate& cs1 = chainman.ActiveChainstate();
     483                 :             : 
     484                 :           1 :     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                 :           1 :     const int expected_assumed_valid{20};
     488                 :           1 :     const int last_assumed_valid_idx{111};
     489                 :           1 :     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                 :           1 :     mineBlocks(20);
     494                 :             : 
     495                 :           1 :     CBlockIndex* validated_tip{nullptr};
     496                 :           1 :     CBlockIndex* assumed_base{nullptr};
     497   [ +  -  -  +  :           4 :     CBlockIndex* assumed_tip{WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip())};
                   +  - ]
     498         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(assumed_tip->nHeight, 120);
     499                 :             : 
     500                 :           3 :     auto reload_all_block_indexes = [&]() {
     501                 :           2 :         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).
     505                 :           2 :         chainman.ResetBlockSequenceCounters();
     506         [ +  + ]:           5 :         for (const auto& cs : chainman.m_chainstates) {
     507         [ +  - ]:           3 :             cs->ClearBlockIndexCandidates();
     508   [ +  -  +  - ]:           6 :             BOOST_CHECK(cs->setBlockIndexCandidates.empty());
     509                 :             :         }
     510         [ +  - ]:           2 :         chainman.LoadBlockIndex();
     511         [ +  + ]:           5 :         for (const auto& cs : chainman.m_chainstates) {
     512         [ +  - ]:           3 :             cs->PopulateBlockIndexCandidates();
     513                 :             :         }
     514                 :           3 :     };
     515                 :             : 
     516                 :             :     // Ensure that without any assumed-valid BlockIndex entries, only the current tip is
     517                 :             :     // considered as a candidate.
     518                 :           1 :     reload_all_block_indexes();
     519         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(cs1.setBlockIndexCandidates.size(), 1);
     520                 :             : 
     521                 :             :     // Reset some region of the chain's nStatus, removing the HAVE_DATA flag.
     522   [ -  +  +  + ]:         122 :     for (int i = 0; i <= cs1.m_chain.Height(); ++i) {
     523                 :         121 :         LOCK(::cs_main);
     524         [ +  - ]:         121 :         auto index = cs1.m_chain[i];
     525                 :             : 
     526                 :             :         // Blocks with heights in range [91, 110] are marked as missing data.
     527         [ +  + ]:         121 :         if (i < last_assumed_valid_idx && i >= assumed_valid_start_idx) {
     528                 :          20 :             index->nStatus = BlockStatus::BLOCK_VALID_TREE;
     529                 :          20 :             index->nTx = 0;
     530                 :          20 :             index->m_chain_tx_count = 0;
     531                 :             :         }
     532                 :             : 
     533                 :         121 :         ++num_indexes;
     534                 :             : 
     535                 :             :         // Note the last fully-validated block as the expected validated tip.
     536         [ +  + ]:         121 :         if (i == (assumed_valid_start_idx - 1)) {
     537                 :           1 :             validated_tip = index;
     538                 :             :         }
     539                 :             :         // Note the last assumed valid block as the snapshot base
     540         [ +  + ]:         121 :         if (i == last_assumed_valid_idx - 1) {
     541                 :           1 :             assumed_base = index;
     542                 :             :         }
     543                 :         121 :     }
     544                 :             : 
     545                 :             :     // Note: cs2's tip is not set when ActivateExistingSnapshot is called.
     546   [ +  -  +  -  :           3 :     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                 :           1 :     cs1.m_chain.SetTip(*validated_tip);
     550                 :             : 
     551                 :             :     // Set tip of the assume-valid-based chain to the assume-valid block
     552                 :           1 :     cs2.m_chain.SetTip(*assumed_base);
     553                 :             : 
     554                 :             :     // Sanity check test variables.
     555         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(num_indexes, 121); // 121 total blocks, including genesis
     556         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(assumed_tip->nHeight, 120);  // original chain has height 120
     557         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(validated_tip->nHeight, 90); // current cs1 chain has height 90
     558         [ +  - ]:           1 :     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                 :           1 :     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.
     578         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(cs1.setBlockIndexCandidates.size(), 1);
     579         [ +  - ]:           1 :     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         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(validated_tip), 0);
     596                 :             :     // Check that block 109 is absent
     597         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_base->pprev), 0);
     598                 :             :     // Check that block 110 is present
     599         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_base), 1);
     600                 :             :     // Check that block 120 is present
     601         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_tip), 1);
     602                 :             :     // Check that 11 blocks total are present.
     603         [ +  - ]:           1 :     BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.size(), num_indexes - last_assumed_valid_idx + 1);
     604                 :           1 : }
     605                 :             : 
     606   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(loadblockindex_invalid_descendants, TestChain100Setup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     607                 :             : {
     608         [ -  + ]:           1 :     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   [ +  -  -  + ]:           1 :     auto* child{m_node.chainman->ActiveChain().Tip()};
     616                 :           1 :     auto* parent{child->pprev};
     617                 :           1 :     auto* grand_parent{parent->pprev};
     618                 :           1 :     grand_parent->nStatus = (grand_parent->nStatus | BLOCK_FAILED_VALID);
     619                 :           1 :     parent->nStatus = (parent->nStatus & ~BLOCK_FAILED_VALID) | BLOCK_FAILED_CHILD;
     620                 :           1 :     child->nStatus = (child->nStatus & ~BLOCK_FAILED_VALID);
     621                 :             : 
     622                 :             :     // Reload block index to recompute block status validity flags.
     623         [ +  - ]:           1 :     m_node.chainman->LoadBlockIndex();
     624                 :             : 
     625                 :             :     // check grand_parent, parent, child is marked as BLOCK_FAILED_VALID after reloading the block index
     626   [ +  -  +  -  :           2 :     BOOST_CHECK(grand_parent->nStatus & BLOCK_FAILED_VALID);
                   +  - ]
     627   [ +  -  +  -  :           2 :     BOOST_CHECK(parent->nStatus & BLOCK_FAILED_VALID);
                   +  - ]
     628   [ +  -  +  -  :           2 :     BOOST_CHECK(child->nStatus & BLOCK_FAILED_VALID);
                   +  - ]
     629                 :           1 : }
     630                 :             : 
     631                 :             : //! Verify that ReconsiderBlock clears failure flags for the target block, its ancestors, and descendants,
     632                 :             : //! but not for sibling forks that diverge from a shared ancestor.
     633   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(invalidate_block_and_reconsider_fork, TestChain100Setup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     634                 :             : {
     635         [ -  + ]:           1 :     ChainstateManager& chainman = *Assert(m_node.chainman);
     636                 :           1 :     Chainstate& chainstate = chainman.ActiveChainstate();
     637                 :             : 
     638                 :             :     // we have a chain of 100 blocks: genesis(0) <- ... <- block98 <- block99 <- block100
     639                 :           1 :     CBlockIndex* block98;
     640                 :           1 :     CBlockIndex* block99;
     641                 :           1 :     CBlockIndex* block100;
     642                 :           1 :     {
     643                 :           1 :         LOCK(chainman.GetMutex());
     644   [ +  -  -  + ]:           1 :         block98 = chainman.ActiveChain()[98];
     645   [ +  -  -  + ]:           1 :         block99 = chainman.ActiveChain()[99];
     646   [ +  -  -  +  :           2 :         block100 = chainman.ActiveChain()[100];
                   +  - ]
     647                 :           0 :     }
     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.
     654         [ +  - ]:           1 :     BlockValidationState state;
     655   [ +  -  +  -  :           2 :     BOOST_REQUIRE(chainstate.InvalidateBlock(state, block99));
             +  -  +  - ]
     656   [ +  -  +  +  :           5 :     BOOST_REQUIRE(WITH_LOCK(cs_main, return chainman.ActiveChain().Tip()) == block98);
             +  -  +  - ]
     657   [ +  -  +  -  :           2 :     CScript coinbase_script = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
                   +  - ]
     658         [ +  + ]:           3 :     for (int i = 0; i < 2; ++i) {
     659         [ +  - ]:           4 :         CreateAndProcessBlock({}, coinbase_script);
     660                 :             :     }
     661                 :           1 :     const CBlockIndex* fork_block99;
     662                 :           1 :     const CBlockIndex* fork_block100;
     663                 :           1 :     {
     664         [ +  - ]:           1 :         LOCK(chainman.GetMutex());
     665   [ +  -  -  + ]:           1 :         fork_block99 = chainman.ActiveChain()[99];
     666   [ +  -  +  -  :           2 :         BOOST_REQUIRE(fork_block99->pprev == block98);
                   +  - ]
     667   [ +  -  -  + ]:           1 :         fork_block100 = chainman.ActiveChain()[100];
     668   [ +  -  +  -  :           2 :         BOOST_REQUIRE(fork_block100->pprev == fork_block99);
                   +  - ]
     669                 :           0 :     }
     670                 :             :     // Restore original block99 and block100
     671                 :           1 :     {
     672         [ +  - ]:           1 :         LOCK(chainman.GetMutex());
     673         [ +  - ]:           1 :         chainstate.ResetBlockFailureFlags(block99);
     674         [ +  - ]:           1 :         chainman.RecalculateBestHeader();
     675                 :           0 :     }
     676         [ +  - ]:           1 :     chainstate.ActivateBestChain(state);
     677   [ +  -  +  +  :           5 :     BOOST_REQUIRE(WITH_LOCK(cs_main, return chainman.ActiveChain().Tip()) == block100);
             +  -  +  - ]
     678                 :             : 
     679                 :           1 :     {
     680         [ +  - ]:           1 :         LOCK(chainman.GetMutex());
     681   [ +  -  +  -  :           2 :         BOOST_CHECK(!(block100->nStatus & BLOCK_FAILED_VALID));
                   +  - ]
     682   [ +  -  +  -  :           2 :         BOOST_CHECK(!(block99->nStatus & BLOCK_FAILED_VALID));
                   +  - ]
     683   [ +  -  +  -  :           2 :         BOOST_CHECK(!(fork_block100->nStatus & BLOCK_FAILED_VALID));
                   +  - ]
     684   [ +  -  +  -  :           2 :         BOOST_CHECK(!(fork_block99->nStatus & BLOCK_FAILED_VALID));
                   +  - ]
     685                 :           0 :     }
     686                 :             : 
     687                 :             :     // Invalidate block98
     688   [ +  -  +  -  :           2 :     BOOST_REQUIRE(chainstate.InvalidateBlock(state, block98));
             +  -  +  - ]
     689                 :             : 
     690                 :           1 :     {
     691         [ +  - ]:           1 :         LOCK(chainman.GetMutex());
     692                 :             :         // block98 and all descendants of block98 are marked BLOCK_FAILED_VALID
     693   [ +  -  +  -  :           2 :         BOOST_CHECK(block98->nStatus & BLOCK_FAILED_VALID);
                   +  - ]
     694   [ +  -  +  -  :           2 :         BOOST_CHECK(block99->nStatus & BLOCK_FAILED_VALID);
                   +  - ]
     695   [ +  -  +  -  :           2 :         BOOST_CHECK(block100->nStatus & BLOCK_FAILED_VALID);
                   +  - ]
     696   [ +  -  +  -  :           2 :         BOOST_CHECK(fork_block99->nStatus & BLOCK_FAILED_VALID);
                   +  - ]
     697   [ +  -  +  -  :           2 :         BOOST_CHECK(fork_block100->nStatus & BLOCK_FAILED_VALID);
                   +  - ]
     698                 :           0 :     }
     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                 :           1 :     {
     704         [ +  - ]:           1 :         LOCK(chainman.GetMutex());
     705         [ +  - ]:           1 :         chainstate.ResetBlockFailureFlags(block99);
     706         [ +  - ]:           1 :         chainman.RecalculateBestHeader();
     707                 :           0 :     }
     708         [ +  - ]:           1 :     chainstate.ActivateBestChain(state);
     709                 :           1 :     {
     710         [ +  - ]:           1 :         LOCK(chainman.GetMutex());
     711   [ +  -  +  -  :           2 :         BOOST_CHECK(!(block98->nStatus & BLOCK_FAILED_VALID));
                   +  - ]
     712   [ +  -  +  -  :           2 :         BOOST_CHECK(!(block99->nStatus & BLOCK_FAILED_VALID));
                   +  - ]
     713   [ +  -  +  -  :           2 :         BOOST_CHECK(!(block100->nStatus & BLOCK_FAILED_VALID));
                   +  - ]
     714   [ +  -  +  -  :           2 :         BOOST_CHECK(fork_block99->nStatus & BLOCK_FAILED_VALID);
                   +  - ]
     715   [ +  -  +  -  :           2 :         BOOST_CHECK(fork_block100->nStatus & BLOCK_FAILED_VALID);
                   +  - ]
     716                 :           1 :     }
     717                 :           2 : }
     718                 :             : 
     719                 :             : //! Ensure that snapshot chainstate can be loaded when found on disk after a
     720                 :             : //! restart, and that new blocks can be connected to both chainstates.
     721   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_init, SnapshotTestSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     722                 :             : {
     723         [ -  + ]:           1 :     ChainstateManager& chainman = *Assert(m_node.chainman);
     724                 :           1 :     Chainstate& bg_chainstate = chainman.ActiveChainstate();
     725                 :             : 
     726                 :           1 :     this->SetupSnapshot();
     727                 :             : 
     728         [ +  - ]:           1 :     fs::path snapshot_chainstate_dir = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
     729   [ +  -  +  -  :           2 :     BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
             +  -  +  - ]
     730   [ +  -  +  -  :           3 :     BOOST_CHECK_EQUAL(snapshot_chainstate_dir, gArgs.GetDataDirNet() / "chainstate_snapshot");
                   +  - ]
     731                 :             : 
     732   [ +  -  +  -  :           3 :     BOOST_CHECK(WITH_LOCK(::cs_main, return chainman.CurrentChainstate().m_from_snapshot_blockhash));
             +  -  +  - ]
     733   [ +  -  +  - ]:           3 :     const uint256 snapshot_tip_hash = WITH_LOCK(chainman.GetMutex(),
     734                 :             :         return chainman.ActiveTip()->GetBlockHash());
     735                 :             : 
     736   [ +  +  +  -  :           2 :     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().
     743         [ +  - ]:           1 :     DisconnectedBlockTransactions unused_pool{MAX_DISCONNECTED_TX_POOL_BYTES};
     744         [ +  - ]:           1 :     BlockValidationState unused_state;
     745                 :           1 :     {
     746   [ +  -  -  +  :           1 :         LOCK2(::cs_main, bg_chainstate.MempoolMutex());
                   +  - ]
     747   [ +  -  +  -  :           2 :         BOOST_CHECK(bg_chainstate.DisconnectTip(unused_state, &unused_pool));
             +  -  +  - ]
     748         [ +  - ]:           1 :         unused_pool.clear();  // to avoid queuedTx assertion errors on teardown
     749         [ +  - ]:           1 :     }
     750   [ +  -  -  +  :           1 :     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         [ +  - ]:           1 :     ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
     755                 :             : 
     756   [ +  -  +  -  :           1 :     BOOST_TEST_MESSAGE("Performing Load/Verify/Activate of chainstate");
                   +  - ]
     757                 :             : 
     758                 :             :     // This call reinitializes the chainstates.
     759         [ +  - ]:           1 :     this->LoadVerifyActivateChainstate();
     760                 :             : 
     761                 :           1 :     {
     762         [ +  - ]:           1 :         LOCK(chainman_restarted.GetMutex());
     763   [ +  -  -  +  :           1 :         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   [ +  -  -  +  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[0]->m_chain.Height(), 109);
                   +  - ]
     769   [ +  -  -  +  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[1]->m_chain.Height(), 210);
                   +  - ]
     770                 :             : 
     771   [ +  -  +  -  :           2 :         BOOST_CHECK(chainman_restarted.CurrentChainstate().m_from_snapshot_blockhash);
                   +  - ]
     772   [ +  -  +  -  :           2 :         BOOST_CHECK(chainman_restarted.CurrentChainstate().m_assumeutxo == Assumeutxo::UNVALIDATED);
                   +  - ]
     773                 :             : 
     774   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.ActiveTip()->GetBlockHash(), snapshot_tip_hash);
                   +  - ]
     775   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
                   +  - ]
     776   [ +  -  -  +  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.HistoricalChainstate()->m_chain.Height(), 109);
             +  -  +  - ]
     777                 :           0 :     }
     778                 :             : 
     779   [ +  -  +  -  :           1 :     BOOST_TEST_MESSAGE(
                   +  - ]
     780                 :             :         "Ensure we can mine blocks on top of the initialized snapshot chainstate");
     781         [ +  - ]:           1 :     mineBlocks(10);
     782                 :           1 :     {
     783         [ +  - ]:           1 :         LOCK(chainman_restarted.GetMutex());
     784   [ +  -  +  -  :           1 :         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   [ +  -  -  +  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 2);
                   +  - ]
     789   [ +  -  -  +  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[0]->m_chain.Height(), 110);
                   +  - ]
     790   [ +  -  -  +  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[1]->m_chain.Height(), 220);
                   +  - ]
     791   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.HistoricalChainstate(), nullptr);
                   +  - ]
     792                 :           1 :     }
     793                 :           2 : }
     794                 :             : 
     795   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_completion, SnapshotTestSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     796                 :             : {
     797                 :           1 :     this->SetupSnapshot();
     798                 :             : 
     799         [ -  + ]:           1 :     ChainstateManager& chainman = *Assert(m_node.chainman);
     800                 :           1 :     Chainstate& active_cs = chainman.ActiveChainstate();
     801         [ +  + ]:           2 :     Chainstate& validated_cs{*Assert(WITH_LOCK(cs_main, return chainman.HistoricalChainstate()))};
     802                 :           1 :     auto tip_cache_before_complete = active_cs.m_coinstip_cache_size_bytes;
     803                 :           1 :     auto db_cache_before_complete = active_cs.m_coinsdb_cache_size_bytes;
     804                 :             : 
     805                 :           1 :     SnapshotCompletionResult res;
     806                 :           1 :     m_node.notifications->m_shutdown_on_fatal_error = false;
     807                 :             : 
     808         [ +  - ]:           1 :     fs::path snapshot_chainstate_dir = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
     809   [ +  -  +  -  :           2 :     BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
             +  -  +  - ]
     810   [ +  -  +  -  :           3 :     BOOST_CHECK_EQUAL(snapshot_chainstate_dir, gArgs.GetDataDirNet() / "chainstate_snapshot");
                   +  - ]
     811                 :             : 
     812   [ +  -  +  -  :           3 :     BOOST_CHECK(WITH_LOCK(::cs_main, return chainman.CurrentChainstate().m_from_snapshot_blockhash));
             +  -  +  - ]
     813   [ +  -  +  - ]:           3 :     const uint256 snapshot_tip_hash = WITH_LOCK(chainman.GetMutex(),
     814                 :             :         return chainman.ActiveTip()->GetBlockHash());
     815                 :             : 
     816   [ +  -  +  - ]:           3 :     res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validated_cs, active_cs));
     817   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(res, SnapshotCompletionResult::SUCCESS);
     818                 :             : 
     819   [ +  -  +  -  :           3 :     BOOST_CHECK(WITH_LOCK(::cs_main, return chainman.CurrentChainstate().m_assumeutxo == Assumeutxo::VALIDATED));
             +  -  +  - ]
     820   [ +  -  +  -  :           3 :     BOOST_CHECK(WITH_LOCK(::cs_main, return chainman.CurrentChainstate().m_from_snapshot_blockhash));
             +  -  +  - ]
     821   [ +  -  +  -  :           2 :     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   [ +  -  +  -  :           2 :     BOOST_CHECK(active_cs.m_coinstip_cache_size_bytes > tip_cache_before_complete);
                   +  - ]
     826   [ +  -  +  -  :           2 :     BOOST_CHECK(active_cs.m_coinsdb_cache_size_bytes > db_cache_before_complete);
                   +  - ]
     827                 :             : 
     828                 :             :     // Trying completion again should return false.
     829   [ +  -  +  - ]:           3 :     res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validated_cs, active_cs));
     830   [ +  -  +  - ]:           1 :     BOOST_CHECK_EQUAL(res, SnapshotCompletionResult::SKIPPED);
     831                 :             : 
     832                 :             :     // The invalid snapshot path should not have been used.
     833         [ +  - ]:           2 :     fs::path snapshot_invalid_dir = gArgs.GetDataDirNet() / "chainstate_snapshot_INVALID";
     834   [ +  -  +  -  :           2 :     BOOST_CHECK(!fs::exists(snapshot_invalid_dir));
             +  -  +  - ]
     835                 :             :     // chainstate_snapshot should still exist.
     836   [ +  -  +  -  :           2 :     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         [ +  - ]:           1 :     ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
     842                 :             : 
     843   [ +  -  +  -  :           1 :     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         [ +  - ]:           1 :     this->LoadVerifyActivateChainstate();
     848                 :             : 
     849   [ +  -  +  -  :           2 :     BOOST_CHECK(!fs::exists(snapshot_invalid_dir));
             +  -  +  - ]
     850                 :             :     // chainstate_snapshot should now *not* exist.
     851   [ +  -  +  -  :           2 :     BOOST_CHECK(!fs::exists(snapshot_chainstate_dir));
             +  -  +  - ]
     852                 :             : 
     853         [ +  - ]:           1 :     const Chainstate& active_cs2 = chainman_restarted.ActiveChainstate();
     854                 :             : 
     855                 :           1 :     {
     856         [ +  - ]:           1 :         LOCK(chainman_restarted.GetMutex());
     857   [ +  -  -  +  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 1);
                   +  - ]
     858   [ +  -  +  -  :           2 :         BOOST_CHECK(!chainman_restarted.CurrentChainstate().m_from_snapshot_blockhash);
                   +  - ]
     859   [ +  -  +  -  :           2 :         BOOST_CHECK(active_cs2.m_coinstip_cache_size_bytes > tip_cache_before_complete);
                   +  - ]
     860   [ +  -  +  -  :           2 :         BOOST_CHECK(active_cs2.m_coinsdb_cache_size_bytes > db_cache_before_complete);
                   +  - ]
     861                 :             : 
     862   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.ActiveTip()->GetBlockHash(), snapshot_tip_hash);
                   +  - ]
     863   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
             +  -  +  - ]
     864                 :           0 :     }
     865                 :             : 
     866   [ +  -  +  -  :           1 :     BOOST_TEST_MESSAGE(
                   +  - ]
     867                 :             :         "Ensure we can mine blocks on top of the \"new\" IBD chainstate");
     868         [ +  - ]:           1 :     mineBlocks(10);
     869                 :           1 :     {
     870         [ +  - ]:           1 :         LOCK(chainman_restarted.GetMutex());
     871   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
             +  -  +  - ]
     872                 :           1 :     }
     873                 :           2 : }
     874                 :             : 
     875   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_completion_hash_mismatch, SnapshotTestSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     876                 :             : {
     877                 :           1 :     auto chainstates = this->SetupSnapshot();
     878         [ -  + ]:           1 :     Chainstate& validation_chainstate = *std::get<0>(chainstates);
     879         [ -  + ]:           1 :     Chainstate& unvalidated_cs = *std::get<1>(chainstates);
     880         [ -  + ]:           1 :     ChainstateManager& chainman = *Assert(m_node.chainman);
     881                 :           1 :     SnapshotCompletionResult res;
     882                 :           1 :     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.
     886   [ +  -  +  - ]:           3 :     CCoinsViewCache& ibd_coins = WITH_LOCK(::cs_main,
     887                 :             :         return validation_chainstate.CoinsTip());
     888                 :           1 :     Coin badcoin;
     889                 :           1 :     badcoin.out.nValue = m_rng.rand32();
     890                 :           1 :     badcoin.nHeight = 1;
     891                 :           1 :     badcoin.out.scriptPubKey.assign(m_rng.randbits(6), 0);
     892         [ +  - ]:           1 :     Txid txid = Txid::FromUint256(m_rng.rand256());
     893         [ +  - ]:           1 :     ibd_coins.AddCoin(COutPoint(txid, 0), std::move(badcoin), false);
     894                 :             : 
     895         [ +  - ]:           2 :     fs::path snapshot_chainstate_dir = gArgs.GetDataDirNet() / "chainstate_snapshot";
     896   [ +  -  +  -  :           2 :     BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
             +  -  +  - ]
     897                 :             : 
     898                 :           1 :     {
     899   [ +  -  +  - ]:           2 :         ASSERT_DEBUG_LOG("failed to validate the -assumeutxo snapshot state");
     900   [ +  -  +  - ]:           3 :         res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validation_chainstate, unvalidated_cs));
     901   [ +  -  +  - ]:           1 :         BOOST_CHECK_EQUAL(res, SnapshotCompletionResult::HASH_MISMATCH);
     902                 :           1 :     }
     903                 :             : 
     904                 :           1 :     {
     905         [ +  - ]:           1 :         LOCK(chainman.GetMutex());
     906   [ +  -  -  +  :           1 :         BOOST_CHECK_EQUAL(chainman.m_chainstates.size(), 2);
                   +  - ]
     907   [ +  -  +  -  :           2 :         BOOST_CHECK(chainman.m_chainstates[0]->m_assumeutxo == Assumeutxo::VALIDATED);
                   +  - ]
     908   [ +  -  +  -  :           2 :         BOOST_CHECK(!chainman.m_chainstates[0]->SnapshotBase());
             +  -  +  - ]
     909   [ +  -  +  -  :           2 :         BOOST_CHECK(chainman.m_chainstates[1]->m_assumeutxo == Assumeutxo::INVALID);
                   +  - ]
     910   [ +  -  +  -  :           2 :         BOOST_CHECK(chainman.m_chainstates[1]->SnapshotBase());
             +  -  +  - ]
     911                 :           0 :     }
     912                 :             : 
     913         [ +  - ]:           2 :     fs::path snapshot_invalid_dir = gArgs.GetDataDirNet() / "chainstate_snapshot_INVALID";
     914   [ +  -  +  -  :           2 :     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         [ +  - ]:           1 :     ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
     920                 :             : 
     921   [ +  -  +  -  :           1 :     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         [ +  - ]:           1 :     this->LoadVerifyActivateChainstate();
     926                 :             : 
     927   [ +  -  +  -  :           2 :     BOOST_CHECK(fs::exists(snapshot_invalid_dir));
             +  -  +  - ]
     928   [ +  -  +  -  :           2 :     BOOST_CHECK(!fs::exists(snapshot_chainstate_dir));
             +  -  +  - ]
     929                 :             : 
     930                 :           1 :     {
     931         [ +  - ]:           1 :         LOCK(::cs_main);
     932   [ +  -  -  +  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 1);
                   +  - ]
     933   [ +  -  +  -  :           2 :         BOOST_CHECK(!chainman_restarted.CurrentChainstate().m_from_snapshot_blockhash);
                   +  - ]
     934   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
             +  -  +  - ]
     935                 :           0 :     }
     936                 :             : 
     937   [ +  -  +  -  :           1 :     BOOST_TEST_MESSAGE(
                   +  - ]
     938                 :             :         "Ensure we can mine blocks on top of the \"new\" IBD chainstate");
     939         [ +  - ]:           1 :     mineBlocks(10);
     940                 :           1 :     {
     941         [ +  - ]:           1 :         LOCK(::cs_main);
     942   [ +  -  +  -  :           1 :         BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
             +  -  +  - ]
     943                 :           1 :     }
     944                 :           2 : }
     945                 :             : 
     946                 :             : /** Helper function to parse args into args_man and return the result of applying them to opts */
     947                 :             : template <typename Options>
     948                 :          20 : util::Result<Options> SetOptsFromArgs(ArgsManager& args_man, Options opts,
     949                 :             :                                       const std::vector<const char*>& args)
     950                 :             : {
     951   [ +  -  -  + ]:          40 :     const auto argv{Cat({"ignore"}, args)};
     952         [ -  + ]:          20 :     std::string error{};
     953   [ -  +  +  -  :          20 :     if (!args_man.ParseParameters(argv.size(), argv.data(), error)) {
                   -  + ]
     954         [ #  # ]:           0 :         return util::Error{Untranslated("ParseParameters failed with error: " + error)};
     955                 :             :     }
     956         [ +  - ]:          20 :     const auto result{node::ApplyArgsManOptions(args_man, opts)};
     957         [ +  + ]:          30 :     if (!result) return util::Error{util::ErrorString(result)};
     958                 :          30 :     return opts;
     959   [ -  -  +  - ]:          45 : }
     960                 :             : 
     961   [ +  -  +  -  :           7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_args, BasicTestingSetup)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     962                 :             : {
     963                 :             :     //! Try to apply the provided args to a ChainstateManager::Options
     964                 :          21 :     auto get_opts = [&](const std::vector<const char*>& args) {
     965   [ +  +  +  - ]:          20 :         static kernel::Notifications notifications{};
     966                 :          20 :         static const ChainstateManager::Options options{
     967         [ +  - ]:           1 :             .chainparams = ::Params(),
     968                 :             :             .datadir = {},
     969   [ +  +  +  - ]:          21 :             .notifications = notifications};
     970         [ +  - ]:          40 :         return SetOptsFromArgs(*this->m_node.args, options, args);
     971                 :           1 :     };
     972                 :             :     //! Like get_opts, but requires the provided args to be valid and unwraps the result
     973                 :          16 :     auto get_valid_opts = [&](const std::vector<const char*>& args) {
     974                 :          15 :         const auto result{get_opts(args)};
     975   [ +  -  +  -  :          30 :         BOOST_REQUIRE_MESSAGE(result, util::ErrorString(result).original);
                   +  - ]
     976         [ +  - ]:          15 :         return *result;
     977                 :          16 :     };
     978                 :             : 
     979                 :             :     // test -assumevalid
     980   [ +  -  +  - ]:           3 :     BOOST_CHECK(!get_valid_opts({}).assumed_valid_block);
     981   [ +  -  +  - ]:           2 :     BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid="}).assumed_valid_block, uint256::ZERO);
     982   [ +  -  +  - ]:           2 :     BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid=0"}).assumed_valid_block, uint256::ZERO);
     983   [ +  -  +  - ]:           2 :     BOOST_CHECK_EQUAL(get_valid_opts({"-noassumevalid"}).assumed_valid_block, uint256::ZERO);
     984   [ +  -  +  - ]:           2 :     BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid=0x12"}).assumed_valid_block, uint256{0x12});
     985                 :             : 
     986                 :           1 :     std::string assume_valid{"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"};
     987   [ +  -  -  +  :           2 :     BOOST_CHECK_EQUAL(get_valid_opts({("-assumevalid=" + assume_valid).c_str()}).assumed_valid_block, uint256::FromHex(assume_valid));
          +  -  +  -  +  
             -  +  -  +  
                      - ]
     988                 :             : 
     989   [ +  -  +  -  :           2 :     BOOST_CHECK(!get_opts({"-assumevalid=xyz"}));                                                               // invalid hex characters
          +  -  +  -  +  
                      - ]
     990   [ +  -  +  -  :           2 :     BOOST_CHECK(!get_opts({"-assumevalid=01234567890123456789012345678901234567890123456789012345678901234"})); // > 64 hex chars
          +  -  +  -  +  
                      - ]
     991                 :             : 
     992                 :             :     // test -minimumchainwork
     993   [ +  -  +  -  :           3 :     BOOST_CHECK(!get_valid_opts({}).minimum_chain_work);
             +  -  +  - ]
     994   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL(get_valid_opts({"-minimumchainwork=0"}).minimum_chain_work, arith_uint256());
          +  -  +  -  +  
                      - ]
     995   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL(get_valid_opts({"-nominimumchainwork"}).minimum_chain_work, arith_uint256());
          +  -  +  -  +  
                      - ]
     996   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL(get_valid_opts({"-minimumchainwork=0x1234"}).minimum_chain_work, arith_uint256{0x1234});
          +  -  +  -  +  
                      - ]
     997                 :             : 
     998         [ +  - ]:           1 :     std::string minimum_chainwork{"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"};
     999   [ +  -  -  +  :           3 :     BOOST_CHECK_EQUAL(get_valid_opts({("-minimumchainwork=" + minimum_chainwork).c_str()}).minimum_chain_work, UintToArith256(uint256::FromHex(minimum_chainwork).value()));
          +  -  +  -  +  
          -  +  -  +  -  
                   +  - ]
    1000                 :             : 
    1001   [ +  -  +  -  :           2 :     BOOST_CHECK(!get_opts({"-minimumchainwork=xyz"}));                                                               // invalid hex characters
          +  -  +  -  +  
                      - ]
    1002   [ +  -  +  -  :           2 :     BOOST_CHECK(!get_opts({"-minimumchainwork=01234567890123456789012345678901234567890123456789012345678901234"})); // > 64 hex chars
          +  -  +  -  +  
                      - ]
    1003                 :             : 
    1004   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL(get_valid_opts({}).prevoutfetch_threads_num, DEFAULT_PREVOUTFETCH_THREADS);
                   +  - ]
    1005   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL(get_valid_opts({"-prevoutfetchthreads=0"}).prevoutfetch_threads_num, 0);
          +  -  +  -  +  
                      - ]
    1006   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL(get_valid_opts({"-prevoutfetchthreads=3"}).prevoutfetch_threads_num, 3);
          +  -  +  -  +  
                      - ]
    1007   [ +  -  +  -  :           2 :     BOOST_CHECK_EQUAL(get_valid_opts({"-prevoutfetchthreads=100"}).prevoutfetch_threads_num, MAX_PREVOUTFETCH_THREADS);
          +  -  +  -  +  
                      - ]
    1008   [ +  -  +  -  :           2 :     BOOST_CHECK(!get_opts({"-prevoutfetchthreads=-1"}));
             +  -  +  - ]
    1009                 :           1 : }
    1010                 :             : 
    1011                 :             : BOOST_AUTO_TEST_SUITE_END()
        

Generated by: LCOV version 2.0-1