p2p_node_network_limited.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 2017-present The Bitcoin Core developers
   3  # Distributed under the MIT software license, see the accompanying
   4  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  """Tests NODE_NETWORK_LIMITED.
   6  
   7  Tests that a node configured with -prune=550 signals NODE_NETWORK_LIMITED correctly
   8  and that it responds to getdata requests for blocks correctly:
   9      - send a block within 288 + 2 of the tip
  10      - disconnect peers who request blocks older than that."""
  11  from test_framework.messages import (
  12      CInv,
  13      MSG_BLOCK,
  14      NODE_NETWORK_LIMITED,
  15      NODE_P2P_V2,
  16      NODE_WITNESS,
  17      msg_getdata,
  18  )
  19  from test_framework.p2p import P2PInterface
  20  from test_framework.test_framework import BitcoinTestFramework
  21  from test_framework.util import (
  22      assert_equal,
  23      assert_raises_rpc_error,
  24      try_rpc
  25  )
  26  
  27  # Minimum blocks required to signal NODE_NETWORK_LIMITED #
  28  NODE_NETWORK_LIMITED_MIN_BLOCKS = 288
  29  
  30  class P2PIgnoreInv(P2PInterface):
  31      def on_inv(self, message):
  32          # The node will send us invs for other blocks. Ignore them.
  33          pass
  34      def send_getdata_for_block(self, blockhash):
  35          getdata_request = msg_getdata()
  36          getdata_request.inv.append(CInv(MSG_BLOCK, int(blockhash, 16)))
  37          self.send_without_ping(getdata_request)
  38  
  39  class NodeNetworkLimitedTest(BitcoinTestFramework):
  40      def set_test_params(self):
  41          self.setup_clean_chain = True
  42          self.num_nodes = 3
  43          self.extra_args = [['-prune=550'], [], []]
  44  
  45      def disconnect_all(self):
  46          self.disconnect_nodes(0, 1)
  47          self.disconnect_nodes(0, 2)
  48          self.disconnect_nodes(1, 2)
  49  
  50      def setup_network(self):
  51          self.add_nodes(self.num_nodes, self.extra_args)
  52          self.start_nodes()
  53  
  54      def test_avoid_requesting_historical_blocks(self):
  55          self.log.info("Test full node does not request blocks beyond the limited peer threshold")
  56          pruned_node = self.nodes[0]
  57          miner = self.nodes[1]
  58          full_node = self.nodes[2]
  59  
  60          # Connect and generate block to ensure IBD=false
  61          self.connect_nodes(1, 0)
  62          self.connect_nodes(1, 2)
  63          self.generate(miner, 1)
  64  
  65          # Verify peers are out of IBD
  66          for node in self.nodes:
  67              assert not node.getblockchaininfo()['initialblockdownload']
  68  
  69          # Isolate full_node (the node will remain out of IBD)
  70          full_node.setnetworkactive(False)
  71          self.wait_until(lambda: len(full_node.getpeerinfo()) == 0)
  72  
  73          # Mine blocks and sync the pruned node. Surpass the NETWORK_NODE_LIMITED threshold.
  74          # Blocks deeper than the threshold are considered "historical blocks"
  75          num_historial_blocks = 12
  76          self.generate(miner, NODE_NETWORK_LIMITED_MIN_BLOCKS + num_historial_blocks, sync_fun=self.no_op)
  77          self.sync_blocks([miner, pruned_node])
  78  
  79          # Connect full_node to prune_node and check peers don't disconnect right away.
  80          # (they will disconnect if full_node, which is chain-wise behind, request blocks
  81          # older than NODE_NETWORK_LIMITED_MIN_BLOCKS)
  82          start_height_full_node = full_node.getblockcount()
  83          full_node.setnetworkactive(True)
  84          self.connect_nodes(2, 0)
  85          assert_equal(len(full_node.getpeerinfo()), 1)
  86  
  87          # Wait until the full_node is headers-wise sync
  88          best_block_hash = pruned_node.getbestblockhash()
  89          default_value = {'status': ''}  # No status
  90          self.wait_until(lambda: next(filter(lambda x: x['hash'] == best_block_hash, full_node.getchaintips()), default_value)['status'] == "headers-only")
  91  
  92          # Now, since the node aims to download a window of 1024 blocks,
  93          # ensure it requests the blocks below the threshold only (with a
  94          # 2-block buffer). And also, ensure it does not request any
  95          # historical block.
  96          tip_height = pruned_node.getblockcount()
  97          limit_buffer = 2
  98          # Prevent races by waiting for the tip to arrive first
  99          self.wait_until(lambda: not try_rpc(-1, "Block not available (not fully downloaded)", full_node.getblock, pruned_node.getbestblockhash()))
 100          for height in range(start_height_full_node + 1, tip_height + 1):
 101              if height <= tip_height - (NODE_NETWORK_LIMITED_MIN_BLOCKS - limit_buffer):
 102                  assert_raises_rpc_error(-1, "Block not available (not fully downloaded)", full_node.getblock, pruned_node.getblockhash(height))
 103              else:
 104                  full_node.getblock(pruned_node.getblockhash(height))  # just assert it does not throw an exception
 105  
 106          # Lastly, ensure the full_node is not sync and verify it can get synced by
 107          # establishing a connection with another full node capable of providing them.
 108          assert_equal(full_node.getblockcount(), start_height_full_node)
 109          self.connect_nodes(2, 1)
 110          self.sync_blocks([miner, full_node])
 111  
 112      def run_test(self):
 113          node = self.nodes[0].add_p2p_connection(P2PIgnoreInv())
 114  
 115          expected_services = NODE_WITNESS | NODE_NETWORK_LIMITED
 116          if self.options.v2transport:
 117              expected_services |= NODE_P2P_V2
 118  
 119          self.log.info("Check that node has signalled expected services.")
 120          assert_equal(node.nServices, expected_services)
 121  
 122          self.log.info("Check that the localservices is as expected.")
 123          assert_equal(int(self.nodes[0].getnetworkinfo()['localservices'], 16), expected_services)
 124  
 125          self.log.info("Mine enough blocks to reach the NODE_NETWORK_LIMITED range.")
 126          self.connect_nodes(0, 1)
 127          blocks = self.generate(self.nodes[1], 292, sync_fun=lambda: self.sync_blocks([self.nodes[0], self.nodes[1]]))
 128  
 129          self.log.info("Make sure we can max retrieve block at tip-288.")
 130          node.send_getdata_for_block(blocks[1])  # last block in valid range
 131          node.wait_for_block(int(blocks[1], 16), timeout=3)
 132  
 133          self.log.info("Requesting block at height 2 (tip-289) must fail (ignored).")
 134          node.send_getdata_for_block(blocks[0])  # first block outside of the 288+2 limit
 135          node.wait_for_disconnect(timeout=5)
 136          self.nodes[0].disconnect_p2ps()
 137  
 138          # connect unsynced node 2 with pruned NODE_NETWORK_LIMITED peer
 139          # because node 2 is in IBD and node 0 is a NODE_NETWORK_LIMITED peer, sync must not be possible
 140          self.connect_nodes(0, 2)
 141          try:
 142              self.sync_blocks([self.nodes[0], self.nodes[2]], timeout=5)
 143          except Exception:
 144              pass
 145          # node2 must remain at height 0
 146          assert_equal(self.nodes[2].getblockheader(self.nodes[2].getbestblockhash())['height'], 0)
 147  
 148          # now connect also to node 1 (non pruned)
 149          self.connect_nodes(1, 2)
 150  
 151          # sync must be possible
 152          self.sync_blocks()
 153  
 154          # disconnect all peers
 155          self.disconnect_all()
 156  
 157          # mine 10 blocks on node 0 (pruned node)
 158          self.generate(self.nodes[0], 10, sync_fun=self.no_op)
 159  
 160          # connect node1 (non pruned) with node0 (pruned) and check if the can sync
 161          self.connect_nodes(0, 1)
 162  
 163          # sync must be possible, node 1 is no longer in IBD and should therefore connect to node 0 (NODE_NETWORK_LIMITED)
 164          self.sync_blocks([self.nodes[0], self.nodes[1]])
 165  
 166          self.test_avoid_requesting_historical_blocks()
 167  
 168  if __name__ == '__main__':
 169      NodeNetworkLimitedTest(__file__).main()
 170