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) 2019-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 that we reject low difficulty headers to prevent our block tree from filling up with useless bloat"""7from test_framework.test_framework import BitcoinTestFramework9from test_framework.p2p import (10P2PInterface,11)13from test_framework.messages import (14msg_headers,15)17from test_framework.blocktools import (18MAX_FUTURE_BLOCK_TIME,19NORMAL_GBT_REQUEST_PARAMS,20create_block,21)23from test_framework.util import assert_equal25import re26import time28NODE1_BLOCKS_REQUIRED = 1529NODE2_BLOCKS_REQUIRED = 204732class RejectLowDifficultyHeadersTest(BitcoinTestFramework):33def set_test_params(self):34self.rpc_timeout *= 4 # To avoid timeout when generating BLOCKS_TO_MINE35self.setup_clean_chain = True36self.num_nodes = 437# Node0 has no required chainwork; node1 requires 15 blocks on top of the genesis block; node2 requires 204738self.extra_args = [["-minimumchainwork=0x0", "-checkblockindex=0"], ["-minimumchainwork=0x1f", "-checkblockindex=0"], ["-minimumchainwork=0x1000", "-checkblockindex=0"], ["-minimumchainwork=0x1000", "-checkblockindex=0", "[email protected]"]]40def setup_network(self):41self.setup_nodes()42self.reconnect_all()43self.sync_all()45def disconnect_all(self):46self.disconnect_nodes(0, 1)47self.disconnect_nodes(0, 2)48self.disconnect_nodes(0, 3)50def reconnect_all(self):51self.connect_nodes(0, 1)52self.connect_nodes(0, 2)53self.connect_nodes(0, 3)55def mocktime_all(self, time):56for n in self.nodes:57n.setmocktime(time)59def test_chains_sync_when_long_enough(self):60self.log.info("Generate blocks on the node with no required chainwork, and verify nodes 1 and 2 have no new headers in their headers tree")61with (62self.nodes[1].assert_debug_log(expected_msgs=["[net] Ignoring low-work chain (height=14)"], timeout=2),63self.nodes[2].assert_debug_log(expected_msgs=["[net] Ignoring low-work chain (height=14)"], timeout=2),64self.nodes[3].assert_debug_log(expected_msgs=["Synchronizing blockheaders, height: 14"], timeout=2),65):66self.generate(self.nodes[0], NODE1_BLOCKS_REQUIRED-1, sync_fun=self.no_op)68# Node3 should always allow headers due to noban permissions69self.log.info("Check that node3 will sync headers (due to noban permissions)")71def check_node3_chaintips(num_tips, tip_hash, height):72node3_chaintips = self.nodes[3].getchaintips()73assert_equal(len(node3_chaintips), num_tips)74assert {75'height': height,76'hash': tip_hash,77'branchlen': height,78'status': 'headers-only',79} in node3_chaintips81check_node3_chaintips(2, self.nodes[0].getbestblockhash(), NODE1_BLOCKS_REQUIRED-1)83for node in self.nodes[1:3]:84chaintips = node.getchaintips()85assert_equal(len(chaintips), 1)86assert {87'height': 0,88'hash': '0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206',89'branchlen': 0,90'status': 'active',91} in chaintips93self.log.info("Generate more blocks to satisfy node1's minchainwork requirement, and verify node2 still has no new headers in headers tree")94with (95self.nodes[2].assert_debug_log(expected_msgs=["[net] Ignoring low-work chain (height=15)"], timeout=2),96self.nodes[3].assert_debug_log(expected_msgs=["Synchronizing blockheaders, height: 15"], timeout=2),97):98self.generate(self.nodes[0], NODE1_BLOCKS_REQUIRED - self.nodes[0].getblockcount(), sync_fun=self.no_op)99self.sync_blocks(self.nodes[0:2]) # node3 will sync headers (noban permissions) but not blocks (due to minchainwork)101assert {102'height': 0,103'hash': '0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206',104'branchlen': 0,105'status': 'active',106} in self.nodes[2].getchaintips()108assert_equal(len(self.nodes[2].getchaintips()), 1)110self.log.info("Check that node3 accepted these headers as well")111check_node3_chaintips(2, self.nodes[0].getbestblockhash(), NODE1_BLOCKS_REQUIRED)113self.log.info("Generate long chain for node0/node1/node3")114self.generate(self.nodes[0], NODE2_BLOCKS_REQUIRED-self.nodes[0].getblockcount(), sync_fun=self.no_op)116self.log.info("Verify that node2 and node3 will sync the chain when it gets long enough")117self.sync_blocks()119def test_peerinfo_includes_headers_presync_height(self):120self.log.info("Test that getpeerinfo() includes headers presync height")122# Disconnect network, so that we can find our own peer connection more123# easily124self.disconnect_all()126p2p = self.nodes[0].add_p2p_connection(P2PInterface())127node = self.nodes[0]129# Ensure we have a long chain already130current_height = self.nodes[0].getblockcount()131if (current_height < 3000):132self.generate(node, 3000-current_height, sync_fun=self.no_op)134# Send a group of 2000 headers, forking from genesis.135new_blocks = []136hashPrevBlock = int(node.getblockhash(0), 16)137for i in range(2000):138block = create_block(hashprev = hashPrevBlock, tmpl=node.getblocktemplate(NORMAL_GBT_REQUEST_PARAMS))139block.solve()140new_blocks.append(block)141hashPrevBlock = block.hash_int143headers_message = msg_headers(headers=new_blocks)144p2p.send_and_ping(headers_message)146# getpeerinfo should show a sync in progress147assert_equal(node.getpeerinfo()[0]['presynced_headers'], 2000)149self.log.info("Test whether a lagging clock aborts low-work headers sync")150node.disconnect_p2ps()151node.setmocktime(node.getblockheader(node.getblockhash(0))['mediantime'] - MAX_FUTURE_BLOCK_TIME - 1)152p2p = node.add_p2p_connection(P2PInterface())153p2p.send_without_ping(headers_message)154node.wait_until_stopped(expect_error=True, expected_ret_code=[-6, # Unix1553, # Windows native1560xC0000409], # Windows cross builds157expected_stderr=re.compile("Failure when attempting to initiate headers sync: System clock"))159def test_large_reorgs_can_succeed(self):160self.log.info("Test that a 2000+ block reorg, starting from a point that is more than 2000 blocks before a locator entry, can succeed")162self.sync_all() # Ensure all nodes are synced.163self.disconnect_all()165# locator(block at height T) will have heights:166# [T, T-1, ..., T-10, T-12, T-16, T-24, T-40, T-72, T-136, T-264,167# T-520, T-1032, T-2056, T-4104, ...]168# So mine a number of blocks > 4104 to ensure that the first window of169# received headers during a sync are fully between locator entries.170BLOCKS_TO_MINE = 4110172self.generate(self.nodes[0], BLOCKS_TO_MINE, sync_fun=self.no_op)173self.generate(self.nodes[1], BLOCKS_TO_MINE+2, sync_fun=self.no_op)175self.reconnect_all()177self.mocktime_all(int(time.time())) # Temporarily hold time to avoid internal timeouts178self.sync_blocks(timeout=300) # Ensure tips eventually agree179self.mocktime_all(0)182def run_test(self):183self.test_chains_sync_when_long_enough()185self.test_large_reorgs_can_succeed()187self.test_peerinfo_includes_headers_presync_height()191if __name__ == '__main__':192RejectLowDifficultyHeadersTest(__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.