Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
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.
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.
69{
70 Chainstate& chainstate = Assert(m_node.chainman)->ActiveChainstate();
71 for (const auto& [index_name, make_index] : INDEX_FACTORIES) {
73 const int tip_height{WITH_LOCK(cs_main, return m_node.chainman->ActiveChain().Tip()->nHeight)};
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 StopIndex(*index, m_node);
89 };
90
91 // Part 1: Sync, then "crash" (stop without flushing). Models a node that
92 // started up, had its index catch up, but never flushed before going down.
93 // The end-of-sync Commit() runs at the chain tip but m_last_flushed_block
94 // is null, so it is skipped.
95 sync_index(false, tip_height, 0);
96
97 // Part 2: Restart cleanly. Sync, force a chainstate flush, and drain the
98 // validation queue so the index's ChainStateFlushed callback runs.
99 // Now m_last_flushed_block == tip and the index can commit.
100 sync_index(true, tip_height, tip_height);
101
102 // Part 3: Connect a new block on the chain without flushing
103 // (m_last_flushed_block stays at tip_height). For a real node this would
104 // happen in parallel with Sync(). Here we do it before Sync() to make the
105 // race state deterministic.
106 CreateAndProcessBlock({}, CScript() << OP_TRUE);
107 sync_index(false, tip_height + 1, tip_height);
108 }
109}
110
111// Test shutdown between BlockConnected and ChainStateFlushed notifications,
112// make sure index is not corrupted and reloads at the last committed height.
114{
115 Chainstate& chainstate = Assert(m_node.chainman)->ActiveChainstate();
116 const CChainParams& params = Params();
117 const int tip_height{WITH_LOCK(cs_main, return chainstate.m_chain.Height())};
118 chainstate.ForceFlushStateToDisk();
119 // Drain the notification before registering any index.
120 m_node.chain->context()->validation_signals->SyncWithValidationInterfaceQueue();
121 for (const auto& [index_name, make_index] : INDEX_FACTORIES) {
123 {
124 auto index{make_index(m_node)};
125 BOOST_REQUIRE(index->Init());
126 index->Sync();
127 std::shared_ptr<const CBlock> new_block;
128 CBlockIndex* new_block_index = nullptr;
129 {
130 const CScript script_pub_key{CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG};
131 const CBlock block = this->CreateBlock({}, script_pub_key);
132
133 new_block = std::make_shared<CBlock>(block);
134
135 LOCK(cs_main);
137 BOOST_CHECK(CheckBlock(block, state, params.GetConsensus()));
138 BOOST_CHECK(m_node.chainman->AcceptBlock(new_block, state, &new_block_index, true, nullptr, nullptr, true));
139 CCoinsViewCache view(&chainstate.CoinsTip());
140 BOOST_CHECK(chainstate.ConnectBlock(block, state, new_block_index, view));
141 }
142 // Send block connected notification, then stop the index without
143 // sending a chainstate flushed notification. Prior to #24138, this
144 // would cause the index to be corrupted and fail to reload.
146 index->Stop();
147 }
148
149 {
150 auto index{make_index(m_node)};
151 BOOST_REQUIRE(index->Init());
152 // Make sure the index reloads from the pre-crash commit.
153 BOOST_CHECK_EQUAL(index->GetSummary().best_block_height, tip_height);
154 BOOST_REQUIRE(index->StartBackgroundSync());
155 index->Stop();
156 }
157 }
158}
159
161{
162private:
164 std::unique_ptr<BaseIndex::DB> m_db;
165 std::shared_future<void> m_blocker;
167
168public:
169 explicit IndexReorgCrash(std::unique_ptr<interfaces::Chain> chain, std::shared_future<void> blocker, int blocking_height, FakeNodeClock& clock)
170 : BaseIndex(std::move(chain), "test index", "testidx"), m_clock(clock), m_blocker(blocker), m_blocking_height(blocking_height)
171 {
172 const fs::path path = gArgs.GetDataDirNet() / "index";
173 fs::create_directories(path);
174 m_db = std::make_unique<BaseIndex::DB>(path / "db", /*n_cache_size=*/0, /*f_memory=*/true, /*f_wipe=*/false);
175 }
176
177 bool AllowPrune() const override { return false; }
178 BaseIndex::DB& GetDB() const override { return *m_db; }
179
180 bool CustomAppend(const interfaces::BlockInfo& block) override
181 {
182 // Simulate a delay so new blocks can get connected during the initial sync
183 if (block.height == m_blocking_height) m_blocker.wait();
184
185 // Move mock time forward so the best index gets updated only when we are not at the blocking height
186 if (block.height == m_blocking_height - 1 || block.height > m_blocking_height) {
187 m_clock += 31s;
188 }
189
190 return true;
191 }
192};
193
195{
196 std::promise<void> promise;
197 std::shared_future<void> blocker(promise.get_future());
198 int blocking_height = WITH_LOCK(cs_main, return m_node.chainman->ActiveChain().Tip()->nHeight);
199
201 BOOST_REQUIRE(index.Init());
202 BOOST_REQUIRE(index.StartBackgroundSync());
203
204 auto func_wait_until = [&](int height, std::chrono::milliseconds timeout) {
205 auto deadline = std::chrono::steady_clock::now() + timeout;
206 while (index.GetSummary().best_block_height < height) {
207 if (std::chrono::steady_clock::now() > deadline) {
208 BOOST_FAIL(strprintf("Timeout waiting for index height %d (current: %d)", height, index.GetSummary().best_block_height));
209 return;
210 }
211 std::this_thread::sleep_for(100ms);
212 }
213 };
214
215 // Wait until the index is one block before the fork point
216 func_wait_until(blocking_height - 1, /*timeout=*/5s);
217
218 // Create a fork to trigger the reorg
219 std::vector<std::shared_ptr<CBlock>> fork;
220 const CBlockIndex* prev_tip = WITH_LOCK(cs_main, return m_node.chainman->ActiveChain().Tip()->pprev);
222
223 for (const auto& block : fork) {
224 BOOST_REQUIRE(m_node.chainman->ProcessNewBlock(block, /*force_processing=*/true, /*min_pow_checked=*/true, nullptr));
225 }
226
227 // The index thread is blocked and not done
228 BOOST_CHECK(!index.GetSummary().synced);
229
230 // Unblock the index thread so it can process the reorg
231 promise.set_value();
232 // Wait for the index to reach the new tip
234
235 StopIndex(index, m_node);
236}
237
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
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition check.h:119
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
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
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)
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()
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.
#define BOOST_CHECK_EQUAL(v1, v2)
Definition object.cpp:17
#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:243
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
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:57
std::unique_ptr< ChainstateManager > chainman
Definition context.h:74
std::unique_ptr< interfaces::Chain > chain
Definition context.h:78
#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:80
void StopIndex(BaseIndex &index, node::NodeContext &node)
Drain validation callbacks before stopping an index, matching Shutdown() in init.cpp.
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
Functions for validating blocks and updating the block tree.
FakeNodeClock clock