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) 2017-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"""Tests NODE_NETWORK_LIMITED.7Tests that a node configured with -prune=550 signals NODE_NETWORK_LIMITED correctly8and that it responds to getdata requests for blocks correctly:9- send a block within 288 + 2 of the tip10- disconnect peers who request blocks older than that."""11from test_framework.messages import (12CInv,13MSG_BLOCK,14NODE_NETWORK_LIMITED,15NODE_P2P_V2,16NODE_WITNESS,17msg_getdata,18)19from test_framework.p2p import P2PInterface20from test_framework.test_framework import BitcoinTestFramework21from test_framework.util import (22assert_equal,23assert_raises_rpc_error,24try_rpc25)27# Minimum blocks required to signal NODE_NETWORK_LIMITED #28NODE_NETWORK_LIMITED_MIN_BLOCKS = 28830class P2PIgnoreInv(P2PInterface):31def on_inv(self, message):32# The node will send us invs for other blocks. Ignore them.33pass34def send_getdata_for_block(self, blockhash):35getdata_request = msg_getdata()36getdata_request.inv.append(CInv(MSG_BLOCK, int(blockhash, 16)))37self.send_without_ping(getdata_request)39class NodeNetworkLimitedTest(BitcoinTestFramework):40def set_test_params(self):41self.setup_clean_chain = True42self.num_nodes = 343self.extra_args = [['-prune=550'], [], []]45def disconnect_all(self):46self.disconnect_nodes(0, 1)47self.disconnect_nodes(0, 2)48self.disconnect_nodes(1, 2)50def setup_network(self):51self.add_nodes(self.num_nodes, self.extra_args)52self.start_nodes()54def test_avoid_requesting_historical_blocks(self):55self.log.info("Test full node does not request blocks beyond the limited peer threshold")56pruned_node = self.nodes[0]57miner = self.nodes[1]58full_node = self.nodes[2]60# Connect and generate block to ensure IBD=false61self.connect_nodes(1, 0)62self.connect_nodes(1, 2)63self.generate(miner, 1)65# Verify peers are out of IBD66for node in self.nodes:67assert not node.getblockchaininfo()['initialblockdownload']69# Isolate full_node (the node will remain out of IBD)70full_node.setnetworkactive(False)71self.wait_until(lambda: len(full_node.getpeerinfo()) == 0)73# Mine blocks and sync the pruned node. Surpass the NETWORK_NODE_LIMITED threshold.74# Blocks deeper than the threshold are considered "historical blocks"75num_historial_blocks = 1276self.generate(miner, NODE_NETWORK_LIMITED_MIN_BLOCKS + num_historial_blocks, sync_fun=self.no_op)77self.sync_blocks([miner, pruned_node])79# Connect full_node to prune_node and check peers don't disconnect right away.80# (they will disconnect if full_node, which is chain-wise behind, request blocks81# older than NODE_NETWORK_LIMITED_MIN_BLOCKS)82start_height_full_node = full_node.getblockcount()83full_node.setnetworkactive(True)84self.connect_nodes(2, 0)85assert_equal(len(full_node.getpeerinfo()), 1)87# Wait until the full_node is headers-wise sync88best_block_hash = pruned_node.getbestblockhash()89default_value = {'status': ''} # No status90self.wait_until(lambda: next(filter(lambda x: x['hash'] == best_block_hash, full_node.getchaintips()), default_value)['status'] == "headers-only")92# Now, since the node aims to download a window of 1024 blocks,93# ensure it requests the blocks below the threshold only (with a94# 2-block buffer). And also, ensure it does not request any95# historical block.96tip_height = pruned_node.getblockcount()97limit_buffer = 298# Prevent races by waiting for the tip to arrive first99self.wait_until(lambda: not try_rpc(-1, "Block not available (not fully downloaded)", full_node.getblock, pruned_node.getbestblockhash()))100for height in range(start_height_full_node + 1, tip_height + 1):101if height <= tip_height - (NODE_NETWORK_LIMITED_MIN_BLOCKS - limit_buffer):102assert_raises_rpc_error(-1, "Block not available (not fully downloaded)", full_node.getblock, pruned_node.getblockhash(height))103else:104full_node.getblock(pruned_node.getblockhash(height)) # just assert it does not throw an exception106# Lastly, ensure the full_node is not sync and verify it can get synced by107# establishing a connection with another full node capable of providing them.108assert_equal(full_node.getblockcount(), start_height_full_node)109self.connect_nodes(2, 1)110self.sync_blocks([miner, full_node])112def run_test(self):113node = self.nodes[0].add_p2p_connection(P2PIgnoreInv())115expected_services = NODE_WITNESS | NODE_NETWORK_LIMITED116if self.options.v2transport:117expected_services |= NODE_P2P_V2119self.log.info("Check that node has signalled expected services.")120assert_equal(node.nServices, expected_services)122self.log.info("Check that the localservices is as expected.")123assert_equal(int(self.nodes[0].getnetworkinfo()['localservices'], 16), expected_services)125self.log.info("Mine enough blocks to reach the NODE_NETWORK_LIMITED range.")126self.connect_nodes(0, 1)127blocks = self.generate(self.nodes[1], 292, sync_fun=lambda: self.sync_blocks([self.nodes[0], self.nodes[1]]))129self.log.info("Make sure we can max retrieve block at tip-288.")130node.send_getdata_for_block(blocks[1]) # last block in valid range131node.wait_for_block(int(blocks[1], 16), timeout=3)133self.log.info("Requesting block at height 2 (tip-289) must fail (ignored).")134node.send_getdata_for_block(blocks[0]) # first block outside of the 288+2 limit135node.wait_for_disconnect(timeout=5)136self.nodes[0].disconnect_p2ps()138# connect unsynced node 2 with pruned NODE_NETWORK_LIMITED peer139# because node 2 is in IBD and node 0 is a NODE_NETWORK_LIMITED peer, sync must not be possible140self.connect_nodes(0, 2)141try:142self.sync_blocks([self.nodes[0], self.nodes[2]], timeout=5)143except Exception:144pass145# node2 must remain at height 0146assert_equal(self.nodes[2].getblockheader(self.nodes[2].getbestblockhash())['height'], 0)148# now connect also to node 1 (non pruned)149self.connect_nodes(1, 2)151# sync must be possible152self.sync_blocks()154# disconnect all peers155self.disconnect_all()157# mine 10 blocks on node 0 (pruned node)158self.generate(self.nodes[0], 10, sync_fun=self.no_op)160# connect node1 (non pruned) with node0 (pruned) and check if the can sync161self.connect_nodes(0, 1)163# sync must be possible, node 1 is no longer in IBD and should therefore connect to node 0 (NODE_NETWORK_LIMITED)164self.sync_blocks([self.nodes[0], self.nodes[1]])166self.test_avoid_requesting_historical_blocks()168if __name__ == '__main__':169NodeNetworkLimitedTest(__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.