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"""6Test stalling logic during IBD7"""9import time11from test_framework.blocktools import (12create_block,13)14from test_framework.messages import (15MSG_BLOCK,16MSG_TYPE_MASK,17)18from test_framework.p2p import (19CBlockHeader,20msg_block,21msg_headers,22P2PDataStore,23)24from test_framework.test_framework import BitcoinTestFramework25from test_framework.util import (26assert_equal,27)30class P2PStaller(P2PDataStore):31def __init__(self, stall_blocks):32self.stall_blocks = stall_blocks33super().__init__()35def on_getdata(self, message):36for inv in message.inv:37self.getdata_requests.append(inv.hash)38if (inv.type & MSG_TYPE_MASK) == MSG_BLOCK:39if (inv.hash not in self.stall_blocks):40self.send_without_ping(msg_block(self.block_store[inv.hash]))42def on_getheaders(self, message):43pass46class P2PIBDStallingTest(BitcoinTestFramework):47def set_test_params(self):48self.setup_clean_chain = True49self.num_nodes = 151def run_test(self):52NUM_BLOCKS = 102553NUM_PEERS = 554node = self.nodes[0]55tip = int(node.getbestblockhash(), 16)56blocks = []57height = 158block_time = node.getblock(node.getbestblockhash())['time'] + 159self.log.info("Prepare blocks without sending them to the node")60block_dict = {}61for _ in range(NUM_BLOCKS):62blocks.append(create_block(tip, height=height, ntime=block_time))63blocks[-1].solve()64tip = blocks[-1].hash_int65block_time += 166height += 167block_dict[blocks[-1].hash_int] = blocks[-1]68stall_index = 069second_stall_index = 50070stall_blocks = [blocks[stall_index].hash_int, blocks[second_stall_index].hash_int]72headers_message = msg_headers()73headers_message.headers = [CBlockHeader(b) for b in blocks[:NUM_BLOCKS-1]]74peers = []76self.log.info("Check that a staller does not get disconnected if the 1024 block lookahead buffer is filled")77self.mocktime = int(time.time()) + 178node.setmocktime(self.mocktime)79for id in range(NUM_PEERS):80peers.append(node.add_outbound_p2p_connection(P2PStaller(stall_blocks), p2p_idx=id, connection_type="outbound-full-relay"))81peers[-1].block_store = block_dict82peers[-1].send_and_ping(headers_message)84# Wait until all blocks are received (except for the stall blocks), so that no other blocks are in flight.85self.wait_until(lambda: sum(len(peer['inflight']) for peer in node.getpeerinfo()) == len(stall_blocks))87self.all_sync_send_with_ping(peers)88# If there was a peer marked for stalling, it would get disconnected89self.mocktime += 390node.setmocktime(self.mocktime)91self.all_sync_send_with_ping(peers)92assert_equal(node.num_test_p2p_connections(), NUM_PEERS)94self.log.info("Check that increasing the window beyond 1024 blocks triggers stalling logic")95headers_message.headers = [CBlockHeader(b) for b in blocks]96with node.assert_debug_log(expected_msgs=['Stall started']):97for p in peers:98p.send_without_ping(headers_message)99self.all_sync_send_with_ping(peers)101self.log.info("Check that the stalling peer is disconnected after 2 seconds")102self.mocktime += 3103node.setmocktime(self.mocktime)104peers[0].wait_for_disconnect()105assert_equal(node.num_test_p2p_connections(), NUM_PEERS - 1)106self.wait_until(lambda: self.is_block_requested(peers, stall_blocks[0]))107# Make sure that SendMessages() is invoked, which assigns the missing block108# to another peer and starts the stalling logic for them109self.all_sync_send_with_ping(peers)111self.log.info("Check that the stalling timeout gets doubled to 4 seconds for the next staller")112# No disconnect after just 3 seconds113self.mocktime += 3114node.setmocktime(self.mocktime)115self.all_sync_send_with_ping(peers)116assert_equal(node.num_test_p2p_connections(), NUM_PEERS - 1)118self.mocktime += 2119node.setmocktime(self.mocktime)120self.wait_until(lambda: sum(x.is_connected for x in node.p2ps) == NUM_PEERS - 2)121self.wait_until(lambda: self.is_block_requested(peers, stall_blocks[0]))122self.all_sync_send_with_ping(peers)124self.log.info("Check that the stalling timeout gets doubled to 8 seconds for the next staller")125# No disconnect after just 7 seconds126self.mocktime += 7127node.setmocktime(self.mocktime)128self.all_sync_send_with_ping(peers)129assert_equal(node.num_test_p2p_connections(), NUM_PEERS - 2)131self.mocktime += 2132node.setmocktime(self.mocktime)133self.wait_until(lambda: sum(x.is_connected for x in node.p2ps) == NUM_PEERS - 3)134self.wait_until(lambda: self.is_block_requested(peers, stall_blocks[0]))135self.all_sync_send_with_ping(peers)137self.log.info("Provide the first withheld block and check that stalling timeout gets reduced back to 2 seconds")138with node.assert_debug_log(expected_msgs=['Decreased stalling timeout to 2 seconds'], unexpected_msgs=['Stall started']):139for p in peers:140if p.is_connected and (stall_blocks[0] in p.getdata_requests):141p.send_without_ping(msg_block(block_dict[stall_blocks[0]]))142self.all_sync_send_with_ping(peers)144self.log.info("Check that all outstanding blocks up to the second stall block get connected")145self.wait_until(lambda: node.getblockcount() == second_stall_index)148def all_sync_send_with_ping(self, peers):149for p in peers:150if p.is_connected:151p.sync_with_ping()153def is_block_requested(self, peers, hash):154for p in peers:155if p.is_connected and (hash in p.getdata_requests):156return True157return False160if __name__ == '__main__':161P2PIBDStallingTest(__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.