Bitcoin Core  22.99.0
P2P Digital Currency
validation_chainstate_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020-2021 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 <random.h>
7 #include <uint256.h>
8 #include <consensus/validation.h>
9 #include <sync.h>
10 #include <rpc/blockchain.h>
11 #include <test/util/chainstate.h>
12 #include <test/util/setup_common.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, TestingSetup)
20 
21 BOOST_AUTO_TEST_CASE(validation_chainstate_resize_caches)
24 {
25  ChainstateManager manager;
26  WITH_LOCK(::cs_main, manager.m_blockman.m_block_tree_db = std::make_unique<CBlockTreeDB>(1 << 20, true));
27  CTxMemPool mempool;
28 
30  auto add_coin = [](CCoinsViewCache& coins_view) -> COutPoint {
31  Coin newcoin;
32  uint256 txid = InsecureRand256();
33  COutPoint outp{txid, 0};
34  newcoin.nHeight = 1;
35  newcoin.out.nValue = InsecureRand32();
36  newcoin.out.scriptPubKey.assign((uint32_t)56, 1);
37  coins_view.AddCoin(outp, std::move(newcoin), false);
38 
39  return outp;
40  };
41 
42  CChainState& c1 = WITH_LOCK(cs_main, return manager.InitializeChainstate(&mempool));
43  c1.InitCoinsDB(
44  /*cache_size_bytes=*/1 << 23, /*in_memory=*/true, /*should_wipe=*/false);
45  WITH_LOCK(::cs_main, c1.InitCoinsCache(1 << 23));
46  BOOST_REQUIRE(c1.LoadGenesisBlock()); // Need at least one block loaded to be able to flush caches
47 
48  // Add a coin to the in-memory cache, upsize once, then downsize.
49  {
50  LOCK(::cs_main);
51  auto outpoint = add_coin(c1.CoinsTip());
52 
53  // Set a meaningless bestblock value in the coinsview cache - otherwise we won't
54  // flush during ResizecoinsCaches() and will subsequently hit an assertion.
56 
57  BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));
58 
59  c1.ResizeCoinsCaches(
60  1 << 24, // upsizing the coinsview cache
61  1 << 22 // downsizing the coinsdb cache
62  );
63 
64  // View should still have the coin cached, since we haven't destructed the cache on upsize.
65  BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));
66 
67  c1.ResizeCoinsCaches(
68  1 << 22, // downsizing the coinsview cache
69  1 << 23 // upsizing the coinsdb cache
70  );
71 
72  // The view cache should be empty since we had to destruct to downsize.
73  BOOST_CHECK(!c1.CoinsTip().HaveCoinInCache(outpoint));
74  }
75 
76  // Avoid triggering the address sanitizer.
77  WITH_LOCK(::cs_main, manager.Unload());
78 }
79 
85 {
87  uint256 curr_tip = ::g_best_block;
88 
89  // Mine 10 more blocks, putting at us height 110 where a valid assumeutxo value can
90  // be found.
91  mineBlocks(10);
92 
93  // After adding some blocks to the tip, best block should have changed.
94  BOOST_CHECK(::g_best_block != curr_tip);
95 
96  BOOST_REQUIRE(CreateAndActivateUTXOSnapshot(m_node, m_path_root));
97 
98  // Ensure our active chain is the snapshot chainstate.
99  BOOST_CHECK(chainman.IsSnapshotActive());
100 
101  curr_tip = ::g_best_block;
102 
103  // Mine a new block on top of the activated snapshot chainstate.
104  mineBlocks(1); // Defined in TestChain100Setup.
105 
106  // After adding some blocks to the snapshot tip, best block should have changed.
107  BOOST_CHECK(::g_best_block != curr_tip);
108 
109  curr_tip = ::g_best_block;
110 
111  BOOST_CHECK_EQUAL(chainman.GetAll().size(), 2);
112 
113  CChainState& background_cs{*[&] {
114  for (CChainState* cs : chainman.GetAll()) {
115  if (cs != &chainman.ActiveChainstate()) {
116  return cs;
117  }
118  }
119  assert(false);
120  }()};
121 
122  // Create a block to append to the validation chain.
123  std::vector<CMutableTransaction> noTxns;
124  CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
125  CBlock validation_block = this->CreateBlock(noTxns, scriptPubKey, background_cs);
126  auto pblock = std::make_shared<const CBlock>(validation_block);
127  BlockValidationState state;
128  CBlockIndex* pindex = nullptr;
129  const CChainParams& chainparams = Params();
130  bool newblock = false;
131 
132  // TODO: much of this is inlined from ProcessNewBlock(); just reuse PNB()
133  // once it is changed to support multiple chainstates.
134  {
135  LOCK(::cs_main);
136  bool checked = CheckBlock(*pblock, state, chainparams.GetConsensus());
137  BOOST_CHECK(checked);
138  bool accepted = background_cs.AcceptBlock(
139  pblock, state, &pindex, true, nullptr, &newblock);
140  BOOST_CHECK(accepted);
141  }
142  // UpdateTip is called here
143  bool block_added = background_cs.ActivateBestChain(state, pblock);
144 
145  // Ensure tip is as expected
146  BOOST_CHECK_EQUAL(background_cs.m_chain.Tip()->GetBlockHash(), validation_block.GetHash());
147 
148  // g_best_block should be unchanged after adding a block to the background
149  // validation chain.
150  BOOST_CHECK(block_added);
151  BOOST_CHECK_EQUAL(curr_tip, ::g_best_block);
152 }
153 
BOOST_AUTO_TEST_CASE
BOOST_AUTO_TEST_CASE(validation_chainstate_resize_caches)
Test resizing coins-related CChainState caches during runtime.
Definition: validation_chainstate_tests.cpp:23
assert
assert(!tx.IsCoinBase())
BlockValidationState
Definition: validation.h:141
setup_common.h
sync.h
CTxMemPool
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:429
uint256.h
InsecureRand256
static uint256 InsecureRand256()
Definition: setup_common.h:73
m_node
node::NodeContext m_node
Definition: bitcoin-gui.cpp:36
validation.h
CChainParams
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:69
add_coin
static void add_coin(const CAmount &nValue, int nInput, std::vector< OutputGroup > &set)
Definition: coin_selection.cpp:80
WITH_LOCK
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:270
CChainParams::GetConsensus
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:82
InsecureRand32
static uint32_t InsecureRand32()
Definition: setup_common.h:72
chainparams.h
ChainstateManager::ActiveChainstate
CChainState & ActiveChainstate() const
The most-work chain.
Definition: validation.cpp:5025
BOOST_FIXTURE_TEST_SUITE
#define BOOST_FIXTURE_TEST_SUITE(a, b)
Definition: object.cpp:14
BOOST_AUTO_TEST_SUITE_END
BOOST_AUTO_TEST_SUITE_END()
Assert
#define Assert(val)
Identity function.
Definition: check.h:57
CBlockHeader::GetHash
uint256 GetHash() const
Definition: block.cpp:11
cs
static void pool cs
Definition: mempool_eviction.cpp:12
Coin::out
CTxOut out
unspent transaction output
Definition: coins.h:34
CTxOut::nValue
CAmount nValue
Definition: transaction.h:151
ChainstateManager::IsSnapshotActive
bool IsSnapshotActive() const
Definition: validation.cpp:5032
random.h
ToByteVector
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:60
Coin
A UTXO entry.
Definition: coins.h:30
Coin::nHeight
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:40
CTxOut::scriptPubKey
CScript scriptPubKey
Definition: transaction.h:152
g_best_block
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:143
CCoinsViewCache::HaveCoinInCache
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:164
TestChain100Setup
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:124
ChainstateManager::GetAll
CChainState &InitializeChainstate(CTxMemPool *mempool, const std::optional< uint256 > &snapshot_blockhash=std::nullopt) LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * GetAll)()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
Definition: validation.h:906
uint256
256-bit opaque blob.
Definition: uint256.h:126
CChainState
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:459
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
ChainstateManager
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:792
CheckBlock
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
Functions for validating blocks and updating the block tree.
Definition: validation.cpp:3240
CBlock
Definition: block.h:62
prevector::assign
void assign(size_type n, const T &val)
Definition: prevector.h:218
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:213
CChainState::CoinsTip
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:562
CCoinsViewCache::SetBestBlock
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:175
chainstate.h
LOCK
#define LOCK(cs)
Definition: sync.h:226
CreateAndActivateUTXOSnapshot
static bool CreateAndActivateUTXOSnapshot(node::NodeContext &node, const fs::path root, F malleation=NoMalleation)
Create and activate a UTXO snapshot, optionally providing a function to malleate the snapshot.
Definition: chainstate.h:27
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:561
node::NodeContext::chainman
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:48
CChainState::InitCoinsDB
void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe, std::string leveldb_name="chainstate")
Initialize the CoinsViews UTXO set database management data structures.
Definition: validation.cpp:1452
TestingSetup
Testing setup that configures a complete environment.
Definition: setup_common.h:107
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
blockchain.h
BOOST_FIXTURE_TEST_CASE
BOOST_FIXTURE_TEST_CASE(chainstate_update_tip, TestChain100Setup)
Test UpdateTip behavior for both active and background chainstates.
Definition: validation_chainstate_tests.cpp:84
cs_main
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:138
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:151
CChainState::LoadGenesisBlock
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
Definition: validation.cpp:4099
OP_CHECKSIG
@ OP_CHECKSIG
Definition: script.h:183
BOOST_CHECK
#define BOOST_CHECK(expr)
Definition: object.cpp:17
BOOST_CHECK_EQUAL
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
ChainstateManager::m_blockman
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:862