Bitcoin Core 30.99.0
P2P Digital Currency
validation_chainstate_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2020-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/amount.h>
9#include <random.h>
10#include <rpc/blockchain.h>
11#include <script/script.h>
12#include <sync.h>
14#include <test/util/coins.h>
15#include <test/util/random.h>
17#include <uint256.h>
18#include <util/check.h>
19#include <validation.h>
20
21#include <vector>
22
23#include <boost/test/unit_test.hpp>
24
25BOOST_FIXTURE_TEST_SUITE(validation_chainstate_tests, ChainTestingSetup)
26
27
29BOOST_AUTO_TEST_CASE(validation_chainstate_resize_caches)
30{
32 CTxMemPool& mempool = *Assert(m_node.mempool);
33 Chainstate& c1 = WITH_LOCK(cs_main, return manager.InitializeChainstate(&mempool));
34 c1.InitCoinsDB(
35 /*cache_size_bytes=*/1 << 23, /*in_memory=*/true, /*should_wipe=*/false);
36 WITH_LOCK(::cs_main, c1.InitCoinsCache(1 << 23));
37 BOOST_REQUIRE(c1.LoadGenesisBlock()); // Need at least one block loaded to be able to flush caches
38
39 // Add a coin to the in-memory cache, upsize once, then downsize.
40 {
42 const auto outpoint = AddTestCoin(m_rng, c1.CoinsTip());
43
44 // Set a meaningless bestblock value in the coinsview cache - otherwise we won't
45 // flush during ResizecoinsCaches() and will subsequently hit an assertion.
46 c1.CoinsTip().SetBestBlock(m_rng.rand256());
47
48 BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));
49
50 c1.ResizeCoinsCaches(
51 1 << 24, // upsizing the coinsview cache
52 1 << 22 // downsizing the coinsdb cache
53 );
54
55 // View should still have the coin cached, since we haven't destructed the cache on upsize.
56 BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));
57
58 c1.ResizeCoinsCaches(
59 1 << 22, // downsizing the coinsview cache
60 1 << 23 // upsizing the coinsdb cache
61 );
62
63 // The view cache should be empty since we had to destruct to downsize.
64 BOOST_CHECK(!c1.CoinsTip().HaveCoinInCache(outpoint));
65 }
66}
67
68BOOST_FIXTURE_TEST_CASE(connect_tip_does_not_cache_inputs_on_failed_connect, TestChain100Setup)
69{
70 Chainstate& chainstate{Assert(m_node.chainman)->ActiveChainstate()};
71
72 COutPoint outpoint;
73 {
75 outpoint = AddTestCoin(m_rng, chainstate.CoinsTip());
76 chainstate.CoinsTip().Flush(/*reallocate_cache=*/false);
77 }
78
80 tx.vin.emplace_back(outpoint);
81 tx.vout.emplace_back(MAX_MONEY, CScript{} << OP_TRUE);
82
83 const auto tip{WITH_LOCK(cs_main, return chainstate.m_chain.Tip()->GetBlockHash())};
84 const CBlock block{CreateBlock({tx}, CScript{} << OP_TRUE, chainstate)};
85 BOOST_CHECK(Assert(m_node.chainman)->ProcessNewBlock(std::make_shared<CBlock>(block), true, true, nullptr));
86
88 BOOST_CHECK_EQUAL(tip, chainstate.m_chain.Tip()->GetBlockHash()); // block rejected
89 BOOST_CHECK(!chainstate.CoinsTip().HaveCoinInCache(outpoint)); // input not cached
90}
91
97{
99 const auto get_notify_tip{[&]() {
100 LOCK(m_node.notifications->m_tip_block_mutex);
101 BOOST_REQUIRE(m_node.notifications->TipBlock());
102 return *m_node.notifications->TipBlock();
103 }};
104 uint256 curr_tip = get_notify_tip();
105
106 // Mine 10 more blocks, putting at us height 110 where a valid assumeutxo value can
107 // be found.
108 mineBlocks(10);
109
110 // After adding some blocks to the tip, best block should have changed.
111 BOOST_CHECK(get_notify_tip() != curr_tip);
112
113 // Grab block 1 from disk; we'll add it to the background chain later.
114 std::shared_ptr<CBlock> pblockone = std::make_shared<CBlock>();
115 {
117 chainman.m_blockman.ReadBlock(*pblockone, *chainman.ActiveChain()[1]);
118 }
119
120 BOOST_REQUIRE(CreateAndActivateUTXOSnapshot(
121 this, NoMalleation, /*reset_chainstate=*/ true));
122
123 // Ensure our active chain is the snapshot chainstate.
125
126 curr_tip = get_notify_tip();
127
128 // Mine a new block on top of the activated snapshot chainstate.
129 mineBlocks(1); // Defined in TestChain100Setup.
130
131 // After adding some blocks to the snapshot tip, best block should have changed.
132 BOOST_CHECK(get_notify_tip() != curr_tip);
133
134 curr_tip = get_notify_tip();
135
136 Chainstate& background_cs{*Assert(WITH_LOCK(::cs_main, return chainman.HistoricalChainstate()))};
137
138 // Append the first block to the background chain.
140 CBlockIndex* pindex = nullptr;
141 const CChainParams& chainparams = Params();
142 bool newblock = false;
143
144 // TODO: much of this is inlined from ProcessNewBlock(); just reuse PNB()
145 // once it is changed to support multiple chainstates.
146 {
148 bool checked = CheckBlock(*pblockone, state, chainparams.GetConsensus());
149 BOOST_CHECK(checked);
150 bool accepted = chainman.AcceptBlock(
151 pblockone, state, &pindex, true, nullptr, &newblock, true);
152 BOOST_CHECK(accepted);
153 }
154
155 // UpdateTip is called here
156 bool block_added = background_cs.ActivateBestChain(state, pblockone);
157
158 // Ensure tip is as expected
159 BOOST_CHECK_EQUAL(background_cs.m_chain.Tip()->GetBlockHash(), pblockone->GetHash());
160
161 // get_notify_tip() should be unchanged after adding a block to the background
162 // validation chain.
163 BOOST_CHECK(block_added);
164 BOOST_CHECK_EQUAL(curr_tip, get_notify_tip());
165}
166
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
node::NodeContext m_node
Definition: bitcoin-gui.cpp:43
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:113
Definition: block.h:74
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:77
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:89
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:204
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:193
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:188
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:551
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:686
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
kernel::ChainstateRole GetRole() const EXCLUSIVE_LOCKS_REQUIRED(void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe)
Return the current role of the chainstate.
const std::optional< uint256 > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
Definition: validation.h:637
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Definition: validation.h:936
Chainstate * HistoricalChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return historical chainstate targeting a specific block, if any.
Definition: validation.h:1124
SnapshotCompletionResult MaybeValidateSnapshot(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & CurrentChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Try to validate an assumeutxo snapshot by using a validated historical chainstate targeted at the sna...
Definition: validation.h:1115
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1161
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1034
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 ReadBlock(CBlock &block, const FlatFilePos &pos, const std::optional< uint256 > &expected_hash) const
Functions for disk access for blocks.
256-bit opaque blob.
Definition: uint256.h:195
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()
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:17
#define BOOST_CHECK(expr)
Definition: object.cpp:16
@ OP_TRUE
Definition: script.h:84
A mutable version of CTransaction.
Definition: transaction.h:358
std::vector< CTxOut > vout
Definition: transaction.h:360
std::vector< CTxIn > vin
Definition: transaction.h:359
Testing setup that performs all steps up until right before ChainstateManager gets initialized.
Definition: setup_common.h:106
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:146
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:258
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:289
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(connect_tip_does_not_cache_inputs_on_failed_connect, TestChain100Setup)
BOOST_AUTO_TEST_CASE(validation_chainstate_resize_caches)
Test resizing coins-related Chainstate caches during runtime.