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"""Test RPC calls related to net.7Tests correspond to code in rpc/net.cpp.8"""10from decimal import Decimal11from itertools import product12import platform13import time15import test_framework.messages16from test_framework.p2p import (17P2PInterface,18P2P_SERVICES,19)20from test_framework.test_framework import BitcoinTestFramework21from test_framework.util import (22assert_approx,23assert_equal,24assert_greater_than,25assert_raises_rpc_error,26p2p_port,27)28from test_framework.wallet import MiniWallet31def assert_net_servicesnames(servicesflag, servicenames):32"""Utility that checks if all flags are correctly decoded in33`getpeerinfo` and `getnetworkinfo`.35:param servicesflag: The services as an integer.36:param servicenames: The list of decoded services names, as strings.37"""38servicesflag_generated = 039for servicename in servicenames:40servicesflag_generated |= getattr(test_framework.messages, 'NODE_' + servicename)41assert_equal(servicesflag_generated, servicesflag)44def seed_addrman(node):45""" Populate the addrman with addresses from different networks.46Here 2 ipv4, 2 ipv6, 1 cjdns, 2 onion and 1 i2p addresses are added.47"""48# These addresses currently don't collide with a deterministic addrman.49# If the addrman positioning/bucketing is changed, these might collide50# and adding them fails.51success = { "success": True }52assert_equal(node.addpeeraddress(address="1.2.3.4", tried=True, port=8333), success)53assert_equal(node.addpeeraddress(address="2.0.0.0", port=8333), success)54assert_equal(node.addpeeraddress(address="1233:3432:2434:2343:3234:2345:6546:4534", tried=True, port=8333), success)55assert_equal(node.addpeeraddress(address="2803:0:1234:abcd::1", port=45324), success)56assert_equal(node.addpeeraddress(address="fc00:1:2:3:4:5:6:7", port=8333), success)57assert_equal(node.addpeeraddress(address="pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion", tried=True, port=8333), success)58assert_equal(node.addpeeraddress(address="nrfj6inpyf73gpkyool35hcmne5zwfmse3jl3aw23vk7chdemalyaqad.onion", port=45324, tried=True), success)59assert_equal(node.addpeeraddress(address="c4gfnttsuwqomiygupdqqqyy5y5emnk5c73hrfvatri67prd7vyq.b32.i2p", port=8333), success)62class NetTest(BitcoinTestFramework):63def set_test_params(self):64self.num_nodes = 265self.extra_args = [66["-minrelaytxfee=0.00001000"],67["-minrelaytxfee=0.00000500"],68]69# Specify a non-working proxy to make sure no actual connections to public IPs are attempted70for args in self.extra_args:71args.append("-proxy=127.0.0.1:1")72self.supports_cli = False74def run_test(self):75# We need miniwallet to make a transaction76self.wallet = MiniWallet(self.nodes[0])78# By default, the test framework sets up an addnode connection from79# node 1 --> node0. By connecting node0 --> node 1, we're left with80# the two nodes being connected both ways.81# Topology will look like: node0 <--> node182self.connect_nodes(0, 1)83self.sync_all()85self.test_connection_count()86self.test_getpeerinfo()87self.test_getnettotals()88self.test_getnetworkinfo()89self.test_addnode_getaddednodeinfo()90self.test_service_flags()91self.test_getnodeaddresses()92self.test_addpeeraddress()93self.test_sendmsgtopeer()94self.test_getaddrmaninfo()95self.test_getrawaddrman()97def test_connection_count(self):98self.log.info("Test getconnectioncount")99# After using `connect_nodes` to connect nodes 0 and 1 to each other.100assert_equal(self.nodes[0].getconnectioncount(), 2)102def test_getpeerinfo(self):103self.log.info("Test getpeerinfo")104# Create a few getpeerinfo last_block/last_transaction values.105self.wallet.send_self_transfer(from_node=self.nodes[0]) # Make a transaction so we can see it in the getpeerinfo results106self.generate(self.nodes[1], 1)107time_now = int(time.time())108peer_info = [x.getpeerinfo() for x in self.nodes]109# Verify last_block and last_transaction keys/values.110for node, peer, field in product(range(self.num_nodes), range(2), ['last_block', 'last_transaction']):111assert field in peer_info[node][peer].keys()112if peer_info[node][peer][field] != 0:113assert_approx(peer_info[node][peer][field], time_now, vspan=60)114# check both sides of bidirectional connection between nodes115# the address bound to on one side will be the source address for the other node116assert_equal(peer_info[0][0]['addrbind'], peer_info[1][0]['addr'])117assert_equal(peer_info[1][0]['addrbind'], peer_info[0][0]['addr'])118assert_equal(peer_info[0][0]['minfeefilter'], Decimal("0.00000500"))119assert_equal(peer_info[1][0]['minfeefilter'], Decimal("0.00001000"))120# check the `servicesnames` field121for info in peer_info:122assert_net_servicesnames(int(info[0]["services"], 0x10), info[0]["servicesnames"])124assert_equal(peer_info[0][0]['connection_type'], 'inbound')125assert_equal(peer_info[0][1]['connection_type'], 'manual')127assert_equal(peer_info[1][0]['connection_type'], 'manual')128assert_equal(peer_info[1][1]['connection_type'], 'inbound')130# Check dynamically generated networks list in getpeerinfo help output.131assert "(ipv4, ipv6, onion, i2p, cjdns, not_publicly_routable)" in self.nodes[0].help("getpeerinfo")133self.log.info("Check getpeerinfo output before a version message was sent")134no_version_peer_id = 2135no_version_peer_conntime = int(time.time())136self.nodes[0].setmocktime(no_version_peer_conntime)137with self.nodes[0].wait_for_new_peer():138no_version_peer = self.nodes[0].add_p2p_connection(P2PInterface(), send_version=False, wait_for_verack=False)139if self.options.v2transport:140self.wait_until(lambda: self.nodes[0].getpeerinfo()[no_version_peer_id]["transport_protocol_type"] == "v2")141self.nodes[0].setmocktime(0)142peer_info = self.nodes[0].getpeerinfo()[no_version_peer_id]143peer_info.pop("addr")144peer_info.pop("addrbind")145# The next two fields will vary for v2 connections because we send a rng-based number of decoy messages146peer_info.pop("bytesrecv")147peer_info.pop("bytessent")148assert_equal(149peer_info,150{151"addr_processed": 0,152"addr_rate_limited": 0,153"addr_relay_enabled": False,154"bip152_hb_from": False,155"bip152_hb_to": False,156"bytesrecv_per_msg": {},157"bytessent_per_msg": {},158"connection_type": "inbound",159"conntime": no_version_peer_conntime,160"id": no_version_peer_id,161"inbound": True,162"inflight": [],163"last_block": 0,164"last_transaction": 0,165"lastrecv": 0 if not self.options.v2transport else no_version_peer_conntime,166"lastsend": 0 if not self.options.v2transport else no_version_peer_conntime,167"minfeefilter": Decimal("0E-8"),168"network": "not_publicly_routable",169"permissions": [],170"presynced_headers": -1,171"relaytxes": False,172"inv_to_send": 0,173"last_inv_sequence": 0,174"services": "0000000000000000",175"servicesnames": [],176"session_id": "" if not self.options.v2transport else no_version_peer.v2_state.peer['session_id'].hex(),177"subver": "",178"synced_blocks": -1,179"synced_headers": -1,180"timeoffset": 0,181"transport_protocol_type": "v1" if not self.options.v2transport else "v2",182"version": 0,183},184)185no_version_peer.peer_disconnect()186self.wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 2)188def test_getnettotals(self):189self.log.info("Test getnettotals")190# Test getnettotals and getpeerinfo by doing a ping. The bytes191# sent/received should increase by at least the size of one ping192# and one pong. Both have a payload size of 8 bytes, but the total193# size depends on the used p2p version:194# - p2p v1: 24 bytes (header) + 8 bytes (payload) = 32 bytes195# - p2p v2: 21 bytes (header/tag with short-id) + 8 bytes (payload) = 29 bytes196ping_size = 32 if not self.options.v2transport else 29197net_totals_before = self.nodes[0].getnettotals()198peer_info_before = self.nodes[0].getpeerinfo()200self.nodes[0].ping()201self.wait_until(lambda: (self.nodes[0].getnettotals()['totalbytessent'] >= net_totals_before['totalbytessent'] + ping_size * 2), timeout=1)202self.wait_until(lambda: (self.nodes[0].getnettotals()['totalbytesrecv'] >= net_totals_before['totalbytesrecv'] + ping_size * 2), timeout=1)204for peer_before in peer_info_before:205def peer_after():206return next(p for p in self.nodes[0].getpeerinfo() if p['id'] == peer_before['id'])208self.wait_until(lambda: peer_after()['bytesrecv_per_msg'].get('pong', 0) >= peer_before['bytesrecv_per_msg'].get('pong', 0) + ping_size, timeout=1)209self.wait_until(lambda: peer_after()['bytessent_per_msg'].get('ping', 0) >= peer_before['bytessent_per_msg'].get('ping', 0) + ping_size, timeout=1)211def test_getnetworkinfo(self):212self.log.info("Test getnetworkinfo")213info = self.nodes[0].getnetworkinfo()214assert_equal(info['networkactive'], True)215assert_equal(info['connections'], 2)216assert_equal(info['connections_in'], 1)217assert_equal(info['connections_out'], 1)219with self.nodes[0].assert_debug_log(expected_msgs=['SetNetworkActive: false\n']):220self.nodes[0].setnetworkactive(state=False)221assert_equal(self.nodes[0].getnetworkinfo()['networkactive'], False)222# Wait a bit for all sockets to close223for n in self.nodes:224self.wait_until(lambda: n.getnetworkinfo()['connections'] == 0, timeout=3)226with self.nodes[0].assert_debug_log(expected_msgs=['SetNetworkActive: true\n']):227self.nodes[0].setnetworkactive(state=True)228# Connect nodes both ways.229self.connect_nodes(0, 1)230self.connect_nodes(1, 0)232info = self.nodes[0].getnetworkinfo()233assert_equal(info['networkactive'], True)234assert_equal(info['connections'], 2)235assert_equal(info['connections_in'], 1)236assert_equal(info['connections_out'], 1)238# check the `servicesnames` field239network_info = [node.getnetworkinfo() for node in self.nodes]240for info in network_info:241assert_net_servicesnames(int(info["localservices"], 0x10), info["localservicesnames"])243# Check dynamically generated networks list in getnetworkinfo help output.244assert "(ipv4, ipv6, onion, i2p, cjdns)" in self.nodes[0].help("getnetworkinfo")246def test_addnode_getaddednodeinfo(self):247self.log.info("Test addnode and getaddednodeinfo")248assert_equal(self.nodes[0].getaddednodeinfo(), [])249self.log.info("Add a node (node2) to node0")250ip_port = "127.0.0.1:{}".format(p2p_port(2))
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.