p2p_getdata.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 2020-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  """Test GETDATA processing behavior"""
   6  from collections import defaultdict
   7  
   8  from test_framework.messages import (
   9      CInv,
  10      msg_getdata,
  11  )
  12  from test_framework.p2p import P2PInterface
  13  from test_framework.test_framework import BitcoinTestFramework
  14  
  15  
  16  class P2PStoreBlock(P2PInterface):
  17      def __init__(self):
  18          super().__init__()
  19          self.blocks = defaultdict(int)
  20  
  21      def on_block(self, message):
  22          self.blocks[message.block.hash_int] += 1
  23  
  24  
  25  class GetdataTest(BitcoinTestFramework):
  26      def set_test_params(self):
  27          self.num_nodes = 1
  28  
  29      def run_test(self):
  30          p2p_block_store = self.nodes[0].add_p2p_connection(P2PStoreBlock())
  31  
  32          self.log.info("test that an invalid GETDATA doesn't prevent processing of future messages")
  33  
  34          # Send invalid message and verify that node responds to later ping
  35          invalid_getdata = msg_getdata()
  36          invalid_getdata.inv.append(CInv(t=0, h=0))  # INV type 0 is invalid.
  37          p2p_block_store.send_and_ping(invalid_getdata)
  38  
  39          # Check getdata still works by fetching tip block
  40          best_block = int(self.nodes[0].getbestblockhash(), 16)
  41          good_getdata = msg_getdata()
  42          good_getdata.inv.append(CInv(t=2, h=best_block))
  43          p2p_block_store.send_and_ping(good_getdata)
  44          p2p_block_store.wait_until(lambda: p2p_block_store.blocks[best_block] == 1)
  45  
  46  
  47  if __name__ == '__main__':
  48      GetdataTest(__file__).main()
  49