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#!/usr/bin/env python32# Copyright (c) 2022-present The Bitcoin Core developers3# Distributed under the MIT software license, see the accompanying4# file COPYING or http://www.opensource.org/licenses/mit-license.php.5"""Test bitcoin-chainstate tool functionality7Test basic block processing via bitcoin-chainstate tool, including detecting8duplicates and malformed input.10Test that bitcoin-chainstate can load a datadir initialized with an assumeutxo11snapshot and extend the snapshot chain with new blocks.12"""14import subprocess16from test_framework.test_framework import BitcoinTestFramework17from test_framework.util import assert_equal18from test_framework.wallet import MiniWallet20START_HEIGHT = 19921# Hardcoded in regtest chainparams22SNAPSHOT_BASE_BLOCK_HEIGHT = 29923SNAPSHOT_BASE_BLOCK_HASH = "0c552ced4721c249a389eb9b08cb8da261cd46f0e7b5f9d064d48f3113406853"26class BitcoinChainstateTest(BitcoinTestFramework):27def skip_test_if_missing_module(self):28self.skip_if_no_bitcoin_chainstate()30def set_test_params(self):31"""Use the pregenerated, deterministic chain up to height 199."""32self.num_nodes = 234def setup_network(self):35"""Start with the nodes disconnected so that one can generate a snapshot36including blocks the other hasn't yet seen."""37self.add_nodes(2)38self.start_nodes()40def generate_snapshot_chain(self):41self.log.info(f"Generate deterministic chain up to block {SNAPSHOT_BASE_BLOCK_HEIGHT} for node0 while node1 disconnected")42n0 = self.nodes[0]43assert_equal(n0.getblockcount(), START_HEIGHT)44n0.setmocktime(n0.getblockheader(n0.getbestblockhash())['time'])45mini_wallet = MiniWallet(n0)46for i in range(SNAPSHOT_BASE_BLOCK_HEIGHT - n0.getblockchaininfo()["blocks"]):47if i % 3 == 0:48mini_wallet.send_self_transfer(from_node=n0)49self.generate(n0, nblocks=1, sync_fun=self.no_op)50assert_equal(n0.getblockcount(), SNAPSHOT_BASE_BLOCK_HEIGHT)51assert_equal(n0.getbestblockhash(), SNAPSHOT_BASE_BLOCK_HASH)52return n0.dumptxoutset('utxos.dat', "latest")54def add_block(self, datadir, input, *, expected_stderr=None, expected_stdout=None):55proc = subprocess.Popen(56self.get_binaries().chainstate_argv() + ["-regtest", datadir],57stdin=subprocess.PIPE,58stdout=subprocess.PIPE,59stderr=subprocess.PIPE,60text=True,61)62stdout, stderr = proc.communicate(input=input + "\n", timeout=5 * self.options.timeout_factor)63self.log.debug("STDOUT: {0}".format(stdout.strip("\n")))64self.log.info("STDERR: {0}".format(stderr.strip("\n")))66if expected_stderr is not None and expected_stderr not in stderr:67raise AssertionError(f"Expected stderr output '{expected_stderr}' does not partially match stderr:\n{stderr}")68if expected_stdout is not None and expected_stdout not in stdout:69raise AssertionError(f"Expected stdout output '{expected_stdout}' does not partially match stdout:\n{stdout}")71def basic_test(self):72n0 = self.nodes[0]73n1 = self.nodes[1]74datadir = n1.chain_path75n1.stop_node()76block = n0.getblock(n0.getblockhash(START_HEIGHT+1), 0)77self.log.info(f"Test bitcoin-chainstate {self.get_binaries().chainstate_argv()} with datadir: {datadir}")78self.add_block(datadir, block, expected_stderr="Block has not yet been rejected")79self.add_block(datadir, block, expected_stderr="duplicate")80self.add_block(datadir, "00", expected_stderr="Block decode failed")81self.add_block(datadir, "", expected_stderr="Empty line found")83def assumeutxo_test(self, dump_output_path):84n0 = self.nodes[0]85n1 = self.nodes[1]86self.start_node(1)87self.log.info("Submit headers for new blocks to node1, then load the snapshot so it activates")88for height in range(START_HEIGHT+2, SNAPSHOT_BASE_BLOCK_HEIGHT+1):89block = n0.getblock(n0.getblockhash(height), 0)90n1.submitheader(block)91assert_equal(n1.getblockcount(), START_HEIGHT+1)92loaded = n1.loadtxoutset(dump_output_path)93assert_equal(loaded['base_height'], SNAPSHOT_BASE_BLOCK_HEIGHT)94datadir = n1.chain_path95n1.stop_node()96self.log.info(f"Test bitcoin-chainstate {self.get_binaries().chainstate_argv()} with an assumeutxo datadir: {datadir}")97new_tip_hash = self.generate(n0, nblocks=1, sync_fun=self.no_op)[0]98self.add_block(datadir, n0.getblock(new_tip_hash, 0), expected_stdout="Block tip changed")100def run_test(self):101dump_output = self.generate_snapshot_chain()102self.basic_test()103self.assumeutxo_test(dump_output['path'])105if __name__ == "__main__":106BitcoinChainstateTest(__file__).main()
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.