Bitcoin Core 32.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
88 // Drain in-flight validation callbacks before destroying the index.
89 m_node.chain->context()->validation_signals->SyncWithValidationInterfaceQueue();
90 // shutdown sequence (c.f. Shutdown() in init.cpp)
91 index->Stop();
92 };
93
94 // Part 1: Sync, then "crash" (stop without flushing). Models a node that
95 // started up, had its index catch up, but never flushed before going down.
96 // The end-of-sync Commit() runs at the chain tip but m_last_flushed_block
97 // is null, so it is skipped.
98 sync_index(false, tip_height, 0);
99
100 // Part 2: Restart cleanly. Sync, force a chainstate flush, and drain the
101 // validation queue so the index's ChainStateFlushed callback runs.
102 // Now m_last_flushed_block == tip and the index can commit.
103 sync_index(true, tip_height, tip_height);
104
105 // Part 3: Connect a new block on the chain without flushing
106 // (m_last_flushed_block stays at tip_height). For a real node this would
107 // happen in parallel with Sync(). Here we do it before Sync() to make the
108 // race state deterministic.
109 CreateAndProcessBlock({}, CScript() << OP_TRUE);
110 sync_index(false, tip_height + 1, tip_height);
111 }
112}
113
114// Test shutdown between BlockConnected and ChainStateFlushed notifications,
115// make sure index is not corrupted and reloads at the last committed height.
117{
118 Chainstate& chainstate = Assert(m_node.chainman)->ActiveChainstate();
119 const CChainParams& params = Params();
120 const int tip_height{WITH_LOCK(cs_main, return chainstate.m_chain.Height())};
121 chainstate.ForceFlushStateToDisk();
122 // Drain the notification before registering any index.
123 m_node.chain->context()->validation_signals->SyncWithValidationInterfaceQueue();
124 for (const auto& [index_name, make_index] : INDEX_FACTORIES) {
125 BOOST_TEST_INFO_SCOPE(index_name);
126 {
127 auto index{make_index(m_node)};
128 BOOST_REQUIRE(index->Init());
129 index->Sync();
130 std::shared_ptr<const CBlock> new_block;
131 CBlockIndex* new_block_index = nullptr;
132 {
133 const CScript script_pub_key{CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG};
134 const CBlock block = this->CreateBlock({}, script_pub_key);
135
136 new_block = std::make_shared<CBlock>(block);
137
138 LOCK(cs_main);
140 BOOST_CHECK(CheckBlock(block, state, params.GetConsensus()));
141 BOOST_CHECK(m_node.chainman->AcceptBlock(new_block, state, &new_block_index, true, nullptr, nullptr, true));
142 CCoinsViewCache view(&chainstate.CoinsTip());
143 BOOST_CHECK(chainstate.ConnectBlock(block, state, new_block_index, view));
144 }
145 // Send block connected notification, then stop the index without
146 // sending a chainstate flushed notification. Prior to #24138, this
147 // would cause the index to be corrupted and fail to reload.
148 ValidationInterfaceTest::BlockConnected(ChainstateRole{}, *index, new_block, new_block_index);
149 index->Stop();
150 }
151
152 {
153 auto index{make_index(m_node)};
154 BOOST_REQUIRE(index->Init());
155 // Make sure the index reloads from the pre-crash commit.
156 BOOST_CHECK_EQUAL(index->GetSummary().best_block_height, tip_height);
157 BOOST_REQUIRE(index->StartBackgroundSync());
158 index->Stop();
159 }
160 }
161}
162
164{
165private:
167 std::unique_ptr<BaseIndex::DB> m_db;
168 std::shared_future<void> m_blocker;
170
171public:
172 explicit IndexReorgCrash(std::unique_ptr<interfaces::Chain> chain, std::shared_future<void> blocker, int blocking_height, FakeNodeClock& clock)
173 : BaseIndex(std::move(chain), "test index", "testidx"), m_clock(clock), m_blocker(blocker), m_blocking_height(blocking_height)
174 {
175 const fs::path path = gArgs.GetDataDirNet() / "index";
176 fs::create_directories(path);
177 m_db = std::make_unique<BaseIndex::DB>(path / "db", /*n_cache_size=*/0, /*f_memory=*/true, /*f_wipe=*/false);
178 }
179
180 bool AllowPrune() const override { return false; }
181 BaseIndex::DB& GetDB() const override { return *m_db; }
182
183 bool CustomAppend(const interfaces::BlockInfo& block) override
184 {
185 // Simulate a delay so new blocks can get connected during the initial sync
186 if (block.height == m_blocking_height) m_blocker.wait();
187
188 // Move mock time forward so the best index gets updated only when we are not at the blocking height
189 if (block.height == m_blocking_height - 1 || block.height > m_blocking_height) {
190 m_clock += 31s;
191 }
192
193 return true;
194 }
195};
196
198{
199 std::promise<void> promise;
200 std::shared_future<void> blocker(promise.get_future());
201 int blocking_height = WITH_LOCK(cs_main, return m_node.chainman->ActiveChain().Tip()->nHeight);
202
203 IndexReorgCrash index{interfaces::MakeChain(m_node), blocker, blocking_height, m_clock};
204 BOOST_REQUIRE(index.Init());
205 BOOST_REQUIRE(index.StartBackgroundSync());
206
207 auto func_wait_until = [&](int height, std::chrono::milliseconds timeout) {
208 auto deadline = std::chrono::steady_clock::now() + timeout;
209 while (index.GetSummary().best_block_height < height) {
210 if (std::chrono::steady_clock::now() > deadline) {
211 BOOST_FAIL(strprintf("Timeout waiting for index height %d (current: %d)", height, index.GetSummary().best_block_height));
212 return;
213 }
214 std::this_thread::sleep_for(100ms);
215 }
216 };
217
218 // Wait until the index is one block before the fork point
219 func_wait_until(blocking_height - 1, /*timeout=*/5s);
220
221 // Create a fork to trigger the reorg
222 std::vector<std::shared_ptr<CBlock>> fork;
223 const CBlockIndex* prev_tip = WITH_LOCK(cs_main, return m_node.chainman->ActiveChain().Tip()->pprev);
224 BOOST_REQUIRE(BuildChain(m_node, prev_tip, GetScriptForDestination(PKHash(GenerateRandomKey().GetPubKey())), 3, fork));
225
226 for (const auto& block : fork) {
227 BOOST_REQUIRE(m_node.chainman->ProcessNewBlock(block, /*force_processing=*/true, /*min_pow_checked=*/true, nullptr));
228 }
229
230 // The index thread is blocked and not done
231 BOOST_CHECK(!index.GetSummary().synced);
232
233 // Unblock the index thread so it can process the reorg
234 promise.set_value();
235 // Wait for the index to reach the new tip
236 func_wait_until(blocking_height + 2, 5s);
237
238 // Drain unused BlockConnected events, to avoid unsafe memory races during destruction
239 m_node.chain->context()->validation_signals->SyncWithValidationInterfaceQueue();
240 // shutdown sequence (c.f. Shutdown() in init.cpp)
241 index.Stop();
242}
243
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:48
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:550
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:630
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:694
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:789
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.