Skip to content

Commit 541976b

Browse files
committed
Merge bitcoin/bitcoin#27850: test: Add unit & functional test coverage for blockstore
de8f912 test: cover read-only blockstore (Matthew Zipkin) 5c2185b ci: enable chattr +i capability inside containers (Matthew Zipkin) e573f24 unit test: add coverage for BlockManager (Matthew Zipkin) Pull request description: This PR adds unit and functional tests to cover the behavior described in #2039. In particular, that bitcoind will crash on startup if a reindex is requested but the `blk` files are read-only. Eventually this behavior can be updated with bitcoin/bitcoin#27039. This PR just commits the test coverage from #27039 as suggested in bitcoin/bitcoin#27039 (comment) ACKs for top commit: jonatack: ACK de8f912 modulo suggestions in bitcoin/bitcoin#27850 (comment), tested on macOS, but not on Linux for the Linux-related change in the last push achow101: ACK de8f912 MarcoFalke: lgtm ACK de8f912 📶 Tree-SHA512: b9bd684035dcea11c901b649fc39f397a2155a9a8459f3348e67947e387e45312fddeccb52981aef486f8a31deebb5356a7901c1bb94b78f82c24192a369af73
2 parents f5c5dda + de8f912 commit 541976b

File tree

6 files changed

+141
-3
lines changed

6 files changed

+141
-3
lines changed

ci/test/00_setup_env.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ export BASE_BUILD_DIR=${BASE_BUILD_DIR:-$BASE_SCRATCH_DIR/build}
6767
# The folder for previous release binaries.
6868
# This folder exists only on the ci guest, and on the ci host as a volume.
6969
export PREVIOUS_RELEASES_DIR=${PREVIOUS_RELEASES_DIR:-$BASE_ROOT_DIR/prev_releases}
70-
export CI_BASE_PACKAGES=${CI_BASE_PACKAGES:-build-essential libtool autotools-dev automake pkg-config bsdmainutils curl ca-certificates ccache python3 rsync git procps bison}
70+
export CI_BASE_PACKAGES=${CI_BASE_PACKAGES:-build-essential libtool autotools-dev automake pkg-config bsdmainutils curl ca-certificates ccache python3 rsync git procps bison e2fsprogs}
7171
export GOAL=${GOAL:-install}
7272
export DIR_QA_ASSETS=${DIR_QA_ASSETS:-${BASE_SCRATCH_DIR}/qa-assets}
7373
export CI_RETRY_EXE=${CI_RETRY_EXE:-"retry --"}

ci/test/00_setup_env_i686_centos.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ export LC_ALL=C.UTF-8
99
export HOST=i686-pc-linux-gnu
1010
export CONTAINER_NAME=ci_i686_centos
1111
export CI_IMAGE_NAME_TAG="quay.io/centos/amd64:stream9"
12-
export CI_BASE_PACKAGES="gcc-c++ glibc-devel.x86_64 libstdc++-devel.x86_64 glibc-devel.i686 libstdc++-devel.i686 ccache libtool make git python3 python3-pip which patch lbzip2 xz procps-ng dash rsync coreutils bison util-linux"
12+
export CI_BASE_PACKAGES="gcc-c++ glibc-devel.x86_64 libstdc++-devel.x86_64 glibc-devel.i686 libstdc++-devel.i686 ccache libtool make git python3 python3-pip which patch lbzip2 xz procps-ng dash rsync coreutils bison util-linux e2fsprogs"
1313
export PIP_PACKAGES="pyzmq"
1414
export GOAL="install"
1515
export NO_WERROR=1 # Suppress error: #warning _FORTIFY_SOURCE > 2 is treated like 2 on this platform [-Werror=cpp]

ci/test/04_install.sh

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ if [ -z "$DANGER_RUN_CI_ON_HOST" ]; then
3131
fi
3232

3333
# shellcheck disable=SC2086
34-
CI_CONTAINER_ID=$(docker run $CI_CONTAINER_CAP --rm --interactive --detach --tty \
34+
35+
36+
CI_CONTAINER_ID=$(docker run --cap-add LINUX_IMMUTABLE $CI_CONTAINER_CAP --rm --interactive --detach --tty \
3537
--mount "type=bind,src=$BASE_READ_ONLY_DIR,dst=$BASE_READ_ONLY_DIR,readonly" \
3638
--mount "type=volume,src=${CONTAINER_NAME}_ccache,dst=$CCACHE_DIR" \
3739
--mount "type=volume,src=${CONTAINER_NAME}_depends,dst=$DEPENDS_DIR" \

src/test/blockmanager_tests.cpp

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,12 @@
88
#include <node/context.h>
99
#include <node/kernel_notifications.h>
1010
#include <script/solver.h>
11+
#include <primitives/block.h>
1112
#include <util/chaintype.h>
1213
#include <validation.h>
1314

1415
#include <boost/test/unit_test.hpp>
16+
#include <test/util/logging.h>
1517
#include <test/util/setup_common.h>
1618

1719
using node::BLOCK_SERIALIZATION_HEADER_SIZE;
@@ -130,4 +132,73 @@ BOOST_FIXTURE_TEST_CASE(blockmanager_block_data_availability, TestChain100Setup)
130132
BOOST_CHECK(!blockman.CheckBlockDataAvailability(tip, *last_pruned_block));
131133
}
132134

135+
BOOST_AUTO_TEST_CASE(blockmanager_flush_block_file)
136+
{
137+
KernelNotifications notifications{m_node.exit_status};
138+
node::BlockManager::Options blockman_opts{
139+
.chainparams = Params(),
140+
.blocks_dir = m_args.GetBlocksDirPath(),
141+
.notifications = notifications,
142+
};
143+
BlockManager blockman{m_node.kernel->interrupt, blockman_opts};
144+
145+
// Test blocks with no transactions, not even a coinbase
146+
CBlock block1;
147+
block1.nVersion = 1;
148+
CBlock block2;
149+
block2.nVersion = 2;
150+
CBlock block3;
151+
block3.nVersion = 3;
152+
153+
// They are 80 bytes header + 1 byte 0x00 for vtx length
154+
constexpr int TEST_BLOCK_SIZE{81};
155+
156+
// Blockstore is empty
157+
BOOST_CHECK_EQUAL(blockman.CalculateCurrentUsage(), 0);
158+
159+
// Write the first block; dbp=nullptr means this block doesn't already have a disk
160+
// location, so allocate a free location and write it there.
161+
FlatFilePos pos1{blockman.SaveBlockToDisk(block1, /*nHeight=*/1, /*dbp=*/nullptr)};
162+
163+
// Write second block
164+
FlatFilePos pos2{blockman.SaveBlockToDisk(block2, /*nHeight=*/2, /*dbp=*/nullptr)};
165+
166+
// Two blocks in the file
167+
BOOST_CHECK_EQUAL(blockman.CalculateCurrentUsage(), (TEST_BLOCK_SIZE + BLOCK_SERIALIZATION_HEADER_SIZE) * 2);
168+
169+
// First two blocks are written as expected
170+
// Errors are expected because block data is junk, thrown AFTER successful read
171+
CBlock read_block;
172+
BOOST_CHECK_EQUAL(read_block.nVersion, 0);
173+
{
174+
ASSERT_DEBUG_LOG("ReadBlockFromDisk: Errors in block header");
175+
BOOST_CHECK(!blockman.ReadBlockFromDisk(read_block, pos1));
176+
BOOST_CHECK_EQUAL(read_block.nVersion, 1);
177+
}
178+
{
179+
ASSERT_DEBUG_LOG("ReadBlockFromDisk: Errors in block header");
180+
BOOST_CHECK(!blockman.ReadBlockFromDisk(read_block, pos2));
181+
BOOST_CHECK_EQUAL(read_block.nVersion, 2);
182+
}
183+
184+
// When FlatFilePos* dbp is given, SaveBlockToDisk() will not write or
185+
// overwrite anything to the flat file block storage. It will, however,
186+
// update the blockfile metadata. This is to facilitate reindexing
187+
// when the user has the blocks on disk but the metadata is being rebuilt.
188+
// Verify this behavior by attempting (and failing) to write block 3 data
189+
// to block 2 location.
190+
CBlockFileInfo* block_data = blockman.GetBlockFileInfo(0);
191+
BOOST_CHECK_EQUAL(block_data->nBlocks, 2);
192+
BOOST_CHECK(blockman.SaveBlockToDisk(block3, /*nHeight=*/3, /*dbp=*/&pos2) == pos2);
193+
// Metadata is updated...
194+
BOOST_CHECK_EQUAL(block_data->nBlocks, 3);
195+
// ...but there are still only two blocks in the file
196+
BOOST_CHECK_EQUAL(blockman.CalculateCurrentUsage(), (TEST_BLOCK_SIZE + BLOCK_SERIALIZATION_HEADER_SIZE) * 2);
197+
198+
// Block 2 was not overwritten:
199+
// SaveBlockToDisk() did not call WriteBlockToDisk() because `FlatFilePos* dbp` was non-null
200+
blockman.ReadBlockFromDisk(read_block, pos2);
201+
BOOST_CHECK_EQUAL(read_block.nVersion, 2);
202+
}
203+
133204
BOOST_AUTO_TEST_SUITE_END()
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2023-present The Bitcoin Core developers
3+
# Distributed under the MIT software license, see the accompanying
4+
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5+
"""Test running bitcoind with -reindex from a read-only blockstore
6+
- Start a node, generate blocks, then restart with -reindex after setting blk files to read-only
7+
"""
8+
9+
import platform
10+
import stat
11+
import subprocess
12+
from test_framework.test_framework import BitcoinTestFramework
13+
14+
15+
class BlockstoreReindexTest(BitcoinTestFramework):
16+
def set_test_params(self):
17+
self.setup_clean_chain = True
18+
self.num_nodes = 1
19+
self.extra_args = [["-fastprune"]]
20+
21+
def reindex_readonly(self):
22+
self.log.debug("Generate block big enough to start second block file")
23+
fastprune_blockfile_size = 0x10000
24+
opreturn = "6a"
25+
nulldata = fastprune_blockfile_size * "ff"
26+
self.generateblock(self.nodes[0], output=f"raw({opreturn}{nulldata})", transactions=[])
27+
self.stop_node(0)
28+
29+
assert (self.nodes[0].chain_path / "blocks" / "blk00000.dat").exists()
30+
assert (self.nodes[0].chain_path / "blocks" / "blk00001.dat").exists()
31+
32+
self.log.debug("Make the first block file read-only")
33+
filename = self.nodes[0].chain_path / "blocks" / "blk00000.dat"
34+
filename.chmod(stat.S_IREAD)
35+
36+
used_chattr = False
37+
if platform.system() == "Linux":
38+
try:
39+
subprocess.run(['chattr', '+i', filename], capture_output=True, check=True)
40+
used_chattr = True
41+
self.log.info("Made file immutable with chattr")
42+
except subprocess.CalledProcessError as e:
43+
self.log.warning(str(e))
44+
if e.stdout:
45+
self.log.warning(f"stdout: {e.stdout}")
46+
if e.stderr:
47+
self.log.warning(f"stderr: {e.stderr}")
48+
49+
self.log.debug("Attempt to restart and reindex the node with the unwritable block file")
50+
with self.nodes[0].assert_debug_log(expected_msgs=['FlushStateToDisk', 'failed to open file'], unexpected_msgs=[]):
51+
self.nodes[0].assert_start_raises_init_error(extra_args=['-reindex', '-fastprune'],
52+
expected_msg="Error: A fatal internal error occurred, see debug.log for details")
53+
54+
if used_chattr:
55+
subprocess.check_call(['chattr', '-i', filename])
56+
57+
filename.chmod(0o777)
58+
59+
def run_test(self):
60+
self.reindex_readonly()
61+
62+
63+
if __name__ == '__main__':
64+
BlockstoreReindexTest().main()

test/functional/test_runner.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@
162162
'wallet_abandonconflict.py --legacy-wallet',
163163
'wallet_abandonconflict.py --descriptors',
164164
'feature_reindex.py',
165+
'feature_reindex_readonly.py',
165166
'wallet_labels.py --legacy-wallet',
166167
'wallet_labels.py --descriptors',
167168
'p2p_compactblocks.py',

0 commit comments

Comments
 (0)