Bitcoin Core  24.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/setup_common.h>
12 #include <uint256.h>
13 #include <validation.h>
14 
15 #include <vector>
16 
17 #include <boost/test/unit_test.hpp>
18 
19 BOOST_FIXTURE_TEST_SUITE(validation_chainstate_tests, ChainTestingSetup)
20 
21 BOOST_AUTO_TEST_CASE(validation_chainstate_resize_caches)
24 {
26  CTxMemPool& mempool = *Assert(m_node.mempool);
27 
29  auto add_coin = [](CCoinsViewCache& coins_view) -> COutPoint {
30  Coin newcoin;
31  uint256 txid = InsecureRand256();
32  COutPoint outp{txid, 0};
33  newcoin.nHeight = 1;
34  newcoin.out.nValue = InsecureRand32();
35  newcoin.out.scriptPubKey.assign(uint32_t{56}, 1);
36  coins_view.AddCoin(outp, std::move(newcoin), false);
37 
38  return outp;
39  };
40 
41  Chainstate& c1 = WITH_LOCK(cs_main, return manager.InitializeChainstate(&mempool));
42  c1.InitCoinsDB(
43  /*cache_size_bytes=*/1 << 23, /*in_memory=*/true, /*should_wipe=*/false);
44  WITH_LOCK(::cs_main, c1.InitCoinsCache(1 << 23));
45  BOOST_REQUIRE(c1.LoadGenesisBlock()); // Need at least one block loaded to be able to flush caches
46 
47  // Add a coin to the in-memory cache, upsize once, then downsize.
48  {
49  LOCK(::cs_main);
50  auto outpoint = add_coin(c1.CoinsTip());
51 
52  // Set a meaningless bestblock value in the coinsview cache - otherwise we won't
53  // flush during ResizecoinsCaches() and will subsequently hit an assertion.
55 
56  BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));
57 
58  c1.ResizeCoinsCaches(
59  1 << 24, // upsizing the coinsview cache
60  1 << 22 // downsizing the coinsdb cache
61  );
62 
63  // View should still have the coin cached, since we haven't destructed the cache on upsize.
64  BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));
65 
66  c1.ResizeCoinsCaches(
67  1 << 22, // downsizing the coinsview cache
68  1 << 23 // upsizing the coinsdb cache
69  );
70 
71  // The view cache should be empty since we had to destruct to downsize.
72  BOOST_CHECK(!c1.CoinsTip().HaveCoinInCache(outpoint));
73  }
74 }
75 
81 {
83  uint256 curr_tip = ::g_best_block;
84 
85  // Mine 10 more blocks, putting at us height 110 where a valid assumeutxo value can
86  // be found.
87  mineBlocks(10);
88 
89  // After adding some blocks to the tip, best block should have changed.
90  BOOST_CHECK(::g_best_block != curr_tip);
91 
92  BOOST_REQUIRE(CreateAndActivateUTXOSnapshot(
93  this, NoMalleation, /*reset_chainstate=*/ true));
94 
95  // Ensure our active chain is the snapshot chainstate.
96  BOOST_CHECK(WITH_LOCK(::cs_main, return chainman.IsSnapshotActive()));
97 
98  curr_tip = ::g_best_block;
99 
100  // Mine a new block on top of the activated snapshot chainstate.
101  mineBlocks(1); // Defined in TestChain100Setup.
102 
103  // After adding some blocks to the snapshot tip, best block should have changed.
104  BOOST_CHECK(::g_best_block != curr_tip);
105 
106  curr_tip = ::g_best_block;
107 
108  BOOST_CHECK_EQUAL(chainman.GetAll().size(), 2);
109 
110  Chainstate& background_cs{*[&] {
111  for (Chainstate* cs : chainman.GetAll()) {
112  if (cs != &chainman.ActiveChainstate()) {
113  return cs;
114  }
115  }
116  assert(false);
117  }()};
118 
119  // Create a block to append to the validation chain.
120  std::vector<CMutableTransaction> noTxns;
121  CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
122  CBlock validation_block = this->CreateBlock(noTxns, scriptPubKey, background_cs);
123  auto pblock = std::make_shared<const CBlock>(validation_block);
124  BlockValidationState state;
125  CBlockIndex* pindex = nullptr;
126  const CChainParams& chainparams = Params();
127  bool newblock = false;
128 
129  // TODO: much of this is inlined from ProcessNewBlock(); just reuse PNB()
130  // once it is changed to support multiple chainstates.
131  {
132  LOCK(::cs_main);
133  bool checked = CheckBlock(*pblock, state, chainparams.GetConsensus());
134  BOOST_CHECK(checked);
135  bool accepted = background_cs.AcceptBlock(
136  pblock, state, &pindex, true, nullptr, &newblock, true);
137  BOOST_CHECK(accepted);
138  }
139  // UpdateTip is called here
140  bool block_added = background_cs.ActivateBestChain(state, pblock);
141 
142  // Ensure tip is as expected
143  BOOST_CHECK_EQUAL(background_cs.m_chain.Tip()->GetBlockHash(), validation_block.GetHash());
144 
145  // g_best_block should be unchanged after adding a block to the background
146  // validation chain.
147  BOOST_CHECK(block_added);
148  BOOST_CHECK_EQUAL(curr_tip, ::g_best_block);
149 }
150 
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:73
uint256 GetHash() const
Definition: block.cpp:11
Definition: block.h:69
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:151
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:70
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:82
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:213
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:175
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:164
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:36
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:411
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:316
CScript scriptPubKey
Definition: transaction.h:161
CAmount nValue
Definition: transaction.h:160
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:441
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe, fs::path leveldb_name="chainstate")
Initialize the CoinsViews UTXO set database management data structures.
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:540
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:802
Chainstate & ActiveChainstate() const
The most-work chain.
bool IsSnapshotActive() const
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:941
A UTXO entry.
Definition: coins.h:31
CTxOut out
unspent transaction output
Definition: coins.h:34
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:40
void assign(size_type n, const T &val)
Definition: prevector.h:220
256-bit opaque blob.
Definition: uint256.h:119
static void add_coin(const CAmount &nValue, int nInput, std::vector< OutputGroup > &set)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
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
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:63
@ OP_CHECKSIG
Definition: script.h:186
static uint256 InsecureRand256()
Definition: setup_common.h:75
static uint32_t InsecureRand32()
Definition: setup_common.h:74
Testing setup that performs all steps up until right before ChainstateManager gets initialized.
Definition: setup_common.h:99
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:134
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:50
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:54
#define LOCK(cs)
Definition: sync.h:258
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:302
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
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:110
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.