/ test / functional / feature_dersig.py
feature_dersig.py
  1  #!/usr/bin/env python3
  2  # Copyright (c) 2015-2022 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 BIP66 (DER SIG).
  6  
  7  Test the DERSIG soft-fork activation on regtest.
  8  """
  9  
 10  from test_framework.blocktools import (
 11      create_block,
 12      create_coinbase,
 13  )
 14  from test_framework.messages import msg_block
 15  from test_framework.p2p import P2PInterface
 16  from test_framework.script import CScript
 17  from test_framework.test_framework import BitcoinTestFramework
 18  from test_framework.util import (
 19      assert_equal,
 20  )
 21  from test_framework.wallet import (
 22      MiniWallet,
 23      MiniWalletMode,
 24  )
 25  
 26  
 27  # A canonical signature consists of:
 28  # <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
 29  def unDERify(tx):
 30      """
 31      Make the signature in vin 0 of a tx non-DER-compliant,
 32      by adding padding after the S-value.
 33      """
 34      scriptSig = CScript(tx.vin[0].scriptSig)
 35      newscript = []
 36      for i in scriptSig:
 37          if (len(newscript) == 0):
 38              newscript.append(i[0:-1] + b'\0' + i[-1:])
 39          else:
 40              newscript.append(i)
 41      tx.vin[0].scriptSig = CScript(newscript)
 42  
 43  
 44  DERSIG_HEIGHT = 102
 45  
 46  
 47  class BIP66Test(BitcoinTestFramework):
 48      def set_test_params(self):
 49          self.num_nodes = 1
 50          # whitelist peers to speed up tx relay / mempool sync
 51          self.noban_tx_relay = True
 52          self.extra_args = [[
 53              f'-testactivationheight=dersig@{DERSIG_HEIGHT}',
 54              '-par=1',  # Use only one script thread to get the exact log msg for testing
 55          ]]
 56          self.setup_clean_chain = True
 57          self.rpc_timeout = 240
 58  
 59      def create_tx(self, input_txid):
 60          utxo_to_spend = self.miniwallet.get_utxo(txid=input_txid, mark_as_spent=False)
 61          return self.miniwallet.create_self_transfer(utxo_to_spend=utxo_to_spend)['tx']
 62  
 63      def test_dersig_info(self, *, is_active):
 64          assert_equal(self.nodes[0].getdeploymentinfo()['deployments']['bip66'],
 65              {
 66                  "active": is_active,
 67                  "height": DERSIG_HEIGHT,
 68                  "type": "buried",
 69              },
 70          )
 71  
 72      def run_test(self):
 73          peer = self.nodes[0].add_p2p_connection(P2PInterface())
 74          self.miniwallet = MiniWallet(self.nodes[0], mode=MiniWalletMode.RAW_P2PK)
 75  
 76          self.test_dersig_info(is_active=False)
 77  
 78          self.log.info("Mining %d blocks", DERSIG_HEIGHT - 2)
 79          self.coinbase_txids = [self.nodes[0].getblock(b)['tx'][0] for b in self.generate(self.miniwallet, DERSIG_HEIGHT - 2)]
 80  
 81          self.log.info("Test that a transaction with non-DER signature can still appear in a block")
 82  
 83          spendtx = self.create_tx(self.coinbase_txids[0])
 84          unDERify(spendtx)
 85          spendtx.rehash()
 86  
 87          tip = self.nodes[0].getbestblockhash()
 88          block_time = self.nodes[0].getblockheader(tip)['mediantime'] + 1
 89          block = create_block(int(tip, 16), create_coinbase(DERSIG_HEIGHT - 1), block_time, txlist=[spendtx])
 90          block.solve()
 91  
 92          assert_equal(self.nodes[0].getblockcount(), DERSIG_HEIGHT - 2)
 93          self.test_dersig_info(is_active=False)  # Not active as of current tip and next block does not need to obey rules
 94          peer.send_and_ping(msg_block(block))
 95          assert_equal(self.nodes[0].getblockcount(), DERSIG_HEIGHT - 1)
 96          self.test_dersig_info(is_active=True)  # Not active as of current tip, but next block must obey rules
 97          assert_equal(self.nodes[0].getbestblockhash(), block.hash)
 98  
 99          self.log.info("Test that blocks must now be at least version 3")
100          tip = block.sha256
101          block_time += 1
102          block = create_block(tip, create_coinbase(DERSIG_HEIGHT), block_time, version=2)
103          block.solve()
104  
105          with self.nodes[0].assert_debug_log(expected_msgs=[f'{block.hash}, bad-version(0x00000002)']):
106              peer.send_and_ping(msg_block(block))
107              assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)
108              peer.sync_with_ping()
109  
110          self.log.info("Test that transactions with non-DER signatures cannot appear in a block")
111          block.nVersion = 4
112  
113          spendtx = self.create_tx(self.coinbase_txids[1])
114          unDERify(spendtx)
115          spendtx.rehash()
116  
117          # First we show that this tx is valid except for DERSIG by getting it
118          # rejected from the mempool for exactly that reason.
119          assert_equal(
120              [{
121                  'txid': spendtx.hash,
122                  'wtxid': spendtx.getwtxid(),
123                  'allowed': False,
124                  'reject-reason': 'mandatory-script-verify-flag-failed (Non-canonical DER signature)',
125              }],
126              self.nodes[0].testmempoolaccept(rawtxs=[spendtx.serialize().hex()], maxfeerate=0),
127          )
128  
129          # Now we verify that a block with this transaction is also invalid.
130          block.vtx.append(spendtx)
131          block.hashMerkleRoot = block.calc_merkle_root()
132          block.solve()
133  
134          with self.nodes[0].assert_debug_log(expected_msgs=[f'CheckInputScripts on {block.vtx[-1].hash} failed with mandatory-script-verify-flag-failed (Non-canonical DER signature)']):
135              peer.send_and_ping(msg_block(block))
136              assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)
137              peer.sync_with_ping()
138  
139          self.log.info("Test that a block with a DERSIG-compliant transaction is accepted")
140          block.vtx[1] = self.create_tx(self.coinbase_txids[1])
141          block.hashMerkleRoot = block.calc_merkle_root()
142          block.solve()
143  
144          self.test_dersig_info(is_active=True)  # Not active as of current tip, but next block must obey rules
145          peer.send_and_ping(msg_block(block))
146          self.test_dersig_info(is_active=True)  # Active as of current tip
147          assert_equal(int(self.nodes[0].getbestblockhash(), 16), block.sha256)
148  
149  
150  if __name__ == '__main__':
151      BIP66Test().main()