p2p_mutated_blocks.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 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  
   6  """
   7  Test that an attacker can't degrade compact block relay by sending unsolicited
   8  mutated blocks to clear in-flight blocktxn requests from other honest peers.
   9  """
  10  
  11  from test_framework.p2p import P2PInterface
  12  from test_framework.messages import (
  13      BlockTransactions,
  14      msg_cmpctblock,
  15      msg_block,
  16      msg_blocktxn,
  17      msg_headers,
  18      HeaderAndShortIDs,
  19      msg_sendcmpct,
  20  )
  21  from test_framework.test_framework import BitcoinTestFramework
  22  from test_framework.blocktools import (
  23      COINBASE_MATURITY,
  24      create_block,
  25      add_witness_commitment,
  26      NORMAL_GBT_REQUEST_PARAMS,
  27  )
  28  from test_framework.util import assert_equal
  29  from test_framework.wallet import MiniWallet
  30  import copy
  31  
  32  class MutatedBlocksTest(BitcoinTestFramework):
  33      def set_test_params(self):
  34          self.setup_clean_chain = True
  35          self.num_nodes = 1
  36          self.extra_args = [
  37              [
  38                  "-testactivationheight=segwit@1", # causes unconnected headers/blocks to not have segwit considered deployed
  39              ],
  40          ]
  41  
  42      def run_test(self):
  43          self.wallet = MiniWallet(self.nodes[0])
  44          self.generate(self.wallet, COINBASE_MATURITY)
  45  
  46          honest_relayer = self.nodes[0].add_outbound_p2p_connection(P2PInterface(), p2p_idx=0, connection_type="outbound-full-relay")
  47          honest_relayer.send_and_ping(msg_sendcmpct())
  48          attacker = self.nodes[0].add_p2p_connection(P2PInterface())
  49  
  50          # Create new block with two transactions (coinbase + 1 self-transfer).
  51          # The self-transfer transaction is needed to trigger a compact block
  52          # `getblocktxn` roundtrip.
  53          tx = self.wallet.create_self_transfer()["tx"]
  54          block = create_block(tmpl=self.nodes[0].getblocktemplate(NORMAL_GBT_REQUEST_PARAMS), txlist=[tx])
  55          add_witness_commitment(block)
  56          block.solve()
  57  
  58          # Create mutated version of the block by changing the transaction
  59          # version on the self-transfer.
  60          mutated_block = copy.deepcopy(block)
  61          mutated_block.vtx[1].version = 4
  62  
  63          # Send block header through the honest relayer
  64          honest_relayer.send_without_ping(msg_headers([block]))
  65          honest_relayer.wait_for_getdata([block.hash_int], timeout=30)
  66  
  67          # Announce the new block via a compact block through the honest relayer
  68          cmpctblock = HeaderAndShortIDs()
  69          cmpctblock.initialize_from_block(block, use_witness=True)
  70          honest_relayer.send_without_ping(msg_cmpctblock(cmpctblock.to_p2p()))
  71  
  72          # Wait for a `getblocktxn` that attempts to fetch the self-transfer
  73          def self_transfer_requested():
  74              if not honest_relayer.last_message.get('getblocktxn'):
  75                  return False
  76  
  77              get_block_txn = honest_relayer.last_message['getblocktxn']
  78              return get_block_txn.block_txn_request.blockhash == block.hash_int and \
  79                     get_block_txn.block_txn_request.indexes == [1]
  80          honest_relayer.wait_until(self_transfer_requested, timeout=5)
  81  
  82          # Block at height 101 should be the only one in flight from peer 0
  83          peer_info_prior_to_attack = self.nodes[0].getpeerinfo()
  84          assert_equal(peer_info_prior_to_attack[0]['id'], 0)
  85          assert_equal([101], peer_info_prior_to_attack[0]["inflight"])
  86  
  87          # Attempt to clear the honest relayer's download request by sending the
  88          # mutated block (as the attacker).
  89          with self.nodes[0].assert_debug_log(expected_msgs=["Block mutated: bad-txnmrklroot, hashMerkleRoot mismatch"]):
  90              attacker.send_without_ping(msg_block(mutated_block))
  91              # Attacker should get disconnected for sending a mutated block
  92              attacker.wait_for_disconnect(timeout=5)
  93  
  94          # Block at height 101 should *still* be the only block in-flight from
  95          # peer 0
  96          peer_info_after_attack = self.nodes[0].getpeerinfo()
  97          assert_equal(peer_info_after_attack[0]['id'], 0)
  98          assert_equal([101], peer_info_after_attack[0]["inflight"])
  99  
 100          # The honest relayer should be able to complete relaying the block by
 101          # sending the blocktxn that was requested.
 102          block_txn = msg_blocktxn()
 103          block_txn.block_transactions = BlockTransactions(blockhash=block.hash_int, transactions=[tx])
 104          honest_relayer.send_and_ping(block_txn)
 105          assert_equal(self.nodes[0].getbestblockhash(), block.hash_hex)
 106  
 107          # Check that unexpected-witness mutation check doesn't trigger on a header that doesn't connect to anything
 108          assert_equal(len(self.nodes[0].getpeerinfo()), 1)
 109          attacker = self.nodes[0].add_p2p_connection(P2PInterface())
 110          block_missing_prev = copy.deepcopy(block)
 111          block_missing_prev.hashPrevBlock = 123
 112          block_missing_prev.solve()
 113  
 114          # Check that non-connecting block causes disconnect
 115          assert_equal(len(self.nodes[0].getpeerinfo()), 2)
 116          with self.nodes[0].assert_debug_log(expected_msgs=["AcceptBlock FAILED (prev-blk-not-found)"]):
 117              attacker.send_without_ping(msg_block(block_missing_prev))
 118              attacker.wait_for_disconnect(timeout=5)
 119  
 120  
 121  if __name__ == '__main__':
 122      MutatedBlocksTest(__file__).main()
 123