Bitcoin Core 28.99.0
P2P Digital Currency
validation_chainstate_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2020-2022 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>
8#include <random.h>
9#include <rpc/blockchain.h>
10#include <sync.h>
12#include <test/util/coins.h>
13#include <test/util/random.h>
15#include <uint256.h>
16#include <util/check.h>
17#include <validation.h>
18
19#include <vector>
20
21#include <boost/test/unit_test.hpp>
22
23BOOST_FIXTURE_TEST_SUITE(validation_chainstate_tests, ChainTestingSetup)
24
25
27BOOST_AUTO_TEST_CASE(validation_chainstate_resize_caches)
28{
30 CTxMemPool& mempool = *Assert(m_node.mempool);
31 Chainstate& c1 = WITH_LOCK(cs_main, return manager.InitializeChainstate(&mempool));
32 c1.InitCoinsDB(
33 /*cache_size_bytes=*/1 << 23, /*in_memory=*/true, /*should_wipe=*/false);
34 WITH_LOCK(::cs_main, c1.InitCoinsCache(1 << 23));
35 BOOST_REQUIRE(c1.LoadGenesisBlock()); // Need at least one block loaded to be able to flush caches
36
37 // Add a coin to the in-memory cache, upsize once, then downsize.
38 {
40 const auto outpoint = AddTestCoin(m_rng, c1.CoinsTip());
41
42 // Set a meaningless bestblock value in the coinsview cache - otherwise we won't
43 // flush during ResizecoinsCaches() and will subsequently hit an assertion.
44 c1.CoinsTip().SetBestBlock(m_rng.rand256());
45
46 BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));
47
48 c1.ResizeCoinsCaches(
49 1 << 24, // upsizing the coinsview cache
50 1 << 22 // downsizing the coinsdb cache
51 );
52
53 // View should still have the coin cached, since we haven't destructed the cache on upsize.
54 BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));
55
56 c1.ResizeCoinsCaches(
57 1 << 22, // downsizing the coinsview cache
58 1 << 23 // upsizing the coinsdb cache
59 );
60
61 // The view cache should be empty since we had to destruct to downsize.
62 BOOST_CHECK(!c1.CoinsTip().HaveCoinInCache(outpoint));
63 }
64}
65
71{
73 const auto get_notify_tip{[&]() {
74 LOCK(m_node.notifications->m_tip_block_mutex);
75 return m_node.notifications->m_tip_block;
76 }};
77 uint256 curr_tip = get_notify_tip();
78
79 // Mine 10 more blocks, putting at us height 110 where a valid assumeutxo value can
80 // be found.
81 mineBlocks(10);
82
83 // After adding some blocks to the tip, best block should have changed.
84 BOOST_CHECK(get_notify_tip() != curr_tip);
85
86 // Grab block 1 from disk; we'll add it to the background chain later.
87 std::shared_ptr<CBlock> pblockone = std::make_shared<CBlock>();
88 {
90 chainman.m_blockman.ReadBlockFromDisk(*pblockone, *chainman.ActiveChain()[1]);
91 }
92
94 this, NoMalleation, /*reset_chainstate=*/ true));
95
96 // Ensure our active chain is the snapshot chainstate.
98
99 curr_tip = get_notify_tip();
100
101 // Mine a new block on top of the activated snapshot chainstate.
102 mineBlocks(1); // Defined in TestChain100Setup.
103
104 // After adding some blocks to the snapshot tip, best block should have changed.
105 BOOST_CHECK(get_notify_tip() != curr_tip);
106
107 curr_tip = get_notify_tip();
108
109 BOOST_CHECK_EQUAL(chainman.GetAll().size(), 2);
110
111 Chainstate& background_cs{*Assert([&]() -> Chainstate* {
112 for (Chainstate* cs : chainman.GetAll()) {
113 if (cs != &chainman.ActiveChainstate()) {
114 return cs;
115 }
116 }
117 return nullptr;
118 }())};
119
120 // Append the first block to the background chain.
122 CBlockIndex* pindex = nullptr;
123 const CChainParams& chainparams = Params();
124 bool newblock = false;
125
126 // TODO: much of this is inlined from ProcessNewBlock(); just reuse PNB()
127 // once it is changed to support multiple chainstates.
128 {
130 bool checked = CheckBlock(*pblockone, state, chainparams.GetConsensus());
131 BOOST_CHECK(checked);
132 bool accepted = chainman.AcceptBlock(
133 pblockone, state, &pindex, true, nullptr, &newblock, true);
134 BOOST_CHECK(accepted);
135 }
136
137 // UpdateTip is called here
138 bool block_added = background_cs.ActivateBestChain(state, pblockone);
139
140 // Ensure tip is as expected
141 BOOST_CHECK_EQUAL(background_cs.m_chain.Tip()->GetBlockHash(), pblockone->GetHash());
142
143 // get_notify_tip() should be unchanged after adding a block to the background
144 // validation chain.
145 BOOST_CHECK(block_added);
146 BOOST_CHECK_EQUAL(curr_tip, get_notify_tip());
147}
148
node::NodeContext m_node
Definition: bitcoin-gui.cpp:42
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:85
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:141
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:81
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:93
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:179
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:168
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:304
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:505
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:611
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
ChainstateRole GetRole() const EXCLUSIVE_LOCKS_REQUIRED(void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe, fs::path leveldb_name="chainstate")
Return the current role of the chainstate.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:866
bool IsSnapshotActive() const
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1111
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1080
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1007
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
256-bit opaque blob.
Definition: uint256.h:190
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
static void pool cs
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
Testing setup that performs all steps up until right before ChainstateManager gets initialized.
Definition: setup_common.h:105
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:139
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:68
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:72
std::unique_ptr< KernelNotifications > notifications
Issues blocking calls about sync status, errors and warnings.
Definition: context.h:86
#define LOCK(cs)
Definition: sync.h:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
static bool CreateAndActivateUTXOSnapshot(TestingSetup *fixture, F malleation=NoMalleation, bool reset_chainstate=false, bool in_memory_chainstate=false)
Create and activate a UTXO snapshot, optionally providing a function to malleate the snapshot.
Definition: chainstate.h:33
const auto NoMalleation
Definition: chainstate.h:19
COutPoint AddTestCoin(FastRandomContext &rng, CCoinsViewCache &coins_view)
Create a Coin with DynamicMemoryUsage of 80 bytes and add it to the given view.
Definition: coins.cpp:16
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
Functions for validating blocks and updating the block tree.
BOOST_FIXTURE_TEST_CASE(chainstate_update_tip, TestChain100Setup)
Test UpdateTip behavior for both active and background chainstates.
BOOST_AUTO_TEST_CASE(validation_chainstate_resize_caches)
Test resizing coins-related Chainstate caches during runtime.