Line data Source code
1 : // Copyright (c) 2022 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 <chainparams.h> 6 : #include <node/blockstorage.h> 7 : #include <node/context.h> 8 : #include <validation.h> 9 : 10 : #include <boost/test/unit_test.hpp> 11 : #include <test/util/setup_common.h> 12 : 13 : using node::BlockManager; 14 : using node::BLOCK_SERIALIZATION_HEADER_SIZE; 15 : 16 : // use BasicTestingSetup here for the data directory configuration, setup, and cleanup 17 146 : BOOST_FIXTURE_TEST_SUITE(blockmanager_tests, BasicTestingSetup) 18 : 19 149 : BOOST_AUTO_TEST_CASE(blockmanager_find_block_pos) 20 : { 21 1 : const auto params {CreateChainParams(ArgsManager{}, CBaseChainParams::MAIN)}; 22 2 : node::BlockManager::Options blockman_opts{ 23 1 : .chainparams = *params, 24 : }; 25 1 : BlockManager blockman{blockman_opts}; 26 1 : CChain chain {}; 27 : // simulate adding a genesis block normally 28 1 : BOOST_CHECK_EQUAL(blockman.SaveBlockToDisk(params->GenesisBlock(), 0, chain, nullptr).nPos, BLOCK_SERIALIZATION_HEADER_SIZE); 29 : // simulate what happens during reindex 30 : // simulate a well-formed genesis block being found at offset 8 in the blk00000.dat file 31 : // the block is found at offset 8 because there is an 8 byte serialization header 32 : // consisting of 4 magic bytes + 4 length bytes before each block in a well-formed blk file. 33 1 : FlatFilePos pos{0, BLOCK_SERIALIZATION_HEADER_SIZE}; 34 1 : BOOST_CHECK_EQUAL(blockman.SaveBlockToDisk(params->GenesisBlock(), 0, chain, &pos).nPos, BLOCK_SERIALIZATION_HEADER_SIZE); 35 : // now simulate what happens after reindex for the first new block processed 36 : // the actual block contents don't matter, just that it's a block. 37 : // verify that the write position is at offset 0x12d. 38 : // this is a check to make sure that https://github.com/bitcoin/bitcoin/issues/21379 does not recur 39 : // 8 bytes (for serialization header) + 285 (for serialized genesis block) = 293 40 : // add another 8 bytes for the second block's serialization header and we get 293 + 8 = 301 41 1 : FlatFilePos actual{blockman.SaveBlockToDisk(params->GenesisBlock(), 1, chain, nullptr)}; 42 1 : BOOST_CHECK_EQUAL(actual.nPos, BLOCK_SERIALIZATION_HEADER_SIZE + ::GetSerializeSize(params->GenesisBlock(), CLIENT_VERSION) + BLOCK_SERIALIZATION_HEADER_SIZE); 43 1 : } 44 : 45 146 : BOOST_AUTO_TEST_SUITE_END()