Bitcoin Core 30.99.0
P2P Digital Currency
blockmanager_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2022-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 <chain.h>
6#include <chainparams.h>
7#include <clientversion.h>
8#include <node/blockstorage.h>
9#include <node/context.h>
11#include <script/solver.h>
12#include <primitives/block.h>
13#include <util/chaintype.h>
14#include <validation.h>
15
16#include <boost/test/unit_test.hpp>
17#include <test/util/logging.h>
19
25
26// use BasicTestingSetup here for the data directory configuration, setup, and cleanup
28
29BOOST_AUTO_TEST_CASE(blockmanager_find_block_pos)
30{
31 const auto params {CreateChainParams(ArgsManager{}, ChainType::MAIN)};
33 const BlockManager::Options blockman_opts{
34 .chainparams = *params,
35 .blocks_dir = m_args.GetBlocksDirPath(),
36 .notifications = notifications,
37 .block_tree_db_params = DBParams{
38 .path = m_args.GetDataDirNet() / "blocks" / "index",
39 .cache_bytes = 0,
40 },
41 };
42 BlockManager blockman{*Assert(m_node.shutdown_signal), blockman_opts};
43 // simulate adding a genesis block normally
44 BOOST_CHECK_EQUAL(blockman.WriteBlock(params->GenesisBlock(), 0).nPos, STORAGE_HEADER_BYTES);
45 // simulate what happens during reindex
46 // simulate a well-formed genesis block being found at offset 8 in the blk00000.dat file
47 // the block is found at offset 8 because there is an 8 byte serialization header
48 // consisting of 4 magic bytes + 4 length bytes before each block in a well-formed blk file.
50 blockman.UpdateBlockInfo(params->GenesisBlock(), 0, pos);
51 // now simulate what happens after reindex for the first new block processed
52 // the actual block contents don't matter, just that it's a block.
53 // verify that the write position is at offset 0x12d.
54 // this is a check to make sure that https://github.com/bitcoin/bitcoin/issues/21379 does not recur
55 // 8 bytes (for serialization header) + 285 (for serialized genesis block) = 293
56 // add another 8 bytes for the second block's serialization header and we get 293 + 8 = 301
57 FlatFilePos actual{blockman.WriteBlock(params->GenesisBlock(), 1)};
59}
60
61BOOST_FIXTURE_TEST_CASE(blockmanager_scan_unlink_already_pruned_files, TestChain100Setup)
62{
63 // Cap last block file size, and mine new block in a new block file.
64 auto& chainman{*Assert(m_node.chainman)};
65 auto& blockman{chainman.m_blockman};
66 const CBlockIndex* old_tip{WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip())};
67 WITH_LOCK(chainman.GetMutex(), blockman.GetBlockFileInfo(old_tip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);
68 CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
69
70 // Prune the older block file, but don't unlink it
71 int file_number;
72 {
73 LOCK(chainman.GetMutex());
74 file_number = old_tip->GetBlockPos().nFile;
75 blockman.PruneOneBlockFile(file_number);
76 }
77
78 const FlatFilePos pos(file_number, 0);
79
80 // Check that the file is not unlinked after ScanAndUnlinkAlreadyPrunedFiles
81 // if m_have_pruned is not yet set
82 WITH_LOCK(chainman.GetMutex(), blockman.ScanAndUnlinkAlreadyPrunedFiles());
83 BOOST_CHECK(!blockman.OpenBlockFile(pos, true).IsNull());
84
85 // Check that the file is unlinked after ScanAndUnlinkAlreadyPrunedFiles
86 // once m_have_pruned is set
87 blockman.m_have_pruned = true;
88 WITH_LOCK(chainman.GetMutex(), blockman.ScanAndUnlinkAlreadyPrunedFiles());
89 BOOST_CHECK(blockman.OpenBlockFile(pos, true).IsNull());
90
91 // Check that calling with already pruned files doesn't cause an error
92 WITH_LOCK(chainman.GetMutex(), blockman.ScanAndUnlinkAlreadyPrunedFiles());
93
94 // Check that the new tip file has not been removed
95 const CBlockIndex* new_tip{WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip())};
96 BOOST_CHECK_NE(old_tip, new_tip);
97 const int new_file_number{WITH_LOCK(chainman.GetMutex(), return new_tip->GetBlockPos().nFile)};
98 const FlatFilePos new_pos(new_file_number, 0);
99 BOOST_CHECK(!blockman.OpenBlockFile(new_pos, true).IsNull());
100}
101
102BOOST_FIXTURE_TEST_CASE(blockmanager_block_data_availability, TestChain100Setup)
103{
104 // The goal of the function is to return the first not pruned block in the range [upper_block, lower_block].
106 auto& chainman = m_node.chainman;
107 auto& blockman = chainman->m_blockman;
108 const CBlockIndex& tip = *chainman->ActiveTip();
109
110 // Function to prune all blocks from 'last_pruned_block' down to the genesis block
111 const auto& func_prune_blocks = [&](CBlockIndex* last_pruned_block)
112 {
114 CBlockIndex* it = last_pruned_block;
115 while (it != nullptr && it->nStatus & BLOCK_HAVE_DATA) {
116 it->nStatus &= ~BLOCK_HAVE_DATA;
117 it = it->pprev;
118 }
119 };
120
121 // 1) Return genesis block when all blocks are available
122 BOOST_CHECK_EQUAL(&blockman.GetFirstBlock(tip, BLOCK_HAVE_DATA), chainman->ActiveChain()[0]);
123 BOOST_CHECK(blockman.CheckBlockDataAvailability(tip, *chainman->ActiveChain()[0]));
124
125 // 2) Check lower_block when all blocks are available
126 CBlockIndex* lower_block = chainman->ActiveChain()[tip.nHeight / 2];
127 BOOST_CHECK(blockman.CheckBlockDataAvailability(tip, *lower_block));
128
129 // Ensure we don't fail due to the expected absence of undo data in the genesis block
130 CBlockIndex* upper_block = chainman->ActiveChain()[2];
131 CBlockIndex* genesis = chainman->ActiveChain()[0];
132 BOOST_CHECK(blockman.CheckBlockDataAvailability(*upper_block, *genesis, BlockStatus{BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO}));
133 // Ensure we detect absence of undo data in the first block
134 chainman->ActiveChain()[1]->nStatus &= ~BLOCK_HAVE_UNDO;
135 BOOST_CHECK(!blockman.CheckBlockDataAvailability(tip, *genesis, BlockStatus{BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO}));
136
137 // Prune half of the blocks
138 int height_to_prune = tip.nHeight / 2;
139 CBlockIndex* first_available_block = chainman->ActiveChain()[height_to_prune + 1];
140 CBlockIndex* last_pruned_block = first_available_block->pprev;
141 func_prune_blocks(last_pruned_block);
142
143 // 3) The last block not pruned is in-between upper-block and the genesis block
144 BOOST_CHECK_EQUAL(&blockman.GetFirstBlock(tip, BLOCK_HAVE_DATA), first_available_block);
145 BOOST_CHECK(blockman.CheckBlockDataAvailability(tip, *first_available_block));
146 BOOST_CHECK(!blockman.CheckBlockDataAvailability(tip, *last_pruned_block));
147
148 // Simulate that the first available block is missing undo data and
149 // detect this by using a status mask.
150 first_available_block->nStatus &= ~BLOCK_HAVE_UNDO;
151 BOOST_CHECK(!blockman.CheckBlockDataAvailability(tip, *first_available_block, BlockStatus{BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO}));
152 BOOST_CHECK(blockman.CheckBlockDataAvailability(tip, *first_available_block, BlockStatus{BLOCK_HAVE_DATA}));
153}
154
155BOOST_FIXTURE_TEST_CASE(blockmanager_block_data_part, TestChain100Setup)
156{
158 auto& chainman{m_node.chainman};
159 auto& blockman{chainman->m_blockman};
160 const CBlockIndex& tip{*chainman->ActiveTip()};
161 const FlatFilePos tip_block_pos{tip.GetBlockPos()};
162
163 auto block{blockman.ReadRawBlock(tip_block_pos)};
164 BOOST_REQUIRE(block);
165 BOOST_REQUIRE_GE(block->size(), 200);
166
167 const auto expect_part{[&](size_t offset, size_t size) {
168 auto res{blockman.ReadRawBlock(tip_block_pos, std::pair{offset, size})};
169 BOOST_CHECK(res);
170 const auto& part{res.value()};
171 BOOST_CHECK_EQUAL_COLLECTIONS(part.begin(), part.end(), block->begin() + offset, block->begin() + offset + size);
172 }};
173
174 expect_part(0, 20);
175 expect_part(0, block->size() - 1);
176 expect_part(0, block->size() - 10);
177 expect_part(0, block->size());
178 expect_part(1, block->size() - 1);
179 expect_part(10, 20);
180 expect_part(block->size() - 1, 1);
181}
182
183BOOST_FIXTURE_TEST_CASE(blockmanager_block_data_part_error, TestChain100Setup)
184{
186 auto& chainman{m_node.chainman};
187 auto& blockman{chainman->m_blockman};
188 const CBlockIndex& tip{*chainman->ActiveTip()};
189 const FlatFilePos tip_block_pos{tip.GetBlockPos()};
190
191 auto block{blockman.ReadRawBlock(tip_block_pos)};
192 BOOST_REQUIRE(block);
193 BOOST_REQUIRE_GE(block->size(), 200);
194
195 const auto expect_part_error{[&](size_t offset, size_t size) {
196 auto res{blockman.ReadRawBlock(tip_block_pos, std::pair{offset, size})};
197 BOOST_CHECK(!res);
199 }};
200
201 expect_part_error(0, 0);
202 expect_part_error(0, block->size() + 1);
203 expect_part_error(0, std::numeric_limits<size_t>::max());
204 expect_part_error(1, block->size());
205 expect_part_error(2, block->size() - 1);
206 expect_part_error(block->size() - 1, 2);
207 expect_part_error(block->size() - 2, 3);
208 expect_part_error(block->size() + 1, 0);
209 expect_part_error(block->size() + 1, 1);
210 expect_part_error(block->size() + 2, 2);
211 expect_part_error(block->size(), 0);
212 expect_part_error(block->size(), 1);
213 expect_part_error(std::numeric_limits<size_t>::max(), 1);
214 expect_part_error(std::numeric_limits<size_t>::max(), std::numeric_limits<size_t>::max());
215}
216
217BOOST_FIXTURE_TEST_CASE(blockmanager_readblock_hash_mismatch, TestingSetup)
218{
219 CBlockIndex index;
220 {
221 LOCK(cs_main);
222 const auto tip{m_node.chainman->ActiveTip()};
223 index.nStatus = tip->nStatus;
224 index.nDataPos = tip->nDataPos;
225 index.phashBlock = &uint256::ONE; // mismatched block hash
226 }
227
228 ASSERT_DEBUG_LOG("GetHash() doesn't match index");
229 CBlock block;
230 BOOST_CHECK(!m_node.chainman->m_blockman.ReadBlock(block, index));
231}
232
233BOOST_AUTO_TEST_CASE(blockmanager_flush_block_file)
234{
236 node::BlockManager::Options blockman_opts{
237 .chainparams = Params(),
238 .blocks_dir = m_args.GetBlocksDirPath(),
239 .notifications = notifications,
240 .block_tree_db_params = DBParams{
241 .path = m_args.GetDataDirNet() / "blocks" / "index",
242 .cache_bytes = 0,
243 },
244 };
245 BlockManager blockman{*Assert(m_node.shutdown_signal), blockman_opts};
246
247 // Test blocks with no transactions, not even a coinbase
248 CBlock block1;
249 block1.nVersion = 1;
250 CBlock block2;
251 block2.nVersion = 2;
252 CBlock block3;
253 block3.nVersion = 3;
254
255 // They are 80 bytes header + 1 byte 0x00 for vtx length
256 constexpr int TEST_BLOCK_SIZE{81};
257
258 // Blockstore is empty
259 BOOST_CHECK_EQUAL(blockman.CalculateCurrentUsage(), 0);
260
261 // Write the first block to a new location.
262 FlatFilePos pos1{blockman.WriteBlock(block1, /*nHeight=*/1)};
263
264 // Write second block
265 FlatFilePos pos2{blockman.WriteBlock(block2, /*nHeight=*/2)};
266
267 // Two blocks in the file
268 BOOST_CHECK_EQUAL(blockman.CalculateCurrentUsage(), (TEST_BLOCK_SIZE + STORAGE_HEADER_BYTES) * 2);
269
270 // First two blocks are written as expected
271 // Errors are expected because block data is junk, thrown AFTER successful read
272 CBlock read_block;
273 BOOST_CHECK_EQUAL(read_block.nVersion, 0);
274 {
275 ASSERT_DEBUG_LOG("Errors in block header");
276 BOOST_CHECK(!blockman.ReadBlock(read_block, pos1, {}));
277 BOOST_CHECK_EQUAL(read_block.nVersion, 1);
278 }
279 {
280 ASSERT_DEBUG_LOG("Errors in block header");
281 BOOST_CHECK(!blockman.ReadBlock(read_block, pos2, {}));
282 BOOST_CHECK_EQUAL(read_block.nVersion, 2);
283 }
284
285 // During reindex, the flat file block storage will not be written to.
286 // UpdateBlockInfo will, however, update the blockfile metadata.
287 // Verify this behavior by attempting (and failing) to write block 3 data
288 // to block 2 location.
289 CBlockFileInfo* block_data = blockman.GetBlockFileInfo(0);
290 BOOST_CHECK_EQUAL(block_data->nBlocks, 2);
291 blockman.UpdateBlockInfo(block3, /*nHeight=*/3, /*pos=*/pos2);
292 // Metadata is updated...
293 BOOST_CHECK_EQUAL(block_data->nBlocks, 3);
294 // ...but there are still only two blocks in the file
295 BOOST_CHECK_EQUAL(blockman.CalculateCurrentUsage(), (TEST_BLOCK_SIZE + STORAGE_HEADER_BYTES) * 2);
296
297 // Block 2 was not overwritten:
298 BOOST_CHECK(!blockman.ReadBlock(read_block, pos2, {}));
299 BOOST_CHECK_EQUAL(read_block.nVersion, 2);
300}
301
node::NodeContext m_node
Definition: bitcoin-gui.cpp:43
BOOST_AUTO_TEST_CASE(blockmanager_find_block_pos)
BOOST_FIXTURE_TEST_CASE(blockmanager_scan_unlink_already_pruned_files, TestChain100Setup)
BlockStatus
Definition: chain.h:42
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition: chain.h:75
std::unique_ptr< const CChainParams > CreateChainParams(const ArgsManager &args, const ChainType chain)
Creates and returns a std::unique_ptr<CChainParams> of the chosen chain.
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:113
int32_t nVersion
Definition: block.h:30
Definition: block.h:74
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:100
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:106
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:97
uint32_t nBlocks
number of blocks stored in file
Definition: blockstorage.h:59
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:192
static const uint256 ONE
Definition: uint256.h:204
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()
static constexpr uint32_t STORAGE_HEADER_BYTES
Size of header written by WriteBlock before a serialized CBlock (8 bytes)
Definition: blockstorage.h:126
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:123
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:17
#define BOOST_CHECK(expr)
Definition: object.cpp:16
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:180
uint64_t GetSerializeSize(const T &t)
Definition: serialize.h:1095
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: solver.cpp:213
Basic testing setup.
Definition: setup_common.h:64
Application-specific storage settings.
Definition: dbwrapper.h:33
fs::path path
Location in the filesystem where leveldb data will be stored.
Definition: dbwrapper.h:35
Testing fixture that pre-creates a 100-block REGTEST-mode block chain.
Definition: setup_common.h:146
Testing setup that configures a complete environment.
Definition: setup_common.h:121
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
const CChainParams & chainparams
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:72
std::unique_ptr< node::Warnings > warnings
Manages all the node warnings.
Definition: context.h:91
std::function< bool()> shutdown_request
Function to request a shutdown.
Definition: context.h:63
util::SignalInterrupt * shutdown_signal
Interrupt object used to track whether node shutdown was requested.
Definition: context.h:65
std::atomic< int > exit_status
Definition: context.h:89
#define LOCK(cs)
Definition: sync.h:258
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:289
#define ASSERT_DEBUG_LOG(message)
Definition: logging.h:42