Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2022-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#include <chain.h>6#include <chainparams.h>7#include <clientversion.h>8#include <node/blockstorage.h>9#include <node/context.h>10#include <node/kernel_notifications.h>11#include <script/solver.h>12#include <primitives/block.h>13#include <util/chaintype.h>14#include <validation.h>16#include <boost/test/unit_test.hpp>17#include <test/util/common.h>18#include <test/util/logging.h>19#include <test/util/setup_common.h>21using kernel::CBlockFileInfo;22using node::STORAGE_HEADER_BYTES;23using node::BlockManager;24using node::KernelNotifications;25using node::MAX_BLOCKFILE_SIZE;27// use BasicTestingSetup here for the data directory configuration, setup, and cleanup28BOOST_FIXTURE_TEST_SUITE(blockmanager_tests, BasicTestingSetup)30BOOST_AUTO_TEST_CASE(blockmanager_find_block_pos)31{32const auto params {CreateChainParams(ArgsManager{}, ChainType::MAIN)};33KernelNotifications notifications{Assert(m_node.shutdown_request), m_node.exit_status, *Assert(m_node.warnings)};34const BlockManager::Options blockman_opts{35.chainparams = *params,36.blocks_dir = m_args.GetBlocksDirPath(),37.notifications = notifications,38.block_tree_db_params = DBParams{39.path = m_args.GetDataDirNet() / "blocks" / "index",40.cache_bytes = 0,41},42};43BlockManager blockman{*Assert(m_node.shutdown_signal), blockman_opts};44// simulate adding a genesis block normally45LOCK(::cs_main);46BOOST_CHECK_EQUAL(blockman.WriteBlock(params->GenesisBlock(), 0).nPos, STORAGE_HEADER_BYTES);47// simulate what happens during reindex48// simulate a well-formed genesis block being found at offset 8 in the blk00000.dat file49// the block is found at offset 8 because there is an 8 byte serialization header50// consisting of 4 magic bytes + 4 length bytes before each block in a well-formed blk file.51const FlatFilePos pos{0, STORAGE_HEADER_BYTES};52blockman.UpdateBlockInfo(params->GenesisBlock(), 0, pos);53// now simulate what happens after reindex for the first new block processed54// the actual block contents don't matter, just that it's a block.55// verify that the write position is at offset 0x12d.56// this is a check to make sure that https://github.com/bitcoin/bitcoin/issues/21379 does not recur57// 8 bytes (for serialization header) + 285 (for serialized genesis block) = 29358// add another 8 bytes for the second block's serialization header and we get 293 + 8 = 30159FlatFilePos actual{blockman.WriteBlock(params->GenesisBlock(), 1)};60BOOST_CHECK_EQUAL(actual.nPos, STORAGE_HEADER_BYTES + ::GetSerializeSize(TX_WITH_WITNESS(params->GenesisBlock())) + STORAGE_HEADER_BYTES);61}63BOOST_FIXTURE_TEST_CASE(blockmanager_scan_unlink_already_pruned_files, TestChain100Setup)64{65// Cap last block file size, and mine new block in a new block file.66auto& chainman{*Assert(m_node.chainman)};67auto& blockman{chainman.m_blockman};68const CBlockIndex* old_tip{WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip())};69WITH_LOCK(chainman.GetMutex(), blockman.GetBlockFileInfo(old_tip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE);70CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));72// Prune the older block file, but don't unlink it73int file_number;74{75LOCK(chainman.GetMutex());76file_number = old_tip->GetBlockPos().nFile;77blockman.PruneOneBlockFile(file_number);78}80const FlatFilePos pos(file_number, 0);82// Check that the file is not unlinked after ScanAndUnlinkAlreadyPrunedFiles83// if m_have_pruned is not yet set84WITH_LOCK(chainman.GetMutex(), blockman.ScanAndUnlinkAlreadyPrunedFiles());85BOOST_CHECK(!blockman.OpenBlockFile(pos, true).IsNull());87// Check that the file is unlinked after ScanAndUnlinkAlreadyPrunedFiles88// once m_have_pruned is set89blockman.m_have_pruned = true;90WITH_LOCK(chainman.GetMutex(), blockman.ScanAndUnlinkAlreadyPrunedFiles());91BOOST_CHECK(blockman.OpenBlockFile(pos, true).IsNull());93// Check that calling with already pruned files doesn't cause an error94WITH_LOCK(chainman.GetMutex(), blockman.ScanAndUnlinkAlreadyPrunedFiles());96// Check that the new tip file has not been removed97const CBlockIndex* new_tip{WITH_LOCK(chainman.GetMutex(), return chainman.ActiveChain().Tip())};98BOOST_CHECK_NE(old_tip, new_tip);99const int new_file_number{WITH_LOCK(chainman.GetMutex(), return new_tip->GetBlockPos().nFile)};100const FlatFilePos new_pos(new_file_number, 0);101BOOST_CHECK(!blockman.OpenBlockFile(new_pos, true).IsNull());102}104BOOST_FIXTURE_TEST_CASE(blockmanager_block_data_availability, TestChain100Setup)105{106// The goal of the function is to return the first not pruned block in the range [upper_block, lower_block].107LOCK(::cs_main);108auto& chainman = m_node.chainman;109auto& blockman = chainman->m_blockman;110const CBlockIndex& tip = *chainman->ActiveTip();112// Function to prune all blocks from 'last_pruned_block' down to the genesis block113const auto& func_prune_blocks = [&](CBlockIndex* last_pruned_block)114{115LOCK(::cs_main);116CBlockIndex* it = last_pruned_block;117while (it != nullptr && it->nStatus & BLOCK_HAVE_DATA) {118it->nStatus &= ~BLOCK_HAVE_DATA;119it = it->pprev;120}121};123// 1) Return genesis block when all blocks are available124BOOST_CHECK_EQUAL(&blockman.GetFirstBlock(tip, BLOCK_HAVE_DATA), chainman->ActiveChain()[0]);125BOOST_CHECK(blockman.CheckBlockDataAvailability(tip, *chainman->ActiveChain()[0]));127// 2) Check lower_block when all blocks are available128CBlockIndex* lower_block = chainman->ActiveChain()[tip.nHeight / 2];129BOOST_CHECK(blockman.CheckBlockDataAvailability(tip, *lower_block));131// Ensure we don't fail due to the expected absence of undo data in the genesis block132CBlockIndex* upper_block = chainman->ActiveChain()[2];133CBlockIndex* genesis = chainman->ActiveChain()[0];134BOOST_CHECK(blockman.CheckBlockDataAvailability(*upper_block, *genesis, BlockStatus{BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO}));135// Ensure we detect absence of undo data in the first block136chainman->ActiveChain()[1]->nStatus &= ~BLOCK_HAVE_UNDO;137BOOST_CHECK(!blockman.CheckBlockDataAvailability(tip, *genesis, BlockStatus{BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO}));139// Prune half of the blocks140int height_to_prune = tip.nHeight / 2;141CBlockIndex* first_available_block = chainman->ActiveChain()[height_to_prune + 1];142CBlockIndex* last_pruned_block = first_available_block->pprev;143func_prune_blocks(last_pruned_block);145// 3) The last block not pruned is in-between upper-block and the genesis block146BOOST_CHECK_EQUAL(&blockman.GetFirstBlock(tip, BLOCK_HAVE_DATA), first_available_block);147BOOST_CHECK(blockman.CheckBlockDataAvailability(tip, *first_available_block));148BOOST_CHECK(!blockman.CheckBlockDataAvailability(tip, *last_pruned_block));150// Simulate that the first available block is missing undo data and151// detect this by using a status mask.152first_available_block->nStatus &= ~BLOCK_HAVE_UNDO;153BOOST_CHECK(!blockman.CheckBlockDataAvailability(tip, *first_available_block, BlockStatus{BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO}));154BOOST_CHECK(blockman.CheckBlockDataAvailability(tip, *first_available_block, BlockStatus{BLOCK_HAVE_DATA}));155}157BOOST_FIXTURE_TEST_CASE(blockmanager_block_data_part, TestChain100Setup)158{159LOCK(::cs_main);160auto& chainman{m_node.chainman};161auto& blockman{chainman->m_blockman};162const CBlockIndex& tip{*chainman->ActiveTip()};163const FlatFilePos tip_block_pos{tip.GetBlockPos()};165auto block{blockman.ReadRawBlock(tip_block_pos)};166BOOST_REQUIRE(block);167BOOST_REQUIRE_GE(block->size(), 200);169const auto expect_part{[&](size_t offset, size_t size) {170auto res{blockman.ReadRawBlock(tip_block_pos, std::pair{offset, size})};171BOOST_CHECK(res);172const auto& part{res.value()};173BOOST_CHECK_EQUAL_COLLECTIONS(part.begin(), part.end(), block->begin() + offset, block->begin() + offset + size);174}};176expect_part(0, 20);177expect_part(0, block->size() - 1);178expect_part(0, block->size() - 10);179expect_part(0, block->size());180expect_part(1, block->size() - 1);181expect_part(10, 20);182expect_part(block->size() - 1, 1);183}185BOOST_FIXTURE_TEST_CASE(blockmanager_block_data_part_error, TestChain100Setup)186{187LOCK(::cs_main);188auto& chainman{m_node.chainman};189auto& blockman{chainman->m_blockman};190const CBlockIndex& tip{*chainman->ActiveTip()};191const FlatFilePos tip_block_pos{tip.GetBlockPos()};193auto block{blockman.ReadRawBlock(tip_block_pos)};194BOOST_REQUIRE(block);195BOOST_REQUIRE_GE(block->size(), 200);197const auto expect_part_error{[&](size_t offset, size_t size) {198auto res{blockman.ReadRawBlock(tip_block_pos, std::pair{offset, size})};199BOOST_CHECK(!res);200BOOST_CHECK_EQUAL(res.error(), node::ReadRawError::BadPartRange);201}};203expect_part_error(0, 0);204expect_part_error(0, block->size() + 1);205expect_part_error(0, std::numeric_limits<size_t>::max());206expect_part_error(1, block->size());207expect_part_error(2, block->size() - 1);208expect_part_error(block->size() - 1, 2);209expect_part_error(block->size() - 2, 3);210expect_part_error(block->size() + 1, 0);211expect_part_error(block->size() + 1, 1);212expect_part_error(block->size() + 2, 2);213expect_part_error(block->size(), 0);214expect_part_error(block->size(), 1);215expect_part_error(std::numeric_limits<size_t>::max(), 1);216expect_part_error(std::numeric_limits<size_t>::max(), std::numeric_limits<size_t>::max());217}219BOOST_FIXTURE_TEST_CASE(blockmanager_readblock_hash_mismatch, TestingSetup)220{221CBlockIndex index;222{223LOCK(cs_main);224const auto tip{m_node.chainman->ActiveTip()};225index.nStatus = tip->nStatus;226index.nDataPos = tip->nDataPos;227index.phashBlock = &uint256::ONE; // mismatched block hash228}230ASSERT_DEBUG_LOG("GetHash() doesn't match index");231CBlock block;232BOOST_CHECK(!m_node.chainman->m_blockman.ReadBlock(block, index));233}235BOOST_AUTO_TEST_CASE(blockmanager_flush_block_file)236{237KernelNotifications notifications{Assert(m_node.shutdown_request), m_node.exit_status, *Assert(m_node.warnings)};238node::BlockManager::Options blockman_opts{239.chainparams = Params(),240.blocks_dir = m_args.GetBlocksDirPath(),241.notifications = notifications,242.block_tree_db_params = DBParams{243.path = m_args.GetDataDirNet() / "blocks" / "index",244.cache_bytes = 0,245},246};247BlockManager blockman{*Assert(m_node.shutdown_signal), blockman_opts};249// Test blocks with no transactions, not even a coinbase250CBlock block1;
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.