Bitcoin Core 31.99.0
P2P Digital Currency
baseindex_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 <addresstype.h>
6#include <blockfilter.h>
7#include <chain.h>
8#include <chainparams.h>
9#include <coins.h>
10#include <common/args.h>
12#include <index/base.h>
15#include <index/txindex.h>
17#include <interfaces/chain.h>
18#include <kernel/types.h>
19#include <key.h>
20#include <node/context.h>
21#include <primitives/block.h>
22#include <script/script.h>
23#include <sync.h>
24#include <test/util/mining.h>
26#include <test/util/time.h>
28#include <tinyformat.h>
29#include <util/byte_units.h>
30#include <util/check.h>
31#include <util/fs.h>
32#include <validation.h>
33
34#include <boost/test/unit_test.hpp>
35
36#include <chrono>
37#include <functional>
38#include <future>
39#include <memory>
40#include <string>
41#include <thread>
42#include <utility>
43#include <vector>
44
46
47using IndexFactory = std::function<std::unique_ptr<BaseIndex>(node::NodeContext&)>;
48
49static const std::vector<std::pair<std::string, IndexFactory>> INDEX_FACTORIES{
50 {"coinstatsindex", [](node::NodeContext& node) -> std::unique_ptr<BaseIndex> {
51 return std::make_unique<CoinStatsIndex>(interfaces::MakeChain(node), /*n_cache_size=*/1_MiB); }},
52 {"txindex", [](node::NodeContext& node) -> std::unique_ptr<BaseIndex> {
53 return std::make_unique<TxIndex>(interfaces::MakeChain(node), /*n_cache_size=*/1_MiB); }},
54 {"txospenderindex", [](node::NodeContext& node) -> std::unique_ptr<BaseIndex> {
55 return std::make_unique<TxoSpenderIndex>(interfaces::MakeChain(node), /*n_cache_size=*/1_MiB); }},
56 {"blockfilterindex", [](node::NodeContext& node) -> std::unique_ptr<BaseIndex> {
57 return std::make_unique<BlockFilterIndex>(interfaces::MakeChain(node), BlockFilterType::BASIC, /*n_cache_size=*/1_MiB); }},
58};
59
60// Tests of generic BaseIndex functionality that is independent of which
61// concrete index is being used.
62BOOST_AUTO_TEST_SUITE(baseindex_tests)
63
64// Test that the index does not commit ahead of the chainstate's last
65// flushed block. If it did, a subsequent unclean shutdown would corrupt
66// the index, because during reverting it would require blocks that were
67// never flushed to disk.
68BOOST_FIXTURE_TEST_CASE(baseindex_no_commit_ahead_of_flush, TestChain100Setup)
69{
70 Chainstate& chainstate = Assert(m_node.chainman)->ActiveChainstate();
71 for (const auto& [index_name, make_index] : INDEX_FACTORIES) {
72 BOOST_TEST_INFO_SCOPE(index_name);
73 const int tip_height{WITH_LOCK(cs_main, return m_node.chainman->ActiveChain().Tip()->nHeight)};
74 auto sync_index = [&](bool do_flush, int expected_sync_height, int expected_commit_height) {
75 auto index{make_index(m_node)};
76 BOOST_REQUIRE(index->Init());
77 index->Sync();
78 if (do_flush) {
79 chainstate.ForceFlushStateToDisk();
80 m_node.chain->context()->validation_signals->SyncWithValidationInterfaceQueue();
81 }
82 BOOST_CHECK_EQUAL(index->GetSummary().best_block_height, expected_sync_height);
83 index->Stop();
84 // Reload index to see which block data was actually committed.
85 BOOST_REQUIRE(index->Init());
86 BOOST_CHECK_EQUAL(index->GetSummary().best_block_height, expected_commit_height);
87 index->Stop();
88 };
89
90 // Part 1: Sync, then "crash" (stop without flushing). Models a node that
91 // started up, had its index catch up, but never flushed before going down.
92 // The end-of-sync Commit() runs at the chain tip but m_last_flushed_block
93 // is null, so it is skipped.
94 sync_index(false, tip_height, 0);
95
96 // Part 2: Restart cleanly. Sync, force a chainstate flush, and drain the
97 // validation queue so the index's ChainStateFlushed callback runs.
98 // Now m_last_flushed_block == tip and the index can commit.
99 sync_index(true, tip_height, tip_height);
100
101 // Part 3: Connect a new block on the chain without flushing
102 // (m_last_flushed_block stays at tip_height). For a real node this would
103 // happen in parallel with Sync(). Here we do it before Sync() to make the
104 // race state deterministic.
105 CreateAndProcessBlock({}, CScript() << OP_TRUE);
106 sync_index(false, tip_height + 1, tip_height);
107 }
108}
109
110// Test shutdown between BlockConnected and ChainStateFlushed notifications,
111// make sure index is not corrupted and reloads at the last committed height.
113{
114 Chainstate& chainstate = Assert(m_node.chainman)->ActiveChainstate();
115 const CChainParams& params = Params();
116 const int tip_height{WITH_LOCK(cs_main, return chainstate.m_chain.Height())};
117 chainstate.ForceFlushStateToDisk();
118 // Drain the notification before registering any index.
119 m_node.chain->context()->validation_signals->SyncWithValidationInterfaceQueue();
120 for (const auto& [index_name, make_index] : INDEX_FACTORIES) {
121 BOOST_TEST_INFO_SCOPE(index_name);
122 {
123 auto index{make_index(m_node)};
124 BOOST_REQUIRE(index->Init());
125 index->Sync();
126 std::shared_ptr<const CBlock> new_block;
127 CBlockIndex* new_block_index = nullptr;
128 {
129 const CScript script_pub_key{CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG};
130 const CBlock block = this->CreateBlock({}, script_pub_key);
131
132 new_block = std::make_shared<CBlock>(block);
133
134 LOCK(cs_main);
136 BOOST_CHECK(CheckBlock(block, state, params.GetConsensus()));
137 BOOST_CHECK(m_node.chainman->AcceptBlock(new_block, state, &new_block_index, true, nullptr, nullptr, true));
138 CCoinsViewCache view(&chainstate.CoinsTip());
139 BOOST_CHECK(chainstate.ConnectBlock(block, state, new_block_index, view));
140 }
141 // Send block connected notification, then stop the index without
142 // sending a chainstate flushed notification. Prior to #24138, this
143 // would cause the index to be corrupted and fail to reload.
144 ValidationInterfaceTest::BlockConnected(ChainstateRole{}, *index, new_block, new_block_index);
145 index->Stop();
146 }
147
148 {
149 auto index{make_index(m_node)};
150 BOOST_REQUIRE(index->Init());
151 // Make sure the index reloads from the pre-crash commit.
152 BOOST_CHECK_EQUAL(index->GetSummary().best_block_height, tip_height);
153 BOOST_REQUIRE(index->StartBackgroundSync());
154 index->Stop();
155 }
156 }
157}
158
160{
161private:
163 std::unique_ptr<BaseIndex::DB> m_db;
164 std::shared_future<void> m_blocker;
166
167public:
168 explicit IndexReorgCrash(std::unique_ptr<interfaces::Chain> chain, std::shared_future<void> blocker, int blocking_height, FakeNodeClock& clock)
169 : BaseIndex(std::move(chain), "test index", "testidx"), m_clock(clock), m_blocker(blocker), m_blocking_height(blocking_height)
170 {
171 const fs::path path = gArgs.GetDataDirNet() / "index";
172 fs::create_directories(path);
173 m_db = std::make_unique<BaseIndex::DB>(path / "db", /*n_cache_size=*/0, /*f_memory=*/true, /*f_wipe=*/false);
174 }
175
176 bool AllowPrune() const override { return false; }
177 BaseIndex::DB& GetDB() const override { return *m_db; }
178
179 bool CustomAppend(const interfaces::BlockInfo& block) override
180 {
181 // Simulate a delay so new blocks can get connected during the initial sync
182 if (block.height == m_blocking_height) m_blocker.wait();
183
184 // Move mock time forward so the best index gets updated only when we are not at the blocking height
185 if (block.height == m_blocking_height - 1 || block.height > m_blocking_height) {
186 m_clock += 31s;
187 }
188
189 return true;
190 }
191};
192
194{
195 std::promise<void> promise;
196 std::shared_future<void> blocker(promise.get_future());
197 int blocking_height = WITH_LOCK(cs_main, return m_node.chainman->ActiveChain().Tip()->nHeight);
198
199 IndexReorgCrash index{interfaces::MakeChain(m_node), blocker, blocking_height, m_clock};
200 BOOST_REQUIRE(index.Init());
201 BOOST_REQUIRE(index.StartBackgroundSync());
202
203 auto func_wait_until = [&](int height, std::chrono::milliseconds timeout) {
204 auto deadline = std::chrono::steady_clock::now() + timeout;
205 while (index.GetSummary().best_block_height < height) {
206 if (std::chrono::steady_clock::now() > deadline) {
207 BOOST_FAIL(strprintf("Timeout waiting for index height %d (current: %d)", height, index.GetSummary().best_block_height));
208 return;
209 }
210 std::this_thread::sleep_for(100ms);
211 }
212 };
213
214 // Wait until the index is one block before the fork point
215 func_wait_until(blocking_height - 1, /*timeout=*/5s);
216
217 // Create a fork to trigger the reorg
218 std::vector<std::shared_ptr<CBlock>> fork;
219 const CBlockIndex* prev_tip = WITH_LOCK(cs_main, return m_node.chainman->ActiveChain().Tip()->pprev);
220 BOOST_REQUIRE(BuildChain(m_node, prev_tip, GetScriptForDestination(PKHash(GenerateRandomKey().GetPubKey())), 3, fork));
221
222 for (const auto& block : fork) {
223 BOOST_REQUIRE(m_node.chainman->ProcessNewBlock(block, /*force_processing=*/true, /*min_pow_checked=*/true, nullptr));
224 }
225
226 // Unblock the index thread so it can process the reorg
227 promise.set_value();
228 // Wait for the index to reach the new tip
229 func_wait_until(blocking_height + 2, 5s);
230 index.Stop();
231}
232
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
ArgsManager gArgs
Definition: args.cpp:38
std::function< std::unique_ptr< BaseIndex >(node::NodeContext &)> IndexFactory
static const std::vector< std::pair< std::string, IndexFactory > > INDEX_FACTORIES
BOOST_FIXTURE_TEST_CASE(baseindex_no_commit_ahead_of_flush, TestChain100Setup)
node::NodeContext m_node
Definition: bitcoin-gui.cpp:47
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:116
fs::path GetDataDirNet() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get data directory path with appended network identifier.
Definition: args.cpp:328
The database stores a block locator of the chain the database is synced to so that the index can effi...
Definition: base.h:65
Base class for indices of blockchain data.
Definition: base.h:55
Definition: block.h:74
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
int Height() const
Return the maximal height in the chain.
Definition: chain.h:425
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
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:437
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:554
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:628
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:689
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view) EXCLUSIVE_LOCKS_REQUIRED(boo ConnectBlock)(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the best known block, and make it the tip of the block chain.
Definition: validation.h:784
void ForceFlushStateToDisk(bool wipe_cache=true)
Flush all changes to disk.
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
Definition: time.h:54
bool CustomAppend(const interfaces::BlockInfo &block) override
Write update index entries for a newly connected block.
IndexReorgCrash(std::unique_ptr< interfaces::Chain > chain, std::shared_future< void > blocker, int blocking_height, FakeNodeClock &clock)
std::unique_ptr< BaseIndex::DB > m_db
BaseIndex::DB & GetDB() const override
bool AllowPrune() const override
FakeNodeClock & m_clock
std::shared_future< void > m_blocker
static void BlockConnected(const kernel::ChainstateRole &role, CValidationInterface &obj, const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Definition: validation.cpp:59
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()
BOOST_CHECK_EQUAL(headers.FindFirst("key"), "value")
is a home for simple enum and struct type definitions that can be used internally by functions in the...
CKey GenerateRandomKey(bool compressed) noexcept
Definition: key.cpp:354
std::unique_ptr< Chain > MakeChain(node::NodeContext &node)
Return implementation of Chain interface.
Definition: messages.h:21
#define BOOST_CHECK(expr)
Definition: object.cpp:16
@ OP_CHECKSIG
Definition: script.h:191
@ OP_TRUE
Definition: script.h:85
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:68
static bool GetPubKey(const SigningProvider &provider, const SignatureData &sigdata, const CKeyID &address, CPubKey &pubkey)
Definition: sign.cpp:238
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:139
Block data sent with blockConnected, blockDisconnected notifications.
Definition: chain.h:19
Information about chainstate that notifications are sent from.
Definition: types.h:18
NodeContext struct containing references to chain state and connection state.
Definition: context.h:59
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:76
std::unique_ptr< interfaces::Chain > chain
Definition: context.h:80
#define LOCK(cs)
Definition: sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:299
bool BuildChain(const NodeContext &node, const CBlockIndex *pindex, const CScript &coinbase_script_pub_key, size_t length, std::vector< std::shared_ptr< CBlock > > &chain)
Build a chain of length coinbase-only blocks on top of pindex (which need not be the active tip,...
Definition: mining.cpp:78
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
Functions for validating blocks and updating the block tree.