p2p_mutated_blocks.py raw

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