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) 2014-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 running bitcoind with the -rpcbind and -rpcallowip options."""7from test_framework.netutil import NETWORK_ERRORS, all_interfaces, addr_to_hex, get_bind_addrs, test_ipv6_local8from test_framework.test_framework import BitcoinTestFramework, SkipTest9from test_framework.test_node import ErrorMatch10from test_framework.util import assert_equal, rpc_port12class RPCBindTest(BitcoinTestFramework):13def set_test_params(self):14self.setup_clean_chain = True15self.bind_to_localhost_only = False16self.num_nodes = 118def skip_test_if_missing_module(self):19self.skip_if_platform_not_posix()20self.skip_if_no_lsof_on_nonlinux()22def setup_network(self):23self.add_nodes(self.num_nodes, None)25def add_options(self, parser):26parser.add_argument("--ipv4", action='store_true', dest="run_ipv4", help="Run ipv4 tests only", default=False)27parser.add_argument("--ipv6", action='store_true', dest="run_ipv6", help="Run ipv6 tests only", default=False)28parser.add_argument("--nonloopback", action='store_true', dest="run_nonloopback", help="Run non-loopback tests only", default=False)30def run_bind_test(self, allow_ips, connect_to, addresses, expected):31'''32Start a node with requested rpcallowip and rpcbind parameters,33then try to connect, and check if the set of bound addresses34matches the expected set.35'''36self.log.info("Bind test for %s" % str(addresses))37expected = [(addr_to_hex(addr), port) for (addr, port) in expected]38base_args = ['-disablewallet', '-nolisten']39if allow_ips:40base_args += ['-rpcallowip=' + x for x in allow_ips]41binds = ['-rpcbind='+addr for addr in addresses]42self.nodes[0].rpchost = connect_to43self.start_node(0, base_args + binds)44pid = self.nodes[0].process.pid45assert_equal(set(get_bind_addrs(pid)), set(expected))46self.stop_nodes()48def run_invalid_bind_test(self, allow_ips, addresses):49'''50Attempt to start a node with requested rpcallowip and rpcbind51parameters, expecting that the node will fail.52'''53self.log.info(f'Invalid bind test for {addresses}')54base_args = ['-disablewallet', '-nolisten']55if allow_ips:56base_args += ['-rpcallowip=' + x for x in allow_ips]57init_error = 'Error: Invalid port specified in -rpcbind: '58for addr in addresses:59self.nodes[0].assert_start_raises_init_error(base_args + [f'-rpcbind={addr}'], init_error + f"'{addr}'")61def run_allowip_test(self, allow_ips, rpchost, rpcport):62'''63Start a node with rpcallow IP, and request getnetworkinfo64at a non-localhost IP.65'''66success = True67self.log.info("Allow IP test for %s:%d" % (rpchost, rpcport))68node_args = \69['-disablewallet', '-nolisten'] + \70['-rpcallowip='+x for x in allow_ips] + \71['-rpcbind='+addr for addr in ['127.0.0.1', "%s:%d" % (rpchost, rpcport)]] # Bind to localhost as well so start_nodes doesn't hang72self.nodes[0].rpchost = None73self.start_nodes([node_args])74self.nodes[0].rpchost = f"{rpchost}:{rpcport}"75# connect to node through non-loopback interface76node = self.nodes[0].create_new_rpc_connection()77try:78node.getnetworkinfo()79except NETWORK_ERRORS:80success = False81self.stop_nodes()82return success84def run_invalid_allowip_test(self):85'''86Check parameter interaction with -rpcallowip and -cjdnsreachable.87RFC4193 addresses are fc00::/7 like CJDNS but have an optional88"local" L bit making them fd00:: which should always be OK.89'''90self.log.info("Allow RFC4193 when compatible with CJDNS options")91# Don't rpcallow RFC4193 with L-bit=0 if CJDNS is enabled92self.nodes[0].assert_start_raises_init_error(93["-rpcallowip=fc00:db8:c0:ff:ee::/80","-cjdnsreachable"],94"Invalid -rpcallowip subnet specification",95match=ErrorMatch.PARTIAL_REGEX)96# OK to rpcallow RFC4193 with L-bit=1 if CJDNS is enabled97self.start_node(0, ["-rpcallowip=fd00:db8:c0:ff:ee::/80","-cjdnsreachable"])98self.stop_nodes()99# OK to rpcallow RFC4193 with L-bit=0 if CJDNS is not enabled100self.start_node(0, ["-rpcallowip=fc00:db8:c0:ff:ee::/80"])101self.stop_nodes()103def run_test(self):104if sum([self.options.run_ipv4, self.options.run_ipv6, self.options.run_nonloopback]) > 1:105raise AssertionError("Only one of --ipv4, --ipv6 and --nonloopback can be set")107self.log.info("Check for ipv6")108have_ipv6 = test_ipv6_local()109if not have_ipv6 and not (self.options.run_ipv4 or self.options.run_nonloopback):110raise SkipTest("This test requires ipv6 support.")112self.log.info("Check for non-loopback interface")113interfaces = all_interfaces()114if not interfaces:115raise AssertionError("all_interfaces() returned no IPv4 interfaces")116self.non_loopback_ip = None117for name,ip in interfaces:118if not ip.startswith('127.'):119self.non_loopback_ip = ip120break121if self.non_loopback_ip is None and self.options.run_nonloopback:122raise SkipTest("This test requires a non-loopback ip address.")124self.defaultport = rpc_port(0)126if not self.options.run_nonloopback:127self._run_loopback_tests()128if self.options.run_ipv4:129self.run_invalid_bind_test(['127.0.0.1'], ['127.0.0.1:notaport', '127.0.0.1:-18443', '127.0.0.1:0', '127.0.0.1:65536'])130if self.options.run_ipv6:131self.run_invalid_bind_test(['[::1]'], ['[::1]:notaport', '[::1]:-18443', '[::1]:0', '[::1]:65536'])132self.run_invalid_allowip_test()133if not self.options.run_ipv4 and not self.options.run_ipv6:134if self.non_loopback_ip:135self._run_nonloopback_tests()136else:137self.log.info('Non-loopback IP address not found, skipping non-loopback tests')139def _run_loopback_tests(self):140if self.options.run_ipv4:141# check only IPv4 localhost (explicit)142self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1'],143[('127.0.0.1', self.defaultport)])144# check only IPv4 localhost (explicit) with alternative port145self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171'],146[('127.0.0.1', 32171)])147# check only IPv4 localhost (explicit) with multiple alternative ports on same host148self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171', '127.0.0.1:32172'],149[('127.0.0.1', 32171), ('127.0.0.1', 32172)])150else:151# check default without rpcallowip (IPv4 and IPv6 localhost)152self.run_bind_test(None, '127.0.0.1', [],153[('127.0.0.1', self.defaultport), ('::1', self.defaultport)])154# check default with rpcallowip (IPv4 and IPv6 localhost)155self.run_bind_test(['127.0.0.1'], '127.0.0.1', [],156[('127.0.0.1', self.defaultport), ('::1', self.defaultport)])157# check only IPv6 localhost (explicit)158self.run_bind_test(['[::1]'], '[::1]', ['[::1]'],159[('::1', self.defaultport)])160# check both IPv4 and IPv6 localhost (explicit)161self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '[::1]'],162[('127.0.0.1', self.defaultport), ('::1', self.defaultport)])164def _run_nonloopback_tests(self):165self.log.info("Using interface %s for testing" % self.non_loopback_ip)167# check only non-loopback interface168self.run_bind_test([self.non_loopback_ip], self.non_loopback_ip, [self.non_loopback_ip],169[(self.non_loopback_ip, self.defaultport)])171# Check that connections from allowed IPs are allowed172assert self.run_allowip_test([self.non_loopback_ip], self.non_loopback_ip, self.defaultport)173# Otherwise we are denied174if self.options.usecli:175self.log.info("Skip negative IP test with CLI, because the CLI can not throw the tested exception type")176return177assert not self.run_allowip_test(['1.1.1.1'], self.non_loopback_ip, self.defaultport)179if __name__ == '__main__':180RPCBindTest(__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.