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 node disconnect and ban behavior"""6import time7from pathlib import Path9from test_framework.test_framework import BitcoinTestFramework10from test_framework.util import (11assert_equal,12assert_raises_rpc_error,13)15class DisconnectBanTest(BitcoinTestFramework):16def set_test_params(self):17self.num_nodes = 219def run_test(self):20self.log.info("Connect nodes both ways")21# By default, the test framework sets up an addnode connection from22# node 1 --> node0. By connecting node0 --> node 1, we're left with23# the two nodes being connected both ways.24# Topology will look like: node0 <--> node125self.connect_nodes(0, 1)27self.log.info("Test setban and listbanned RPCs")29self.log.info("setban: successfully ban single IP address")30assert_equal(len(self.nodes[1].getpeerinfo()), 2) # node1 should have 2 connections to node0 at this point31self.nodes[1].setban(subnet="127.0.0.1", command="add")32self.wait_until(lambda: len(self.nodes[1].getpeerinfo()) == 0, timeout=10)33assert_equal(len(self.nodes[1].getpeerinfo()), 0) # all nodes must be disconnected at this point34assert_equal(len(self.nodes[1].listbanned()), 1)36self.log.info("clearbanned: successfully clear ban list")37self.nodes[1].clearbanned()38assert_equal(len(self.nodes[1].listbanned()), 0)40self.log.info('Test banlist database recreation')41self.stop_node(1)42target_file = self.nodes[1].chain_path / "banlist.json"43Path.unlink(target_file)44with self.nodes[1].assert_debug_log(["Recreating the banlist database"]):45self.start_node(1)47assert Path.exists(target_file)48assert_equal(self.nodes[1].listbanned(), [])50self.nodes[1].setban("127.0.0.0/24", "add")52self.log.info("setban: fail to ban an already banned subnet")53assert_equal(len(self.nodes[1].listbanned()), 1)54assert_raises_rpc_error(-23, "IP/Subnet already banned", self.nodes[1].setban, "127.0.0.1", "add")56self.log.info("setban: fail to ban an invalid subnet")57assert_raises_rpc_error(-30, "Error: Invalid IP/Subnet", self.nodes[1].setban, "127.0.0.1/42", "add")58assert_equal(len(self.nodes[1].listbanned()), 1) # still only one banned ip because 127.0.0.1 is within the range of 127.0.0.0/2460self.log.info("setban: fail to ban with past absolute timestamp")61assert_raises_rpc_error(-8, "Error: Absolute timestamp is in the past", self.nodes[1].setban, "127.27.0.1", "add", 123, True)63self.log.info("setban remove: fail to unban a non-banned subnet")64assert_raises_rpc_error(-30, "Error: Unban failed", self.nodes[1].setban, "127.0.0.1", "remove")65assert_equal(len(self.nodes[1].listbanned()), 1)67self.log.info("setban remove: successfully unban subnet")68self.nodes[1].setban("127.0.0.0/24", "remove")69assert_equal(len(self.nodes[1].listbanned()), 0)70self.nodes[1].clearbanned()71assert_equal(len(self.nodes[1].listbanned()), 0)73self.log.info("setban: test persistence across node restart")74# Set the mocktime so we can control when bans expire75old_time = int(time.time())76self.nodes[1].setmocktime(old_time)77self.nodes[1].setban("127.0.0.0/32", "add")78self.nodes[1].setban("127.0.0.0/24", "add")79self.nodes[1].setban("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion", "add")80self.nodes[1].setban("192.168.0.1", "add", 1) # ban for 1 seconds81self.nodes[1].setban("2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/19", "add", 1000) # ban for 1000 seconds82listBeforeShutdown = self.nodes[1].listbanned()83assert_equal("192.168.0.1/32", listBeforeShutdown[2]['address'])85self.log.info("setban: test banning with absolute timestamp")86self.nodes[1].setban("192.168.0.2", "add", old_time + 120, absolute=True)88# Move time forward by 3 seconds so the fourth ban has expired89self.nodes[1].setmocktime(old_time + 3)90assert_equal(len(self.nodes[1].listbanned()), 5)92self.log.info("Test ban_duration and time_remaining")93for ban in self.nodes[1].listbanned():94if ban["address"] in ["127.0.0.0/32", "127.0.0.0/24", "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"]:95assert_equal(ban["ban_duration"], 86400)96assert_equal(ban["time_remaining"], 86397)97elif ban["address"] == "2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/19":98assert_equal(ban["ban_duration"], 1000)99assert_equal(ban["time_remaining"], 997)100elif ban["address"] == "192.168.0.2/32":101assert_equal(ban["ban_duration"], 120)102assert_equal(ban["time_remaining"], 117)104# Keep mocktime, to avoid ban expiry when restart takes longer than105# time_remaining106self.restart_node(1, extra_args=[f"-mocktime={old_time+4}"])108listAfterShutdown = self.nodes[1].listbanned()109assert_equal("127.0.0.0/24", listAfterShutdown[0]['address'])110assert_equal("127.0.0.0/32", listAfterShutdown[1]['address'])111assert_equal("192.168.0.2/32", listAfterShutdown[2]['address'])112assert_equal("/19" in listAfterShutdown[3]['address'], True)113assert_equal("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion", listAfterShutdown[4]['address'])115# Clear ban lists116self.nodes[1].clearbanned()117self.log.info("Connect nodes both ways")118self.connect_nodes(0, 1)119self.connect_nodes(1, 0)121self.log.info("Test disconnectnode RPCs")123self.log.info("disconnectnode: fail to disconnect when calling with address and nodeid")124address1 = self.nodes[0].getpeerinfo()[0]['addr']125node1 = self.nodes[0].getpeerinfo()[0]["id"]126assert_raises_rpc_error(-32602, "Only one of address and nodeid should be provided.", self.nodes[0].disconnectnode, address=address1, nodeid=node1)128self.log.info("disconnectnode: fail to disconnect when calling with junk address")129assert_raises_rpc_error(-29, "Node not found in connected nodes", self.nodes[0].disconnectnode, address="221B Baker Street")131self.log.info("disconnectnode: successfully disconnect node by address")132address1 = self.nodes[0].getpeerinfo()[0]['addr']133self.nodes[0].disconnectnode(address=address1)134self.wait_until(lambda: len(self.nodes[1].getpeerinfo()) == 1, timeout=10)135assert address1 not in [node['addr'] for node in self.nodes[0].getpeerinfo()]137self.log.info("disconnectnode: successfully reconnect node")138self.connect_nodes(0, 1) # reconnect the node139assert_equal(len(self.nodes[0].getpeerinfo()), 2)140assert address1 in [node['addr'] for node in self.nodes[0].getpeerinfo()]142self.log.info("disconnectnode: successfully disconnect node by node id")143id1 = self.nodes[0].getpeerinfo()[0]['id']144self.nodes[0].disconnectnode(nodeid=id1)145self.wait_until(lambda: len(self.nodes[1].getpeerinfo()) == 1, timeout=10)146assert id1 not in [node['id'] for node in self.nodes[0].getpeerinfo()]148if __name__ == '__main__':149DisconnectBanTest(__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.