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/logging.h>
16 : : #include <test/util/random.h>
17 : : #include <test/util/setup_common.h>
18 : : #include <test/util/validation.h>
19 : : #include <uint256.h>
20 : : #include <util/result.h>
21 : : #include <util/vector.h>
22 : : #include <validation.h>
23 : : #include <validationinterface.h>
24 : :
25 : : #include <tinyformat.h>
26 : :
27 : : #include <vector>
28 : :
29 : : #include <boost/test/unit_test.hpp>
30 : :
31 : : using node::BlockManager;
32 : : using node::KernelNotifications;
33 : : using node::SnapshotMetadata;
34 : :
35 : : BOOST_FIXTURE_TEST_SUITE(validation_chainstatemanager_tests, TestingSetup)
36 : :
37 : : //! Basic tests for ChainstateManager.
38 : : //!
39 : : //! First create a legacy (IBD) chainstate, then create a snapshot chainstate.
40 [ + - + - : 10 : BOOST_FIXTURE_TEST_CASE(chainstatemanager, TestChain100Setup)
+ - + - -
+ + - + -
+ - + - +
- + - + -
- + + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
- + + - ]
41 : : {
42 : 1 : ChainstateManager& manager = *m_node.chainman;
43 : :
44 [ + - + - ]: 3 : BOOST_CHECK(WITH_LOCK(::cs_main, return !manager.CurrentChainstate().m_from_snapshot_blockhash));
45 : :
46 : : // Create a legacy (IBD) chainstate.
47 : : //
48 : 1 : Chainstate& c1 = manager.ActiveChainstate();
49 : :
50 [ + - + - ]: 3 : BOOST_CHECK(WITH_LOCK(::cs_main, return !manager.CurrentChainstate().m_from_snapshot_blockhash));
51 : 1 : {
52 : 1 : LOCK(manager.GetMutex());
53 [ + - - + : 1 : BOOST_CHECK_EQUAL(manager.m_chainstates.size(), 1);
+ - ]
54 [ + - + - : 1 : BOOST_CHECK_EQUAL(manager.m_chainstates[0].get(), &c1);
+ - ]
55 : 0 : }
56 : :
57 [ + - + - ]: 3 : auto& active_chain = WITH_LOCK(manager.GetMutex(), return manager.ActiveChain());
58 [ + - ]: 1 : BOOST_CHECK_EQUAL(&active_chain, &c1.m_chain);
59 : :
60 : : // Get to a valid assumeutxo tip (per chainparams);
61 : 1 : mineBlocks(10);
62 [ + - + - ]: 3 : BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 110);
63 [ + - + - ]: 3 : auto active_tip = WITH_LOCK(manager.GetMutex(), return manager.ActiveTip());
64 [ - + ]: 1 : auto exp_tip = c1.m_chain.Tip();
65 [ + - ]: 1 : BOOST_CHECK_EQUAL(active_tip, exp_tip);
66 : :
67 [ + - + - ]: 3 : BOOST_CHECK(WITH_LOCK(::cs_main, return !manager.CurrentChainstate().m_from_snapshot_blockhash));
68 : :
69 : : // Create a snapshot-based chainstate.
70 : : //
71 : 1 : const uint256 snapshot_blockhash = active_tip->GetBlockHash();
72 [ + - + - : 3 : Chainstate& c2{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, snapshot_blockhash)))};
+ - ]
73 : 1 : c2.InitCoinsDB(
74 : : /*cache_size_bytes=*/1 << 23, /*in_memory=*/true, /*should_wipe=*/false);
75 : 1 : {
76 : 1 : LOCK(::cs_main);
77 [ + - ]: 1 : c2.InitCoinsCache(1 << 23);
78 [ + - + - ]: 1 : c2.CoinsTip().SetBestBlock(active_tip->GetBlockHash());
79 [ + - + - ]: 1 : c2.setBlockIndexCandidates.insert(manager.m_blockman.LookupBlockIndex(active_tip->GetBlockHash()));
80 [ + - ]: 1 : c2.LoadChainTip();
81 : 0 : }
82 [ + - ]: 1 : BlockValidationState _;
83 [ + - + - : 2 : BOOST_CHECK(c2.ActivateBestChain(_, nullptr));
+ - + - -
+ + - ]
84 : :
85 [ + - + - : 2 : BOOST_CHECK_EQUAL(WITH_LOCK(::cs_main, return *manager.CurrentChainstate().m_from_snapshot_blockhash), snapshot_blockhash);
+ - ]
86 [ + - + - : 3 : BOOST_CHECK(WITH_LOCK(::cs_main, return manager.CurrentChainstate().m_assumeutxo == Assumeutxo::UNVALIDATED));
+ - + - ]
87 [ + - + - : 1 : BOOST_CHECK_EQUAL(&c2, &manager.ActiveChainstate());
+ - ]
88 [ + - + - : 2 : BOOST_CHECK(&c1 != &manager.ActiveChainstate());
+ - + - ]
89 : 1 : {
90 [ + - ]: 1 : LOCK(manager.GetMutex());
91 [ + - - + : 1 : BOOST_CHECK_EQUAL(manager.m_chainstates.size(), 2);
+ - ]
92 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(manager.m_chainstates[0].get(), &c1);
93 [ + - + - : 1 : BOOST_CHECK_EQUAL(manager.m_chainstates[1].get(), &c2);
+ - ]
94 : 0 : }
95 : :
96 [ + - + - ]: 3 : auto& active_chain2 = WITH_LOCK(manager.GetMutex(), return manager.ActiveChain());
97 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(&active_chain2, &c2.m_chain);
98 : :
99 [ + - + - : 3 : BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 110);
+ - ]
100 [ + - ]: 1 : mineBlocks(1);
101 [ + - + - : 3 : BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return manager.ActiveHeight()), 111);
+ - ]
102 [ + + + - : 2 : BOOST_CHECK_EQUAL(WITH_LOCK(manager.GetMutex(), return c1.m_chain.Height()), 110);
+ - ]
103 : :
104 [ + - + - ]: 3 : auto active_tip2 = WITH_LOCK(manager.GetMutex(), return manager.ActiveTip());
105 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(active_tip, active_tip2->pprev);
106 [ + - - + : 2 : BOOST_CHECK_EQUAL(active_tip, c1.m_chain.Tip());
+ - ]
107 [ + - - + : 2 : BOOST_CHECK_EQUAL(active_tip2, c2.m_chain.Tip());
+ - ]
108 : :
109 : : // Let scheduler events finish running to avoid accessing memory that is going to be unloaded
110 [ + - ]: 1 : m_node.validation_signals->SyncWithValidationInterfaceQueue();
111 : 1 : }
112 : :
113 : : //! Test rebalancing the caches associated with each chainstate.
114 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_rebalance_caches, TestChain100Setup)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
115 : : {
116 [ + - ]: 1 : ChainstateManager& manager = *m_node.chainman;
117 : :
118 : 1 : size_t max_cache = 10000;
119 : 1 : manager.m_total_coinsdb_cache = max_cache;
120 : 1 : manager.m_total_coinstip_cache = max_cache;
121 : :
122 : 1 : std::vector<Chainstate*> chainstates;
123 : :
124 : : // Create a legacy (IBD) chainstate.
125 : : //
126 [ + - ]: 1 : Chainstate& c1 = manager.ActiveChainstate();
127 [ + - ]: 1 : chainstates.push_back(&c1);
128 : 1 : {
129 [ + - ]: 1 : LOCK(::cs_main);
130 [ + - ]: 1 : c1.InitCoinsCache(1 << 23);
131 [ + - ]: 1 : manager.MaybeRebalanceCaches();
132 : 0 : }
133 : :
134 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(c1.m_coinstip_cache_size_bytes, max_cache);
135 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(c1.m_coinsdb_cache_size_bytes, max_cache);
136 : :
137 : : // Create a snapshot-based chainstate.
138 : : //
139 [ + - + - : 4 : CBlockIndex* snapshot_base{WITH_LOCK(manager.GetMutex(), return manager.ActiveChain()[manager.ActiveChain().Height() / 2])};
- + + - +
- ]
140 [ + - + - : 3 : Chainstate& c2{WITH_LOCK(::cs_main, return manager.AddChainstate(std::make_unique<Chainstate>(nullptr, manager.m_blockman, manager, *snapshot_base->phashBlock)))};
+ - ]
141 [ + - ]: 1 : chainstates.push_back(&c2);
142 [ + - ]: 1 : c2.InitCoinsDB(
143 : : /*cache_size_bytes=*/1 << 23, /*in_memory=*/true, /*should_wipe=*/false);
144 : :
145 : : // Reset IBD state so IsInitialBlockDownload() returns true and causes
146 : : // MaybeRebalanceCaches() to prioritize the snapshot chainstate, giving it
147 : : // more cache space than the snapshot chainstate. Calling ResetIbd() is
148 : : // necessary because m_cached_is_ibd is already latched to false before
149 : : // the test starts due to the test setup. After ResetIbd() is called,
150 : : // IsInitialBlockDownload() will return true because at this point the active
151 : : // chainstate has a null chain tip.
152 [ + - ]: 1 : static_cast<TestChainstateManager&>(manager).ResetIbd();
153 : :
154 : 1 : {
155 [ + - ]: 1 : LOCK(::cs_main);
156 [ + - ]: 1 : c2.InitCoinsCache(1 << 23);
157 [ + - ]: 1 : manager.MaybeRebalanceCaches();
158 : 0 : }
159 : :
160 [ + - + - ]: 1 : BOOST_CHECK_CLOSE(double(c1.m_coinstip_cache_size_bytes), max_cache * 0.05, 1);
161 [ + - + - ]: 1 : BOOST_CHECK_CLOSE(double(c1.m_coinsdb_cache_size_bytes), max_cache * 0.05, 1);
162 [ + - + - ]: 1 : BOOST_CHECK_CLOSE(double(c2.m_coinstip_cache_size_bytes), max_cache * 0.95, 1);
163 [ + - + - ]: 1 : BOOST_CHECK_CLOSE(double(c2.m_coinsdb_cache_size_bytes), max_cache * 0.95, 1);
164 : 1 : }
165 : :
166 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_ibd_exit_after_loading_blocks, ChainTestingSetup)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
167 : : {
168 : 1 : CBlockIndex tip;
169 [ - + ]: 1 : ChainstateManager& chainman{*Assert(m_node.chainman)};
170 : 33 : auto apply{[&](bool cached_is_ibd, bool loading_blocks, bool tip_exists, bool enough_work, bool tip_recent) {
171 : 32 : LOCK(::cs_main);
172 [ + - ]: 32 : chainman.ResetChainstates();
173 [ + - ]: 32 : chainman.InitializeChainstate(m_node.mempool.get());
174 : :
175 : 32 : const auto recent_time{Now<NodeSeconds>() - chainman.m_options.max_tip_age};
176 : :
177 [ + + ]: 32 : chainman.m_cached_is_ibd.store(cached_is_ibd, std::memory_order_relaxed);
178 [ + + ]: 32 : chainman.m_blockman.m_importing = loading_blocks;
179 [ + + ]: 32 : if (tip_exists) {
180 [ + + + - : 32 : tip.nChainWork = chainman.MinimumChainWork() - (enough_work ? 0 : 1);
+ + ]
181 [ + + + - ]: 16 : tip.nTime = (recent_time - (tip_recent ? 0h : 100h)).time_since_epoch().count();
182 [ + - + - ]: 16 : chainman.ActiveChain().SetTip(tip);
183 : : } else {
184 [ + - - + : 16 : assert(!chainman.ActiveChain().Tip());
- - ]
185 : : }
186 [ + - ]: 32 : chainman.UpdateIBDStatus();
187 : 33 : }};
188 : :
189 [ + + ]: 3 : for (const bool cached_is_ibd : {false, true}) {
190 [ + + ]: 6 : for (const bool loading_blocks : {false, true}) {
191 [ + + ]: 12 : for (const bool tip_exists : {false, true}) {
192 [ + + ]: 24 : for (const bool enough_work : {false, true}) {
193 [ + + ]: 48 : for (const bool tip_recent : {false, true}) {
194 : 32 : apply(cached_is_ibd, loading_blocks, tip_exists, enough_work, tip_recent);
195 [ + + + + : 32 : const bool expected_ibd = cached_is_ibd && (loading_blocks || !tip_exists || !enough_work || !tip_recent);
+ + ]
196 [ + - ]: 32 : BOOST_CHECK_EQUAL(chainman.IsInitialBlockDownload(), expected_ibd);
197 : : }
198 : : }
199 : : }
200 : : }
201 : : }
202 : 1 : }
203 : :
204 : 8 : struct SnapshotTestSetup : TestChain100Setup {
205 : : // Run with coinsdb on the filesystem to support, e.g., moving invalidated
206 : : // chainstate dirs to "*_invalid".
207 : : //
208 : : // Note that this means the tests run considerably slower than in-memory DB
209 : : // tests, but we can't otherwise test this functionality since it relies on
210 : : // destructive filesystem operations.
211 : 4 : SnapshotTestSetup() : TestChain100Setup{
212 : : {},
213 : : {
214 : : .coins_db_in_memory = false,
215 : : .block_tree_db_in_memory = false,
216 : : },
217 [ + - ]: 4 : }
218 : : {
219 : 4 : }
220 : :
221 : 4 : std::tuple<Chainstate*, Chainstate*> SetupSnapshot()
222 : : {
223 [ - + ]: 4 : ChainstateManager& chainman = *Assert(m_node.chainman);
224 : :
225 : 4 : {
226 : 4 : LOCK(::cs_main);
227 [ + - + - : 8 : BOOST_CHECK(!chainman.CurrentChainstate().m_from_snapshot_blockhash);
+ - ]
228 [ + - + - : 12 : BOOST_CHECK(!node::FindAssumeutxoChainstateDir(chainman.m_options.datadir));
+ - - + +
- ]
229 : 0 : }
230 : :
231 : 4 : size_t initial_size;
232 : 4 : size_t initial_total_coins{100};
233 : :
234 : : // Make some initial assertions about the contents of the chainstate.
235 : 4 : {
236 : 4 : LOCK(::cs_main);
237 [ + - + - ]: 4 : CCoinsViewCache& ibd_coinscache = chainman.ActiveChainstate().CoinsTip();
238 [ + - ]: 4 : initial_size = ibd_coinscache.GetCacheSize();
239 : 4 : size_t total_coins{0};
240 : :
241 [ + + ]: 404 : for (CTransactionRef& txn : m_coinbase_txns) {
242 [ + - ]: 400 : COutPoint op{txn->GetHash(), 0};
243 [ + - + - : 800 : BOOST_CHECK(ibd_coinscache.HaveCoin(op));
+ - ]
244 : 400 : total_coins++;
245 : : }
246 : :
247 [ + - + - ]: 4 : BOOST_CHECK_EQUAL(total_coins, initial_total_coins);
248 [ + - + - : 4 : BOOST_CHECK_EQUAL(initial_size, initial_total_coins);
+ - ]
249 : 0 : }
250 : :
251 : 4 : Chainstate& validation_chainstate = chainman.ActiveChainstate();
252 : :
253 : : // Snapshot should refuse to load at this height.
254 [ + - + - ]: 8 : BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(this));
255 [ + - + - ]: 8 : BOOST_CHECK(!chainman.ActiveChainstate().m_from_snapshot_blockhash);
256 : :
257 : : // Mine 10 more blocks, putting at us height 110 where a valid assumeutxo value can
258 : : // be found.
259 : 4 : constexpr int snapshot_height = 110;
260 : 4 : mineBlocks(10);
261 : 4 : initial_size += 10;
262 : 4 : initial_total_coins += 10;
263 : :
264 : : // Should not load malleated snapshots
265 [ + - + - : 16 : BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
+ - ]
266 : : this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
267 : : // A UTXO is missing but count is correct
268 : : metadata.m_coins_count -= 1;
269 : :
270 : : Txid txid;
271 : : auto_infile >> txid;
272 : : // coins size
273 : : (void)ReadCompactSize(auto_infile);
274 : : // vout index
275 : : (void)ReadCompactSize(auto_infile);
276 : : Coin coin;
277 : : auto_infile >> coin;
278 : : }));
279 : :
280 [ + - + - : 12 : BOOST_CHECK(!node::FindAssumeutxoChainstateDir(chainman.m_options.datadir));
- + ]
281 : :
282 [ - + + - : 12 : BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
+ - ]
283 : : this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
284 : : // Coins count is larger than coins in file
285 : : metadata.m_coins_count += 1;
286 : : }));
287 [ - + + - : 12 : BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
+ - ]
288 : : this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
289 : : // Coins count is smaller than coins in file
290 : : metadata.m_coins_count -= 1;
291 : : }));
292 [ - + + - : 12 : BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
+ - ]
293 : : this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
294 : : // Wrong hash
295 : : metadata.m_base_blockhash = uint256::ZERO;
296 : : }));
297 [ - + + - : 12 : BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(
+ - ]
298 : : this, [](AutoFile& auto_infile, SnapshotMetadata& metadata) {
299 : : // Wrong hash
300 : : metadata.m_base_blockhash = uint256::ONE;
301 : : }));
302 : :
303 [ + - + - ]: 8 : BOOST_REQUIRE(CreateAndActivateUTXOSnapshot(this));
304 [ + - + - : 12 : BOOST_CHECK(fs::exists(*node::FindAssumeutxoChainstateDir(chainman.m_options.datadir)));
+ - + - ]
305 : :
306 : : // Ensure our active chain is the snapshot chainstate.
307 [ + - + - ]: 12 : BOOST_CHECK(!chainman.ActiveChainstate().m_from_snapshot_blockhash->IsNull());
308 : :
309 : 4 : Chainstate& snapshot_chainstate = chainman.ActiveChainstate();
310 : :
311 : 4 : {
312 : 4 : LOCK(::cs_main);
313 : :
314 [ + - + - ]: 4 : fs::path found = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
315 : :
316 : : // Note: WriteSnapshotBaseBlockhash() is implicitly tested above.
317 [ + - - + : 8 : BOOST_CHECK_EQUAL(
+ - + - +
- ]
318 : : *node::ReadSnapshotBaseBlockhash(found),
319 : : *Assert(chainman.CurrentChainstate().m_from_snapshot_blockhash));
320 [ + - ]: 4 : }
321 : :
322 : 4 : const auto& au_data = ::Params().AssumeutxoForHeight(snapshot_height);
323 [ + - + - ]: 12 : const CBlockIndex* tip = WITH_LOCK(chainman.GetMutex(), return chainman.ActiveTip());
324 : :
325 [ + - ]: 4 : BOOST_CHECK_EQUAL(tip->m_chain_tx_count, au_data->m_chain_tx_count);
326 : :
327 : : // To be checked against later when we try loading a subsequent snapshot.
328 [ - + + - ]: 8 : uint256 loaded_snapshot_blockhash{*Assert(WITH_LOCK(chainman.GetMutex(), return chainman.CurrentChainstate().m_from_snapshot_blockhash))};
329 : :
330 : : // Make some assertions about the both chainstates. These checks ensure the
331 : : // legacy chainstate hasn't changed and that the newly created chainstate
332 : : // reflects the expected content.
333 : 4 : {
334 : 4 : LOCK(::cs_main);
335 : 4 : int chains_tested{0};
336 : :
337 [ + + ]: 12 : for (const auto& chainstate : chainman.m_chainstates) {
338 [ + - + - : 8 : BOOST_TEST_MESSAGE("Checking coins in " << chainstate->ToString());
+ - + - ]
339 [ + - ]: 8 : CCoinsViewCache& coinscache = chainstate->CoinsTip();
340 : :
341 : : // Both caches will be empty initially.
342 [ + - + - : 8 : BOOST_CHECK_EQUAL((unsigned int)0, coinscache.GetCacheSize());
+ - ]
343 : :
344 : 8 : size_t total_coins{0};
345 : :
346 [ + + ]: 888 : for (CTransactionRef& txn : m_coinbase_txns) {
347 [ + - ]: 880 : COutPoint op{txn->GetHash(), 0};
348 [ + - + - : 1760 : BOOST_CHECK(coinscache.HaveCoin(op));
+ - ]
349 : 880 : total_coins++;
350 : : }
351 : :
352 [ + - + - : 8 : BOOST_CHECK_EQUAL(initial_size , coinscache.GetCacheSize());
+ - ]
353 [ + - + - ]: 8 : BOOST_CHECK_EQUAL(total_coins, initial_total_coins);
354 : 8 : chains_tested++;
355 : : }
356 : :
357 [ + - + - : 4 : BOOST_CHECK_EQUAL(chains_tested, 2);
+ - ]
358 : 0 : }
359 : :
360 : : // Mine some new blocks on top of the activated snapshot chainstate.
361 : 4 : constexpr size_t new_coins{100};
362 : 4 : mineBlocks(new_coins); // Defined in TestChain100Setup.
363 : :
364 : 4 : {
365 : 4 : LOCK(::cs_main);
366 : 4 : size_t coins_in_active{0};
367 : 4 : size_t coins_in_background{0};
368 : 4 : size_t coins_missing_from_background{0};
369 : :
370 [ + + ]: 12 : for (const auto& chainstate : chainman.m_chainstates) {
371 [ + - + - : 8 : BOOST_TEST_MESSAGE("Checking coins in " << chainstate->ToString());
+ - + - ]
372 [ + - ]: 8 : CCoinsViewCache& coinscache = chainstate->CoinsTip();
373 [ + - ]: 8 : bool is_background = chainstate.get() != &chainman.ActiveChainstate();
374 : :
375 [ + + ]: 1688 : for (CTransactionRef& txn : m_coinbase_txns) {
376 [ + - ]: 1680 : COutPoint op{txn->GetHash(), 0};
377 [ + - + + ]: 1680 : if (coinscache.HaveCoin(op)) {
378 [ + + ]: 1280 : (is_background ? coins_in_background : coins_in_active)++;
379 [ + - ]: 400 : } else if (is_background) {
380 : 400 : coins_missing_from_background++;
381 : : }
382 : : }
383 : : }
384 : :
385 [ + - + - ]: 4 : BOOST_CHECK_EQUAL(coins_in_active, initial_total_coins + new_coins);
386 [ + - + - ]: 4 : BOOST_CHECK_EQUAL(coins_in_background, initial_total_coins);
387 [ + - + - : 4 : BOOST_CHECK_EQUAL(coins_missing_from_background, new_coins);
+ - ]
388 : 0 : }
389 : :
390 : : // Snapshot should refuse to load after one has already loaded.
391 [ + - + - ]: 8 : BOOST_REQUIRE(!CreateAndActivateUTXOSnapshot(this));
392 : :
393 : : // Snapshot blockhash should be unchanged.
394 [ + - ]: 4 : BOOST_CHECK_EQUAL(
395 : : *chainman.ActiveChainstate().m_from_snapshot_blockhash,
396 : : loaded_snapshot_blockhash);
397 : 4 : return std::make_tuple(&validation_chainstate, &snapshot_chainstate);
398 : : }
399 : :
400 : : // Simulate a restart of the node by flushing all state to disk, clearing the
401 : : // existing ChainstateManager, and unloading the block index.
402 : : //
403 : : // @returns a reference to the "restarted" ChainstateManager
404 : 3 : ChainstateManager& SimulateNodeRestart()
405 : : {
406 [ - + ]: 3 : ChainstateManager& chainman = *Assert(m_node.chainman);
407 : :
408 [ + - ]: 3 : BOOST_TEST_MESSAGE("Simulating node restart");
409 : 3 : {
410 : 3 : LOCK(chainman.GetMutex());
411 [ + + ]: 9 : for (const auto& cs : chainman.m_chainstates) {
412 [ + + + - ]: 11 : if (cs->CanFlushToDisk()) cs->ForceFlushStateToDisk();
413 : : }
414 : 0 : }
415 : 3 : {
416 : : // Process all callbacks referring to the old manager before wiping it.
417 : 3 : m_node.validation_signals->SyncWithValidationInterfaceQueue();
418 : 3 : LOCK(::cs_main);
419 [ + - ]: 3 : chainman.ResetChainstates();
420 [ + - - + : 3 : BOOST_CHECK_EQUAL(chainman.m_chainstates.size(), 0);
+ - ]
421 [ - + - + : 3 : m_node.notifications = std::make_unique<KernelNotifications>(Assert(m_node.shutdown_request), m_node.exit_status, *Assert(m_node.warnings));
+ - ]
422 : 3 : const ChainstateManager::Options chainman_opts{
423 [ + - ]: 3 : .chainparams = ::Params(),
424 : 3 : .datadir = chainman.m_options.datadir,
425 : 3 : .notifications = *m_node.notifications,
426 : 3 : .signals = m_node.validation_signals.get(),
427 [ + - + - ]: 3 : };
428 : 3 : const BlockManager::Options blockman_opts{
429 : 3 : .chainparams = chainman_opts.chainparams,
430 : : .blocks_dir = m_args.GetBlocksDirPath(),
431 : 3 : .notifications = chainman_opts.notifications,
432 : : .block_tree_db_params = DBParams{
433 [ + - + - ]: 9 : .path = chainman.m_options.datadir / "blocks" / "index",
434 : 3 : .cache_bytes = m_kernel_cache_sizes.block_tree_db,
435 : 3 : .memory_only = m_block_tree_db_in_memory,
436 : : },
437 [ + - + - ]: 6 : };
438 : : // For robustness, ensure the old manager is destroyed before creating a
439 : : // new one.
440 [ + - ]: 3 : m_node.chainman.reset();
441 [ - + + - ]: 3 : m_node.chainman = std::make_unique<ChainstateManager>(*Assert(m_node.shutdown_signal), chainman_opts, blockman_opts);
442 [ + - ]: 6 : }
443 [ - + ]: 3 : return *Assert(m_node.chainman);
444 : : }
445 : : };
446 : :
447 : : //! Test basic snapshot activation.
448 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_activate_snapshot, SnapshotTestSetup)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
449 : : {
450 : 1 : this->SetupSnapshot();
451 : 1 : }
452 : :
453 : : //! Test LoadBlockIndex behavior when multiple chainstates are in use.
454 : : //!
455 : : //! - First, verify that setBlockIndexCandidates is as expected when using a single,
456 : : //! fully-validating chainstate.
457 : : //!
458 : : //! - Then mark a region of the chain as missing data and introduce a second chainstate
459 : : //! that will tolerate assumed-valid blocks. Run LoadBlockIndex() and ensure that the first
460 : : //! chainstate only contains fully validated blocks and the other chainstate contains all blocks,
461 : : //! except those marked assume-valid, because those entries don't HAVE_DATA.
462 : : //!
463 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_loadblockindex, TestChain100Setup)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
464 : : {
465 [ - + ]: 1 : ChainstateManager& chainman = *Assert(m_node.chainman);
466 : 1 : Chainstate& cs1 = chainman.ActiveChainstate();
467 : :
468 : 1 : int num_indexes{0};
469 : : // Blocks in range [assumed_valid_start_idx, last_assumed_valid_idx) will be
470 : : // marked as assumed-valid and not having data.
471 : 1 : const int expected_assumed_valid{20};
472 : 1 : const int last_assumed_valid_idx{111};
473 : 1 : const int assumed_valid_start_idx = last_assumed_valid_idx - expected_assumed_valid;
474 : :
475 : : // Mine to height 120, past the hardcoded regtest assumeutxo snapshot at
476 : : // height 110
477 : 1 : mineBlocks(20);
478 : :
479 : 1 : CBlockIndex* validated_tip{nullptr};
480 : 1 : CBlockIndex* assumed_base{nullptr};
481 [ + - - + : 4 : CBlockIndex* assumed_tip{WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip())};
+ - ]
482 [ + - ]: 1 : BOOST_CHECK_EQUAL(assumed_tip->nHeight, 120);
483 : :
484 : 3 : auto reload_all_block_indexes = [&]() {
485 : 2 : LOCK(chainman.GetMutex());
486 : : // For completeness, we also reset the block sequence counters to
487 : : // ensure that no state which affects the ranking of tip-candidates is
488 : : // retained (even though this isn't strictly necessary).
489 : 2 : chainman.ResetBlockSequenceCounters();
490 [ + + ]: 5 : for (const auto& cs : chainman.m_chainstates) {
491 [ + - ]: 3 : cs->ClearBlockIndexCandidates();
492 [ + - + - ]: 6 : BOOST_CHECK(cs->setBlockIndexCandidates.empty());
493 : : }
494 [ + - ]: 2 : chainman.LoadBlockIndex();
495 : 3 : };
496 : :
497 : : // Ensure that without any assumed-valid BlockIndex entries, only the current tip is
498 : : // considered as a candidate.
499 : 1 : reload_all_block_indexes();
500 [ + - ]: 1 : BOOST_CHECK_EQUAL(cs1.setBlockIndexCandidates.size(), 1);
501 : :
502 : : // Reset some region of the chain's nStatus, removing the HAVE_DATA flag.
503 [ - + + + ]: 122 : for (int i = 0; i <= cs1.m_chain.Height(); ++i) {
504 : 121 : LOCK(::cs_main);
505 [ + - ]: 121 : auto index = cs1.m_chain[i];
506 : :
507 : : // Blocks with heights in range [91, 110] are marked as missing data.
508 [ + + ]: 121 : if (i < last_assumed_valid_idx && i >= assumed_valid_start_idx) {
509 : 20 : index->nStatus = BlockStatus::BLOCK_VALID_TREE;
510 : 20 : index->nTx = 0;
511 : 20 : index->m_chain_tx_count = 0;
512 : : }
513 : :
514 : 121 : ++num_indexes;
515 : :
516 : : // Note the last fully-validated block as the expected validated tip.
517 [ + + ]: 121 : if (i == (assumed_valid_start_idx - 1)) {
518 : 1 : validated_tip = index;
519 : : }
520 : : // Note the last assumed valid block as the snapshot base
521 [ + + ]: 121 : if (i == last_assumed_valid_idx - 1) {
522 : 1 : assumed_base = index;
523 : : }
524 : 121 : }
525 : :
526 : : // Note: cs2's tip is not set when ActivateExistingSnapshot is called.
527 [ + - + - : 3 : Chainstate& cs2{WITH_LOCK(::cs_main, return chainman.AddChainstate(std::make_unique<Chainstate>(nullptr, chainman.m_blockman, chainman, *assumed_base->phashBlock)))};
+ - ]
528 : :
529 : : // Set tip of the fully validated chain to be the validated tip
530 : 1 : cs1.m_chain.SetTip(*validated_tip);
531 : :
532 : : // Set tip of the assume-valid-based chain to the assume-valid block
533 : 1 : cs2.m_chain.SetTip(*assumed_base);
534 : :
535 : : // Sanity check test variables.
536 [ + - ]: 1 : BOOST_CHECK_EQUAL(num_indexes, 121); // 121 total blocks, including genesis
537 [ + - ]: 1 : BOOST_CHECK_EQUAL(assumed_tip->nHeight, 120); // original chain has height 120
538 [ + - ]: 1 : BOOST_CHECK_EQUAL(validated_tip->nHeight, 90); // current cs1 chain has height 90
539 [ + - ]: 1 : BOOST_CHECK_EQUAL(assumed_base->nHeight, 110); // current cs2 chain has height 110
540 : :
541 : : // Regenerate cs1.setBlockIndexCandidates and cs2.setBlockIndexCandidate and
542 : : // check contents below.
543 : 1 : reload_all_block_indexes();
544 : :
545 : : // The fully validated chain should only have the current validated tip and
546 : : // the assumed valid base as candidates, blocks 90 and 110. Specifically:
547 : : //
548 : : // - It does not have blocks 0-89 because they contain less work than the
549 : : // chain tip.
550 : : //
551 : : // - It has block 90 because it has data and equal work to the chain tip,
552 : : // (since it is the chain tip).
553 : : //
554 : : // - It does not have blocks 91-109 because they do not contain data.
555 : : //
556 : : // - It has block 110 even though it does not have data, because
557 : : // LoadBlockIndex has a special case to always add the snapshot block as a
558 : : // candidate. The special case is only actually intended to apply to the
559 : : // snapshot chainstate cs2, not the background chainstate cs1, but it is
560 : : // written broadly and applies to both.
561 : : //
562 : : // - It does not have any blocks after height 110 because cs1 is a background
563 : : // chainstate, and only blocks where are ancestors of the snapshot block
564 : : // are added as candidates for the background chainstate.
565 [ + - ]: 1 : BOOST_CHECK_EQUAL(cs1.setBlockIndexCandidates.size(), 2);
566 [ + - ]: 1 : BOOST_CHECK_EQUAL(cs1.setBlockIndexCandidates.count(validated_tip), 1);
567 [ + - ]: 1 : BOOST_CHECK_EQUAL(cs1.setBlockIndexCandidates.count(assumed_base), 1);
568 : :
569 : : // The assumed-valid tolerant chain has the assumed valid base as a
570 : : // candidate, but otherwise has none of the assumed-valid (which do not
571 : : // HAVE_DATA) blocks as candidates.
572 : : //
573 : : // Specifically:
574 : : // - All blocks below height 110 are not candidates, because cs2 chain tip
575 : : // has height 110 and they have less work than it does.
576 : : //
577 : : // - Block 110 is a candidate even though it does not have data, because it
578 : : // is the snapshot block, which is assumed valid.
579 : : //
580 : : // - Blocks 111-120 are added because they have data.
581 : :
582 : : // Check that block 90 is absent
583 [ + - ]: 1 : BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(validated_tip), 0);
584 : : // Check that block 109 is absent
585 [ + - ]: 1 : BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_base->pprev), 0);
586 : : // Check that block 110 is present
587 [ + - ]: 1 : BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_base), 1);
588 : : // Check that block 120 is present
589 [ + - ]: 1 : BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.count(assumed_tip), 1);
590 : : // Check that 11 blocks total are present.
591 [ + - ]: 1 : BOOST_CHECK_EQUAL(cs2.setBlockIndexCandidates.size(), num_indexes - last_assumed_valid_idx + 1);
592 : 1 : }
593 : :
594 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(loadblockindex_invalid_descendants, TestChain100Setup)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
595 : : {
596 [ - + ]: 1 : LOCK(Assert(m_node.chainman)->GetMutex());
597 : : // consider the chain of blocks grand_parent <- parent <- child
598 : : // intentionally mark:
599 : : // - grand_parent: BLOCK_FAILED_VALID
600 : : // - parent: BLOCK_FAILED_CHILD
601 : : // - child: not invalid
602 : : // Test that when the block index is loaded, all blocks are marked as BLOCK_FAILED_VALID
603 [ + - - + ]: 1 : auto* child{m_node.chainman->ActiveChain().Tip()};
604 : 1 : auto* parent{child->pprev};
605 : 1 : auto* grand_parent{parent->pprev};
606 : 1 : grand_parent->nStatus = (grand_parent->nStatus | BLOCK_FAILED_VALID);
607 : 1 : parent->nStatus = (parent->nStatus & ~BLOCK_FAILED_VALID) | BLOCK_FAILED_CHILD;
608 : 1 : child->nStatus = (child->nStatus & ~BLOCK_FAILED_VALID);
609 : :
610 : : // Reload block index to recompute block status validity flags.
611 [ + - ]: 1 : m_node.chainman->LoadBlockIndex();
612 : :
613 : : // check grand_parent, parent, child is marked as BLOCK_FAILED_VALID after reloading the block index
614 [ + - + - : 2 : BOOST_CHECK(grand_parent->nStatus & BLOCK_FAILED_VALID);
+ - ]
615 [ + - + - : 2 : BOOST_CHECK(parent->nStatus & BLOCK_FAILED_VALID);
+ - ]
616 [ + - + - : 2 : BOOST_CHECK(child->nStatus & BLOCK_FAILED_VALID);
+ - ]
617 : 1 : }
618 : :
619 : : //! Ensure that snapshot chainstate can be loaded when found on disk after a
620 : : //! restart, and that new blocks can be connected to both chainstates.
621 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_init, SnapshotTestSetup)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
622 : : {
623 [ - + ]: 1 : ChainstateManager& chainman = *Assert(m_node.chainman);
624 : 1 : Chainstate& bg_chainstate = chainman.ActiveChainstate();
625 : :
626 : 1 : this->SetupSnapshot();
627 : :
628 [ + - ]: 1 : fs::path snapshot_chainstate_dir = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
629 [ + - + - : 2 : BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
+ - + - ]
630 [ + - + - : 3 : BOOST_CHECK_EQUAL(snapshot_chainstate_dir, gArgs.GetDataDirNet() / "chainstate_snapshot");
+ - + - ]
631 : :
632 [ + - + - : 3 : BOOST_CHECK(WITH_LOCK(::cs_main, return chainman.CurrentChainstate().m_from_snapshot_blockhash));
+ - + - ]
633 [ + - + - ]: 3 : const uint256 snapshot_tip_hash = WITH_LOCK(chainman.GetMutex(),
634 : : return chainman.ActiveTip()->GetBlockHash());
635 : :
636 [ + + + - : 2 : BOOST_CHECK_EQUAL(WITH_LOCK(chainman.GetMutex(), return chainman.m_chainstates.size()), 2);
+ - ]
637 : :
638 : : // "Rewind" the background chainstate so that its tip is not at the
639 : : // base block of the snapshot - this is so after simulating a node restart,
640 : : // it will initialize instead of attempting to complete validation.
641 : : //
642 : : // Note that this is not a realistic use of DisconnectTip().
643 [ + - ]: 1 : DisconnectedBlockTransactions unused_pool{MAX_DISCONNECTED_TX_POOL_BYTES};
644 [ + - ]: 1 : BlockValidationState unused_state;
645 : 1 : {
646 [ + - - + : 1 : LOCK2(::cs_main, bg_chainstate.MempoolMutex());
+ - ]
647 [ + - + - : 2 : BOOST_CHECK(bg_chainstate.DisconnectTip(unused_state, &unused_pool));
+ - + - ]
648 [ + - ]: 1 : unused_pool.clear(); // to avoid queuedTx assertion errors on teardown
649 [ + - ]: 1 : }
650 [ + - - + : 1 : BOOST_CHECK_EQUAL(bg_chainstate.m_chain.Height(), 109);
+ - ]
651 : :
652 : : // Test that simulating a shutdown (resetting ChainstateManager) and then performing
653 : : // chainstate reinitializing successfully reloads both chainstates.
654 [ + - ]: 1 : ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
655 : :
656 [ + - + - : 1 : BOOST_TEST_MESSAGE("Performing Load/Verify/Activate of chainstate");
+ - ]
657 : :
658 : : // This call reinitializes the chainstates.
659 [ + - ]: 1 : this->LoadVerifyActivateChainstate();
660 : :
661 : 1 : {
662 [ + - ]: 1 : LOCK(chainman_restarted.GetMutex());
663 [ + - - + : 1 : BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 2);
+ - ]
664 : : // Background chainstate has height of 109 not 110 here due to a quirk
665 : : // of the LoadVerifyActivate only calling ActivateBestChain on one
666 : : // chainstate. The height would be 110 after a real restart, but it's
667 : : // fine for this test which is focused on the snapshot chainstate.
668 [ + - - + : 1 : BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[0]->m_chain.Height(), 109);
+ - ]
669 [ + - - + : 1 : BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[1]->m_chain.Height(), 210);
+ - ]
670 : :
671 [ + - + - : 2 : BOOST_CHECK(chainman_restarted.CurrentChainstate().m_from_snapshot_blockhash);
+ - ]
672 [ + - + - : 2 : BOOST_CHECK(chainman_restarted.CurrentChainstate().m_assumeutxo == Assumeutxo::UNVALIDATED);
+ - ]
673 : :
674 [ + - + - : 1 : BOOST_CHECK_EQUAL(chainman_restarted.ActiveTip()->GetBlockHash(), snapshot_tip_hash);
+ - ]
675 [ + - + - : 1 : BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
+ - ]
676 [ + - - + : 1 : BOOST_CHECK_EQUAL(chainman_restarted.HistoricalChainstate()->m_chain.Height(), 109);
+ - + - ]
677 : 0 : }
678 : :
679 [ + - + - : 1 : BOOST_TEST_MESSAGE(
+ - ]
680 : : "Ensure we can mine blocks on top of the initialized snapshot chainstate");
681 [ + - ]: 1 : mineBlocks(10);
682 : 1 : {
683 [ + - ]: 1 : LOCK(chainman_restarted.GetMutex());
684 [ + - + - : 1 : BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
+ - ]
685 : :
686 : : // Background chainstate should be unaware of new blocks on the snapshot
687 : : // chainstate, but the block disconnected above is now reattached.
688 [ + - - + : 1 : BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 2);
+ - ]
689 [ + - - + : 1 : BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[0]->m_chain.Height(), 110);
+ - ]
690 [ + - - + : 1 : BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates[1]->m_chain.Height(), 220);
+ - ]
691 [ + - + - : 1 : BOOST_CHECK_EQUAL(chainman_restarted.HistoricalChainstate(), nullptr);
+ - ]
692 : 1 : }
693 : 2 : }
694 : :
695 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_completion, SnapshotTestSetup)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
696 : : {
697 : 1 : this->SetupSnapshot();
698 : :
699 [ - + ]: 1 : ChainstateManager& chainman = *Assert(m_node.chainman);
700 : 1 : Chainstate& active_cs = chainman.ActiveChainstate();
701 [ + + ]: 2 : Chainstate& validated_cs{*Assert(WITH_LOCK(cs_main, return chainman.HistoricalChainstate()))};
702 : 1 : auto tip_cache_before_complete = active_cs.m_coinstip_cache_size_bytes;
703 : 1 : auto db_cache_before_complete = active_cs.m_coinsdb_cache_size_bytes;
704 : :
705 : 1 : SnapshotCompletionResult res;
706 : 1 : m_node.notifications->m_shutdown_on_fatal_error = false;
707 : :
708 [ + - ]: 1 : fs::path snapshot_chainstate_dir = *node::FindAssumeutxoChainstateDir(chainman.m_options.datadir);
709 [ + - + - : 2 : BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
+ - + - ]
710 [ + - + - : 3 : BOOST_CHECK_EQUAL(snapshot_chainstate_dir, gArgs.GetDataDirNet() / "chainstate_snapshot");
+ - + - ]
711 : :
712 [ + - + - : 3 : BOOST_CHECK(WITH_LOCK(::cs_main, return chainman.CurrentChainstate().m_from_snapshot_blockhash));
+ - + - ]
713 [ + - + - ]: 3 : const uint256 snapshot_tip_hash = WITH_LOCK(chainman.GetMutex(),
714 : : return chainman.ActiveTip()->GetBlockHash());
715 : :
716 [ + - + - ]: 3 : res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validated_cs, active_cs));
717 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(res, SnapshotCompletionResult::SUCCESS);
718 : :
719 [ + - + - : 3 : BOOST_CHECK(WITH_LOCK(::cs_main, return chainman.CurrentChainstate().m_assumeutxo == Assumeutxo::VALIDATED));
+ - + - ]
720 [ + - + - : 3 : BOOST_CHECK(WITH_LOCK(::cs_main, return chainman.CurrentChainstate().m_from_snapshot_blockhash));
+ - + - ]
721 [ + - + - : 2 : BOOST_CHECK_EQUAL(WITH_LOCK(chainman.GetMutex(), return chainman.HistoricalChainstate()), nullptr);
+ - ]
722 : :
723 : : // Cache should have been rebalanced and reallocated to the "only" remaining
724 : : // chainstate.
725 [ + - + - : 2 : BOOST_CHECK(active_cs.m_coinstip_cache_size_bytes > tip_cache_before_complete);
+ - ]
726 [ + - + - : 2 : BOOST_CHECK(active_cs.m_coinsdb_cache_size_bytes > db_cache_before_complete);
+ - ]
727 : :
728 : : // Trying completion again should return false.
729 [ + - + - ]: 3 : res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validated_cs, active_cs));
730 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(res, SnapshotCompletionResult::SKIPPED);
731 : :
732 : : // The invalid snapshot path should not have been used.
733 [ + - + - ]: 2 : fs::path snapshot_invalid_dir = gArgs.GetDataDirNet() / "chainstate_snapshot_INVALID";
734 [ + - + - : 2 : BOOST_CHECK(!fs::exists(snapshot_invalid_dir));
+ - + - ]
735 : : // chainstate_snapshot should still exist.
736 [ + - + - : 2 : BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
+ - + - ]
737 : :
738 : : // Test that simulating a shutdown (resetting ChainstateManager) and then performing
739 : : // chainstate reinitializing successfully cleans up the background-validation
740 : : // chainstate data, and we end up with a single chainstate that is at tip.
741 [ + - ]: 1 : ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
742 : :
743 [ + - + - : 1 : BOOST_TEST_MESSAGE("Performing Load/Verify/Activate of chainstate");
+ - ]
744 : :
745 : : // This call reinitializes the chainstates, and should clean up the now unnecessary
746 : : // background-validation leveldb contents.
747 [ + - ]: 1 : this->LoadVerifyActivateChainstate();
748 : :
749 [ + - + - : 2 : BOOST_CHECK(!fs::exists(snapshot_invalid_dir));
+ - + - ]
750 : : // chainstate_snapshot should now *not* exist.
751 [ + - + - : 2 : BOOST_CHECK(!fs::exists(snapshot_chainstate_dir));
+ - + - ]
752 : :
753 [ + - ]: 1 : const Chainstate& active_cs2 = chainman_restarted.ActiveChainstate();
754 : :
755 : 1 : {
756 [ + - ]: 1 : LOCK(chainman_restarted.GetMutex());
757 [ + - - + : 1 : BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 1);
+ - ]
758 [ + - + - : 2 : BOOST_CHECK(!chainman_restarted.CurrentChainstate().m_from_snapshot_blockhash);
+ - ]
759 [ + - + - : 2 : BOOST_CHECK(active_cs2.m_coinstip_cache_size_bytes > tip_cache_before_complete);
+ - ]
760 [ + - + - : 2 : BOOST_CHECK(active_cs2.m_coinsdb_cache_size_bytes > db_cache_before_complete);
+ - ]
761 : :
762 [ + - + - : 1 : BOOST_CHECK_EQUAL(chainman_restarted.ActiveTip()->GetBlockHash(), snapshot_tip_hash);
+ - ]
763 [ + - + - : 1 : BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
+ - + - ]
764 : 0 : }
765 : :
766 [ + - + - : 1 : BOOST_TEST_MESSAGE(
+ - ]
767 : : "Ensure we can mine blocks on top of the \"new\" IBD chainstate");
768 [ + - ]: 1 : mineBlocks(10);
769 : 1 : {
770 [ + - ]: 1 : LOCK(chainman_restarted.GetMutex());
771 [ + - + - : 1 : BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
+ - + - ]
772 : 1 : }
773 : 2 : }
774 : :
775 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_completion_hash_mismatch, SnapshotTestSetup)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
776 : : {
777 : 1 : auto chainstates = this->SetupSnapshot();
778 [ - + ]: 1 : Chainstate& validation_chainstate = *std::get<0>(chainstates);
779 [ - + ]: 1 : Chainstate& unvalidated_cs = *std::get<1>(chainstates);
780 [ - + ]: 1 : ChainstateManager& chainman = *Assert(m_node.chainman);
781 : 1 : SnapshotCompletionResult res;
782 : 1 : m_node.notifications->m_shutdown_on_fatal_error = false;
783 : :
784 : : // Test tampering with the IBD UTXO set with an extra coin to ensure it causes
785 : : // snapshot completion to fail.
786 [ + - + - ]: 3 : CCoinsViewCache& ibd_coins = WITH_LOCK(::cs_main,
787 : : return validation_chainstate.CoinsTip());
788 : 1 : Coin badcoin;
789 : 1 : badcoin.out.nValue = m_rng.rand32();
790 : 1 : badcoin.nHeight = 1;
791 : 1 : badcoin.out.scriptPubKey.assign(m_rng.randbits(6), 0);
792 [ + - ]: 1 : Txid txid = Txid::FromUint256(m_rng.rand256());
793 [ + - ]: 1 : ibd_coins.AddCoin(COutPoint(txid, 0), std::move(badcoin), false);
794 : :
795 [ + - + - ]: 2 : fs::path snapshot_chainstate_dir = gArgs.GetDataDirNet() / "chainstate_snapshot";
796 [ + - + - : 2 : BOOST_CHECK(fs::exists(snapshot_chainstate_dir));
+ - + - ]
797 : :
798 : 1 : {
799 [ + - + - ]: 2 : ASSERT_DEBUG_LOG("failed to validate the -assumeutxo snapshot state");
800 [ + - + - ]: 3 : res = WITH_LOCK(::cs_main, return chainman.MaybeValidateSnapshot(validation_chainstate, unvalidated_cs));
801 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(res, SnapshotCompletionResult::HASH_MISMATCH);
802 : 1 : }
803 : :
804 : 1 : {
805 [ + - ]: 1 : LOCK(chainman.GetMutex());
806 [ + - - + : 1 : BOOST_CHECK_EQUAL(chainman.m_chainstates.size(), 2);
+ - ]
807 [ + - + - : 2 : BOOST_CHECK(chainman.m_chainstates[0]->m_assumeutxo == Assumeutxo::VALIDATED);
+ - ]
808 [ + - + - : 2 : BOOST_CHECK(!chainman.m_chainstates[0]->SnapshotBase());
+ - + - ]
809 [ + - + - : 2 : BOOST_CHECK(chainman.m_chainstates[1]->m_assumeutxo == Assumeutxo::INVALID);
+ - ]
810 [ + - + - : 2 : BOOST_CHECK(chainman.m_chainstates[1]->SnapshotBase());
+ - + - ]
811 : 0 : }
812 : :
813 [ + - + - ]: 2 : fs::path snapshot_invalid_dir = gArgs.GetDataDirNet() / "chainstate_snapshot_INVALID";
814 [ + - + - : 2 : BOOST_CHECK(fs::exists(snapshot_invalid_dir));
+ - + - ]
815 : :
816 : : // Test that simulating a shutdown (resetting ChainstateManager) and then performing
817 : : // chainstate reinitializing successfully loads only the fully-validated
818 : : // chainstate data, and we end up with a single chainstate that is at tip.
819 [ + - ]: 1 : ChainstateManager& chainman_restarted = this->SimulateNodeRestart();
820 : :
821 [ + - + - : 1 : BOOST_TEST_MESSAGE("Performing Load/Verify/Activate of chainstate");
+ - ]
822 : :
823 : : // This call reinitializes the chainstates, and should clean up the now unnecessary
824 : : // background-validation leveldb contents.
825 [ + - ]: 1 : this->LoadVerifyActivateChainstate();
826 : :
827 [ + - + - : 2 : BOOST_CHECK(fs::exists(snapshot_invalid_dir));
+ - + - ]
828 [ + - + - : 2 : BOOST_CHECK(!fs::exists(snapshot_chainstate_dir));
+ - + - ]
829 : :
830 : 1 : {
831 [ + - ]: 1 : LOCK(::cs_main);
832 [ + - - + : 1 : BOOST_CHECK_EQUAL(chainman_restarted.m_chainstates.size(), 1);
+ - ]
833 [ + - + - : 2 : BOOST_CHECK(!chainman_restarted.CurrentChainstate().m_from_snapshot_blockhash);
+ - ]
834 [ + - + - : 1 : BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 210);
+ - + - ]
835 : 0 : }
836 : :
837 [ + - + - : 1 : BOOST_TEST_MESSAGE(
+ - ]
838 : : "Ensure we can mine blocks on top of the \"new\" IBD chainstate");
839 [ + - ]: 1 : mineBlocks(10);
840 : 1 : {
841 [ + - ]: 1 : LOCK(::cs_main);
842 [ + - + - : 1 : BOOST_CHECK_EQUAL(chainman_restarted.ActiveHeight(), 220);
+ - + - ]
843 : 1 : }
844 : 2 : }
845 : :
846 : : /** Helper function to parse args into args_man and return the result of applying them to opts */
847 : : template <typename Options>
848 : 15 : util::Result<Options> SetOptsFromArgs(ArgsManager& args_man, Options opts,
849 : : const std::vector<const char*>& args)
850 : : {
851 [ + - - + ]: 30 : const auto argv{Cat({"ignore"}, args)};
852 [ - + ]: 15 : std::string error{};
853 [ - + + - : 15 : if (!args_man.ParseParameters(argv.size(), argv.data(), error)) {
- + ]
854 [ # # ]: 0 : return util::Error{Untranslated("ParseParameters failed with error: " + error)};
855 : : }
856 [ + - ]: 15 : const auto result{node::ApplyArgsManOptions(args_man, opts)};
857 [ + + ]: 23 : if (!result) return util::Error{util::ErrorString(result)};
858 : 22 : return opts;
859 [ - - + - ]: 34 : }
860 : :
861 [ + - + - : 7 : BOOST_FIXTURE_TEST_CASE(chainstatemanager_args, BasicTestingSetup)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
862 : : {
863 : : //! Try to apply the provided args to a ChainstateManager::Options
864 : 16 : auto get_opts = [&](const std::vector<const char*>& args) {
865 [ + + + - ]: 15 : static kernel::Notifications notifications{};
866 : 15 : static const ChainstateManager::Options options{
867 [ + - ]: 1 : .chainparams = ::Params(),
868 : : .datadir = {},
869 [ + + + - ]: 16 : .notifications = notifications};
870 [ + - ]: 30 : return SetOptsFromArgs(*this->m_node.args, options, args);
871 : 1 : };
872 : : //! Like get_opts, but requires the provided args to be valid and unwraps the result
873 : 12 : auto get_valid_opts = [&](const std::vector<const char*>& args) {
874 : 11 : const auto result{get_opts(args)};
875 [ + - + - : 22 : BOOST_REQUIRE_MESSAGE(result, util::ErrorString(result).original);
+ - ]
876 [ + - ]: 11 : return *result;
877 : 12 : };
878 : :
879 : : // test -assumevalid
880 [ + - + - ]: 3 : BOOST_CHECK(!get_valid_opts({}).assumed_valid_block);
881 [ + - + - ]: 2 : BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid="}).assumed_valid_block, uint256::ZERO);
882 [ + - + - ]: 2 : BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid=0"}).assumed_valid_block, uint256::ZERO);
883 [ + - + - ]: 2 : BOOST_CHECK_EQUAL(get_valid_opts({"-noassumevalid"}).assumed_valid_block, uint256::ZERO);
884 [ + - + - ]: 2 : BOOST_CHECK_EQUAL(get_valid_opts({"-assumevalid=0x12"}).assumed_valid_block, uint256{0x12});
885 : :
886 : 1 : std::string assume_valid{"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"};
887 [ + - - + : 2 : BOOST_CHECK_EQUAL(get_valid_opts({("-assumevalid=" + assume_valid).c_str()}).assumed_valid_block, uint256::FromHex(assume_valid));
+ - + - +
- + - +
- ]
888 : :
889 [ + - + - : 2 : BOOST_CHECK(!get_opts({"-assumevalid=xyz"})); // invalid hex characters
+ - + - +
- ]
890 [ + - + - : 2 : BOOST_CHECK(!get_opts({"-assumevalid=01234567890123456789012345678901234567890123456789012345678901234"})); // > 64 hex chars
+ - + - +
- ]
891 : :
892 : : // test -minimumchainwork
893 [ + - + - : 3 : BOOST_CHECK(!get_valid_opts({}).minimum_chain_work);
+ - + - ]
894 [ + - + - : 2 : BOOST_CHECK_EQUAL(get_valid_opts({"-minimumchainwork=0"}).minimum_chain_work, arith_uint256());
+ - + - +
- ]
895 [ + - + - : 2 : BOOST_CHECK_EQUAL(get_valid_opts({"-nominimumchainwork"}).minimum_chain_work, arith_uint256());
+ - + - +
- ]
896 [ + - + - : 2 : BOOST_CHECK_EQUAL(get_valid_opts({"-minimumchainwork=0x1234"}).minimum_chain_work, arith_uint256{0x1234});
+ - + - +
- ]
897 : :
898 [ + - ]: 1 : std::string minimum_chainwork{"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"};
899 [ + - - + : 3 : BOOST_CHECK_EQUAL(get_valid_opts({("-minimumchainwork=" + minimum_chainwork).c_str()}).minimum_chain_work, UintToArith256(uint256::FromHex(minimum_chainwork).value()));
+ - + - +
- + - + -
+ - ]
900 : :
901 [ + - + - : 2 : BOOST_CHECK(!get_opts({"-minimumchainwork=xyz"})); // invalid hex characters
+ - + - +
- ]
902 [ + - + - : 2 : BOOST_CHECK(!get_opts({"-minimumchainwork=01234567890123456789012345678901234567890123456789012345678901234"})); // > 64 hex chars
+ - + - ]
903 : 1 : }
904 : :
905 : : BOOST_AUTO_TEST_SUITE_END()
|