p2p_disconnect_ban.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 2014-present The Limenka developers
   3  # Distributed under the MIT software license, see the accompanying
   4  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  """Test node disconnect and ban behavior"""
   6  import time
   7  from pathlib import Path
   8  
   9  from test_framework.test_framework import LimenkaTestFramework
  10  from test_framework.util import (
  11      assert_equal,
  12      assert_raises_rpc_error,
  13      p2p_port,
  14  )
  15  
  16  class DisconnectBanTest(LimenkaTestFramework):
  17      def set_test_params(self):
  18          self.num_nodes = 2
  19          self.supports_cli = False
  20  
  21      def run_test(self):
  22          self.log.info("Connect nodes both ways")
  23          # By default, the test framework sets up an addnode connection from
  24          # node 1 --> node0. By connecting node0 --> node 1, we're left with
  25          # the two nodes being connected both ways.
  26          # Topology will look like: node0 <--> node1
  27          self.connect_nodes(0, 1)
  28  
  29          self.log.info("Test setban and listbanned RPCs")
  30  
  31          self.log.info("setban: successfully ban single IP address")
  32          assert_equal(len(self.nodes[1].getpeerinfo()), 2)  # node1 should have 2 connections to node0 at this point
  33          self.nodes[1].setban(subnet="127.0.0.1", command="add")
  34          self.wait_until(lambda: len(self.nodes[1].getpeerinfo()) == 0, timeout=10)
  35          assert_equal(len(self.nodes[1].getpeerinfo()), 0)  # all nodes must be disconnected at this point
  36          assert_equal(len(self.nodes[1].listbanned()), 1)
  37  
  38          self.log.info("clearbanned: successfully clear ban list")
  39          self.nodes[1].clearbanned()
  40          assert_equal(len(self.nodes[1].listbanned()), 0)
  41  
  42          self.log.info('Test banlist database recreation')
  43          self.stop_node(1)
  44          target_file = self.nodes[1].chain_path / "banlist.json"
  45          Path.unlink(target_file)
  46          with self.nodes[1].assert_debug_log(["Recreating the banlist database"]):
  47              self.start_node(1)
  48  
  49          assert Path.exists(target_file)
  50          assert_equal(self.nodes[1].listbanned(), [])
  51  
  52          self.nodes[1].setban("127.0.0.0/24", "add")
  53  
  54          self.log.info("setban: fail to ban an already banned subnet")
  55          assert_equal(len(self.nodes[1].listbanned()), 1)
  56          assert_raises_rpc_error(-23, "IP/Subnet already banned", self.nodes[1].setban, "127.0.0.1", "add")
  57  
  58          self.log.info("setban: fail to ban an invalid subnet")
  59          assert_raises_rpc_error(-30, "Error: Invalid IP/Subnet", self.nodes[1].setban, "127.0.0.1/42", "add")
  60          assert_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/24
  61  
  62          self.log.info("setban: fail to ban with past absolute timestamp")
  63          assert_raises_rpc_error(-8, "Error: Absolute timestamp is in the past", self.nodes[1].setban, "127.27.0.1", "add", 123, True)
  64  
  65          self.log.info("setban remove: fail to unban a non-banned subnet")
  66          assert_raises_rpc_error(-30, "Error: Unban failed", self.nodes[1].setban, "127.0.0.1", "remove")
  67          assert_equal(len(self.nodes[1].listbanned()), 1)
  68  
  69          self.log.info("setban remove: successfully unban subnet")
  70          self.nodes[1].setban("127.0.0.0/24", "remove")
  71          assert_equal(len(self.nodes[1].listbanned()), 0)
  72          self.nodes[1].clearbanned()
  73          assert_equal(len(self.nodes[1].listbanned()), 0)
  74  
  75          self.log.info("setban: test persistence across node restart")
  76          # Set the mocktime so we can control when bans expire
  77          old_time = int(time.time())
  78          self.nodes[1].setmocktime(old_time)
  79          self.nodes[1].setban("127.0.0.0/32", "add")
  80          self.nodes[1].setban("127.0.0.0/24", "add")
  81          self.nodes[1].setban("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion", "add")
  82          self.nodes[1].setban("192.168.0.1", "add", 1)  # ban for 1 seconds
  83          self.nodes[1].setban("2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/19", "add", 1000)  # ban for 1000 seconds
  84          listBeforeShutdown = self.nodes[1].listbanned()
  85          assert_equal("192.168.0.1/32", listBeforeShutdown[2]['address'])
  86  
  87          self.log.info("setban: test banning with absolute timestamp")
  88          self.nodes[1].setban("192.168.0.2", "add", old_time + 120, absolute=True)
  89  
  90          # Move time forward by 3 seconds so the fourth ban has expired
  91          self.nodes[1].setmocktime(old_time + 3)
  92          assert_equal(len(self.nodes[1].listbanned()), 5)
  93  
  94          self.log.info("Test ban_duration and time_remaining")
  95          for ban in self.nodes[1].listbanned():
  96              if ban["address"] in ["127.0.0.0/32", "127.0.0.0/24", "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion"]:
  97                  assert_equal(ban["ban_duration"], 86400)
  98                  assert_equal(ban["time_remaining"], 86397)
  99              elif ban["address"] == "2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/19":
 100                  assert_equal(ban["ban_duration"], 1000)
 101                  assert_equal(ban["time_remaining"], 997)
 102              elif ban["address"] == "192.168.0.2/32":
 103                  assert_equal(ban["ban_duration"], 120)
 104                  assert_equal(ban["time_remaining"], 117)
 105  
 106          # Keep mocktime, to avoid ban expiry when restart takes longer than
 107          # time_remaining
 108          self.restart_node(1, extra_args=[f"-mocktime={old_time+4}"])
 109  
 110          listAfterShutdown = self.nodes[1].listbanned()
 111          assert_equal("127.0.0.0/24", listAfterShutdown[0]['address'])
 112          assert_equal("127.0.0.0/32", listAfterShutdown[1]['address'])
 113          assert_equal("192.168.0.2/32", listAfterShutdown[2]['address'])
 114          assert_equal("/19" in listAfterShutdown[3]['address'], True)
 115          assert_equal("pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd.onion", listAfterShutdown[4]['address'])
 116  
 117          # Clear ban lists
 118          self.nodes[1].clearbanned()
 119          self.log.info("Connect nodes both ways")
 120          self.connect_nodes(0, 1)
 121          self.connect_nodes(1, 0)
 122  
 123          self.log.info("Test disconnectnode RPCs")
 124  
 125          self.log.info("disconnectnode: fail to disconnect when calling with address and nodeid")
 126          address1 = self.nodes[0].getpeerinfo()[0]['addr']
 127          node1 = self.nodes[0].getpeerinfo()[0]["id"]
 128          assert_raises_rpc_error(-32602, "Only one of address and nodeid should be provided.", self.nodes[0].disconnectnode, address=address1, nodeid=node1)
 129  
 130          self.log.info("disconnectnode: fail to disconnect when calling with junk address")
 131          assert_raises_rpc_error(-29, "Node not found in connected nodes", self.nodes[0].disconnectnode, address="221B Baker Street")
 132  
 133          self.log.info("disconnectnode: fail to disconnect when calling with invalid subnet")
 134          assert_raises_rpc_error(-8, "Invalid subnet", self.nodes[0].disconnectnode, address="1.2.3.0/24\0")
 135  
 136          self.log.info("disconnectnode: successfully disconnect node by address and port")
 137          address1 = "127.0.0.1:" + str(p2p_port(1))
 138          assert [node for node in self.nodes[0].getpeerinfo() if node['addr'] == address1]
 139          self.nodes[0].disconnectnode(address=address1)
 140          self.wait_until(lambda: len(self.nodes[1].getpeerinfo()) == 1, timeout=10)
 141          assert not [node for node in self.nodes[0].getpeerinfo() if node['addr'] == address1]
 142  
 143          self.log.info("disconnectnode: successfully reconnect node")
 144          self.connect_nodes(0, 1)  # reconnect the node
 145          assert_equal(len(self.nodes[0].getpeerinfo()), 2)
 146          assert [node for node in self.nodes[0].getpeerinfo() if node['addr'] == address1]
 147  
 148          self.log.info("disconnectnode: successfully disconnect node by address (no port)")
 149          nodes = self.nodes[0].getpeerinfo()
 150          assert nodes and all(node['addr'].startswith('127.0.0.') for node in nodes)
 151          self.nodes[0].disconnectnode(address='127.0.0.1')
 152          self.wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 0, timeout=10)
 153          # reconnect the nodes
 154          self.connect_nodes(0, 1)
 155          self.connect_nodes(1, 0)
 156  
 157          self.log.info("disconnectnode: successfully disconnect node by node id")
 158          id1 = [node for node in self.nodes[0].getpeerinfo() if node['addr'] == address1][0]['id']
 159          self.nodes[0].disconnectnode(nodeid=id1)
 160          self.wait_until(lambda: len(self.nodes[1].getpeerinfo()) == 1, timeout=10)
 161          assert not [node for node in self.nodes[0].getpeerinfo() if node['id'] == id1]
 162          self.connect_nodes(0, 1)  # reconnect the node
 163  
 164          self.log.info("disconnectnode: successfully disconnect node by subnet")
 165          nodes = self.nodes[0].getpeerinfo()
 166          assert nodes and all(node['addr'].startswith('127.0.0.') for node in nodes)
 167          self.nodes[0].disconnectnode(address='127.0.0.1/24')
 168          self.wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 0, timeout=10)
 169  
 170  if __name__ == '__main__':
 171      DisconnectBanTest(__file__).main()
 172