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) 2020-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 block-relay-only anchors functionality"""7import os9from test_framework.p2p import P2PInterface, P2P_SERVICES10from test_framework.socks5 import Socks5Configuration, Socks5Server11from test_framework.messages import CAddress, hash25612from test_framework.test_framework import BitcoinTestFramework13from test_framework.util import check_node_connections, assert_equal15INBOUND_CONNECTIONS = 516BLOCK_RELAY_CONNECTIONS = 217ONION_ADDR = "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion:8333"20class AnchorsTest(BitcoinTestFramework):21def set_test_params(self):22self.num_nodes = 123self.disable_autoconnect = False25def run_test(self):26node_anchors_path = self.nodes[0].chain_path / "anchors.dat"28self.log.info("When node starts, check if anchors.dat doesn't exist")29assert not os.path.exists(node_anchors_path)31self.log.info(f"Add {BLOCK_RELAY_CONNECTIONS} block-relay-only connections to node")32for i in range(BLOCK_RELAY_CONNECTIONS):33self.log.debug(f"block-relay-only: {i}")34self.nodes[0].add_outbound_p2p_connection(35P2PInterface(), p2p_idx=i, connection_type="block-relay-only"36)38self.log.info(f"Add {INBOUND_CONNECTIONS} inbound connections to node")39for i in range(INBOUND_CONNECTIONS):40self.log.debug(f"inbound: {i}")41self.nodes[0].add_p2p_connection(P2PInterface())43self.log.info("Check node connections")44check_node_connections(node=self.nodes[0], num_in=5, num_out=2)46# 127.0.0.147ip = "7f000001"49# Since the ip is always 127.0.0.1 for this case,50# we store only the port to identify the peers51block_relay_nodes_port = []52inbound_nodes_port = []53for p in self.nodes[0].getpeerinfo():54addr_split = p["addr"].split(":")55if p["connection_type"] == "block-relay-only":56block_relay_nodes_port.append(hex(int(addr_split[1]))[2:])57else:58inbound_nodes_port.append(hex(int(addr_split[1]))[2:])60self.log.debug("Stop node")61self.stop_node(0)63# It should contain only the block-relay-only addresses64self.log.info("Check the addresses in anchors.dat")66with open(node_anchors_path, "rb") as file_handler:67anchors = file_handler.read()69anchors_hex = anchors.hex()70for port in block_relay_nodes_port:71ip_port = ip + port72assert ip_port in anchors_hex73for port in inbound_nodes_port:74ip_port = ip + port75assert ip_port not in anchors_hex77self.log.info("Perturb anchors.dat to test it doesn't throw an error during initialization")78with self.nodes[0].assert_debug_log(["0 block-relay-only anchors will be tried for connections."]):79with open(node_anchors_path, "wb") as out_file_handler:80tweaked_contents = bytearray(anchors)81tweaked_contents[20:20] = b'1'82out_file_handler.write(bytes(tweaked_contents))84self.log.debug("Start node")85self.start_node(0)87self.log.info("When node starts, check if anchors.dat doesn't exist anymore")88assert not os.path.exists(node_anchors_path)90self.log.info("Ensure addrv2 support")91# Use proxies to catch outbound connections to networks with 256-bit addresses92onion_conf = Socks5Configuration()93onion_conf.auth = True94onion_conf.unauth = True95# Use port=0 for dynamic allocation to avoid conflicts with concurrent96# tests or ports in TIME_WAIT state from previous test runs.97onion_conf.addr = ('127.0.0.1', 0)98onion_conf.keep_alive = True99onion_proxy = Socks5Server(onion_conf)100onion_proxy.start()101self.restart_node(0, extra_args=[f"-onion={onion_conf.addr[0]}:{onion_conf.addr[1]}"])103self.log.info("Add 256-bit-address block-relay-only connections to node")104self.nodes[0].addconnection(ONION_ADDR, 'block-relay-only', v2transport=False)106self.log.debug("Stop node")107with self.nodes[0].assert_debug_log(["DumpAnchors: Flush 1 outbound block-relay-only peer addresses to anchors.dat"]):108self.stop_node(0)109# Manually close keep_alive proxy connection110onion_proxy.stop()112self.log.info("Check for addrv2 addresses in anchors.dat")113caddr = CAddress()114caddr.net = CAddress.NET_TORV3115caddr.ip, port_str = ONION_ADDR.split(":")116caddr.port = int(port_str)117# TorV3 addrv2 serialization:118# time(4) | services(1) | networkID(1) | address length(1) | address(32)119expected_pubkey = caddr.serialize_v2()[7:39].hex()121# position of services byte of first addr in anchors.dat122# network magic, vector length, version, nTime123services_index = 4 + 1 + 4 + 4124data = bytes()125with open(node_anchors_path, "rb") as file_handler:126data = file_handler.read()127assert_equal(data[services_index], 0x00) # services == NONE128anchors2 = data.hex()129assert expected_pubkey in anchors2131with open(node_anchors_path, "wb") as file_handler:132# Modify service flags for this address even though we never connected to it.133# This is necessary because on restart we will not attempt an anchor connection134# to a host without our required services, even if its address is in the anchors.dat file135new_data = bytearray(data)[:-32]136new_data[services_index] = P2P_SERVICES137new_data_hash = hash256(new_data)138file_handler.write(new_data + new_data_hash)140self.log.info("Restarting node attempts to reconnect to anchors")141with self.nodes[0].assert_debug_log([f"Trying to make an anchor connection to {ONION_ADDR}"], timeout=2):142self.start_node(0, extra_args=[f"-onion={onion_conf.addr[0]}:{onion_conf.addr[1]}"])145if __name__ == "__main__":146AnchorsTest(__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.