Bitcoin Core  27.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>
6 #include <consensus/validation.h>
7 #include <random.h>
8 #include <rpc/blockchain.h>
9 #include <sync.h>
10 #include <test/util/chainstate.h>
11 #include <test/util/coins.h>
12 #include <test/util/random.h>
13 #include <test/util/setup_common.h>
14 #include <uint256.h>
15 #include <validation.h>
16 
17 #include <vector>
18 
19 #include <boost/test/unit_test.hpp>
20 
21 BOOST_FIXTURE_TEST_SUITE(validation_chainstate_tests, ChainTestingSetup)
22 
23 BOOST_AUTO_TEST_CASE(validation_chainstate_resize_caches)
26 {
28  CTxMemPool& mempool = *Assert(m_node.mempool);
29  Chainstate& c1 = WITH_LOCK(cs_main, return manager.InitializeChainstate(&mempool));
30  c1.InitCoinsDB(
31  /*cache_size_bytes=*/1 << 23, /*in_memory=*/true, /*should_wipe=*/false);
32  WITH_LOCK(::cs_main, c1.InitCoinsCache(1 << 23));
33  BOOST_REQUIRE(c1.LoadGenesisBlock()); // Need at least one block loaded to be able to flush caches
34 
35  // Add a coin to the in-memory cache, upsize once, then downsize.
36  {
37  LOCK(::cs_main);
38  const auto outpoint = AddTestCoin(c1.CoinsTip());
39 
40  // Set a meaningless bestblock value in the coinsview cache - otherwise we won't
41  // flush during ResizecoinsCaches() and will subsequently hit an assertion.
43 
44  BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));
45 
46  c1.ResizeCoinsCaches(
47  1 << 24, // upsizing the coinsview cache
48  1 << 22 // downsizing the coinsdb cache
49  );
50 
51  // View should still have the coin cached, since we haven't destructed the cache on upsize.
52  BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));
53 
54  c1.ResizeCoinsCaches(
55  1 << 22, // downsizing the coinsview cache
56  1 << 23 // upsizing the coinsdb cache
57  );
58 
59  // The view cache should be empty since we had to destruct to downsize.
60  BOOST_CHECK(!c1.CoinsTip().HaveCoinInCache(outpoint));
61  }
62 }
63 
69 {
71  uint256 curr_tip = ::g_best_block;
72 
73  // Mine 10 more blocks, putting at us height 110 where a valid assumeutxo value can
74  // be found.
75  mineBlocks(10);
76 
77  // After adding some blocks to the tip, best block should have changed.
78  BOOST_CHECK(::g_best_block != curr_tip);
79 
80  // Grab block 1 from disk; we'll add it to the background chain later.
81  std::shared_ptr<CBlock> pblockone = std::make_shared<CBlock>();
82  {
83  LOCK(::cs_main);
84  chainman.m_blockman.ReadBlockFromDisk(*pblockone, *chainman.ActiveChain()[1]);
85  }
86 
87  BOOST_REQUIRE(CreateAndActivateUTXOSnapshot(
88  this, NoMalleation, /*reset_chainstate=*/ true));
89 
90  // Ensure our active chain is the snapshot chainstate.
91  BOOST_CHECK(WITH_LOCK(::cs_main, return chainman.IsSnapshotActive()));
92 
93  curr_tip = ::g_best_block;
94 
95  // Mine a new block on top of the activated snapshot chainstate.
96  mineBlocks(1); // Defined in TestChain100Setup.
97 
98  // After adding some blocks to the snapshot tip, best block should have changed.
99  BOOST_CHECK(::g_best_block != curr_tip);
100 
101  curr_tip = ::g_best_block;
102 
103  BOOST_CHECK_EQUAL(chainman.GetAll().size(), 2);
104 
105  Chainstate& background_cs{*[&] {
106  for (Chainstate* cs : chainman.GetAll()) {
107  if (cs != &chainman.ActiveChainstate()) {
108  return cs;
109  }
110  }
111  assert(false);
112  }()};
113 
114  // Append the first block to the background chain.
115  BlockValidationState state;
116  CBlockIndex* pindex = nullptr;
117  const CChainParams& chainparams = Params();
118  bool newblock = false;
119 
120  // TODO: much of this is inlined from ProcessNewBlock(); just reuse PNB()
121  // once it is changed to support multiple chainstates.
122  {
123  LOCK(::cs_main);
124  bool checked = CheckBlock(*pblockone, state, chainparams.GetConsensus());
125  BOOST_CHECK(checked);
126  bool accepted = chainman.AcceptBlock(
127  pblockone, state, &pindex, true, nullptr, &newblock, true);
128  BOOST_CHECK(accepted);
129  }
130 
131  // UpdateTip is called here
132  bool block_added = background_cs.ActivateBestChain(state, pblockone);
133 
134  // Ensure tip is as expected
135  BOOST_CHECK_EQUAL(background_cs.m_chain.Tip()->GetBlockHash(), pblockone->GetHash());
136 
137  // g_best_block should be unchanged after adding a block to the background
138  // validation chain.
139  BOOST_CHECK(block_added);
140  BOOST_CHECK_EQUAL(curr_tip, ::g_best_block);
141 }
142 
node::NodeContext m_node
Definition: bitcoin-gui.cpp:37
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:77
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:177
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:166
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:302
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:491
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:597
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:850
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1069
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
Definition: validation.h:1068
bool IsSnapshotActive() const
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1037
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:966
bool AcceptBlock(const std::shared_ptr< const CBlock > &pblock, BlockValidationState &state, CBlockIndex **ppindex, bool fRequested, const FlatFilePos *dbp, bool *fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Sufficiently validate a block for disk storage (and store on disk).
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
256-bit opaque blob.
Definition: uint256.h:106
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
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:69
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:104
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:58
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:62
#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(CCoinsViewCache &coins_view)
Create a Coin with DynamicMemoryUsage of 80 bytes and add it to the given view.
Definition: coins.cpp:16
static uint256 InsecureRand256()
Definition: random.h:50
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
Functions for validating blocks and updating the block tree.
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:114
assert(!tx.IsCoinBase())
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.