feature_nulldummy.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 2016-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 NULLDUMMY softfork.
   6  
   7  Connect to a single node.
   8  Generate 2 blocks (save the coinbases for later).
   9  Generate COINBASE_MATURITY (CB) more blocks to ensure the coinbases are mature.
  10  [Policy/Consensus] Check that NULLDUMMY compliant transactions are accepted in block CB + 3.
  11  [Policy] Check that non-NULLDUMMY transactions are rejected before activation.
  12  [Consensus] Check that the new NULLDUMMY rules are not enforced on block CB + 4.
  13  [Policy/Consensus] Check that the new NULLDUMMY rules are enforced on block CB + 5.
  14  """
  15  import time
  16  
  17  from test_framework.address import address_to_scriptpubkey
  18  from test_framework.blocktools import (
  19      COINBASE_MATURITY,
  20      NORMAL_GBT_REQUEST_PARAMS,
  21      add_witness_commitment,
  22      create_block,
  23  )
  24  from test_framework.messages import (
  25      CTransaction,
  26      tx_from_hex,
  27  )
  28  from test_framework.script import (
  29      OP_0,
  30      OP_TRUE,
  31  )
  32  from test_framework.test_framework import BitcoinTestFramework
  33  from test_framework.util import (
  34      assert_equal,
  35      assert_raises_rpc_error,
  36  )
  37  from test_framework.wallet import getnewdestination
  38  from test_framework.wallet_util import generate_keypair
  39  
  40  NULLDUMMY_TX_ERROR = "mempool-script-verify-flag-failed (Dummy CHECKMULTISIG argument must be zero)"
  41  NULLDUMMY_BLK_ERROR = "block-script-verify-flag-failed (Dummy CHECKMULTISIG argument must be zero)"
  42  
  43  def invalidate_nulldummy_tx(tx):
  44      """Transform a NULLDUMMY compliant tx (i.e. scriptSig starts with OP_0)
  45      to be non-NULLDUMMY compliant by replacing the dummy with OP_TRUE"""
  46      assert_equal(tx.vin[0].scriptSig[0], OP_0)
  47      tx.vin[0].scriptSig = bytes([OP_TRUE]) + tx.vin[0].scriptSig[1:]
  48  
  49  
  50  class NULLDUMMYTest(BitcoinTestFramework):
  51      def set_test_params(self):
  52          self.num_nodes = 1
  53          self.setup_clean_chain = True
  54          # This script tests NULLDUMMY activation, which is part of the 'segwit' deployment, so we go through
  55          # normal segwit activation here (and don't use the default always-on behaviour).
  56          self.extra_args = [[
  57              f'-testactivationheight=segwit@{COINBASE_MATURITY + 5}',
  58              '-addresstype=legacy',
  59          ]]
  60  
  61      def create_transaction(self, *, txid, input_details=None, addr, amount, privkey):
  62          input = {"txid": txid, "vout": 0}
  63          output = {addr: amount}
  64          rawtx = self.nodes[0].createrawtransaction([input], output)
  65          # Details only needed for scripthash or witness spends
  66          input = None if not input_details else [{**input, **input_details}]
  67          signedtx = self.nodes[0].signrawtransactionwithkey(rawtx, [privkey], input)
  68          return tx_from_hex(signedtx["hex"])
  69  
  70      def run_test(self):
  71          self.privkey, self.pubkey = generate_keypair(wif=True)
  72          cms = self.nodes[0].createmultisig(1, [self.pubkey.hex()])
  73          wms = self.nodes[0].createmultisig(1, [self.pubkey.hex()], 'p2sh-segwit')
  74          self.ms_address = cms["address"]
  75          ms_unlock_details = {"scriptPubKey": address_to_scriptpubkey(self.ms_address).hex(),
  76                               "redeemScript": cms["redeemScript"]}
  77          self.wit_ms_address = wms['address']
  78  
  79          self.coinbase_blocks = self.generate(self.nodes[0], 2)  # block height = 2
  80          coinbase_txid = []
  81          for i in self.coinbase_blocks:
  82              coinbase_txid.append(self.nodes[0].getblock(i)['tx'][0])
  83          self.generate(self.nodes[0], COINBASE_MATURITY)  # block height = COINBASE_MATURITY + 2
  84          self.lastblockhash = self.nodes[0].getbestblockhash()
  85          self.lastblockheight = COINBASE_MATURITY + 2
  86          self.lastblocktime = int(time.time()) + self.lastblockheight
  87  
  88          self.log.info(f"Test 1: NULLDUMMY compliant base transactions should be accepted to mempool and mined before activation [{COINBASE_MATURITY + 3}]")
  89          test1txs = [self.create_transaction(txid=coinbase_txid[0], addr=self.ms_address, amount=49,
  90                                              privkey=self.nodes[0].get_deterministic_priv_key().key)]
  91          txid1 = self.nodes[0].sendrawtransaction(test1txs[0].serialize_with_witness().hex(), 0)
  92          test1txs.append(self.create_transaction(txid=txid1, input_details=ms_unlock_details,
  93                                                  addr=self.ms_address, amount=48,
  94                                                  privkey=self.privkey))
  95          txid2 = self.nodes[0].sendrawtransaction(test1txs[1].serialize_with_witness().hex(), 0)
  96          test1txs.append(self.create_transaction(txid=coinbase_txid[1],
  97                                                  addr=self.wit_ms_address, amount=49,
  98                                                  privkey=self.nodes[0].get_deterministic_priv_key().key))
  99          txid3 = self.nodes[0].sendrawtransaction(test1txs[2].serialize_with_witness().hex(), 0)
 100          self.block_submit(self.nodes[0], test1txs, accept=True)
 101  
 102          self.log.info("Test 2: Non-NULLDUMMY base multisig transaction should not be accepted to mempool before activation")
 103          test2tx = self.create_transaction(txid=txid2, input_details=ms_unlock_details,
 104                                            addr=self.ms_address, amount=47,
 105                                            privkey=self.privkey)
 106          invalidate_nulldummy_tx(test2tx)
 107          assert_raises_rpc_error(-26, NULLDUMMY_TX_ERROR, self.nodes[0].sendrawtransaction, test2tx.serialize_with_witness().hex(), 0)
 108  
 109          self.log.info(f"Test 3: Non-NULLDUMMY base transactions should be accepted in a block before activation [{COINBASE_MATURITY + 4}]")
 110          self.block_submit(self.nodes[0], [test2tx], accept=True)
 111  
 112          self.log.info("Test 4: Non-NULLDUMMY base multisig transaction is invalid after activation")
 113          test4tx = self.create_transaction(txid=test2tx.txid_hex, input_details=ms_unlock_details,
 114                                            addr=getnewdestination()[2], amount=46,
 115                                            privkey=self.privkey)
 116          test6txs = [CTransaction(test4tx)]
 117          invalidate_nulldummy_tx(test4tx)
 118          assert_raises_rpc_error(-26, NULLDUMMY_TX_ERROR, self.nodes[0].sendrawtransaction, test4tx.serialize_with_witness().hex(), 0)
 119          self.block_submit(self.nodes[0], [test4tx], accept=False)
 120  
 121          self.log.info("Test 5: Non-NULLDUMMY P2WSH multisig transaction invalid after activation")
 122          test5tx = self.create_transaction(txid=txid3, input_details={"scriptPubKey": test1txs[2].vout[0].scriptPubKey.hex(),
 123                                            "amount": 49, "witnessScript": wms["redeemScript"]},
 124                                            addr=getnewdestination(address_type='p2sh-segwit')[2], amount=48,
 125                                            privkey=self.privkey)
 126          test6txs.append(CTransaction(test5tx))
 127          test5tx.wit.vtxinwit[0].scriptWitness.stack[0] = b'\x01'
 128          assert_raises_rpc_error(-26, NULLDUMMY_TX_ERROR, self.nodes[0].sendrawtransaction, test5tx.serialize_with_witness().hex(), 0)
 129          self.block_submit(self.nodes[0], [test5tx], with_witness=True, accept=False)
 130  
 131          self.log.info(f"Test 6: NULLDUMMY compliant base/witness transactions should be accepted to mempool and in block after activation [{COINBASE_MATURITY + 5}]")
 132          for i in test6txs:
 133              self.nodes[0].sendrawtransaction(i.serialize_with_witness().hex(), 0)
 134          self.block_submit(self.nodes[0], test6txs, with_witness=True, accept=True)
 135  
 136      def block_submit(self, node, txs, *, with_witness=False, accept):
 137          tmpl = node.getblocktemplate(NORMAL_GBT_REQUEST_PARAMS)
 138          assert_equal(tmpl['previousblockhash'], self.lastblockhash)
 139          assert_equal(tmpl['height'], self.lastblockheight + 1)
 140          block = create_block(tmpl=tmpl, ntime=self.lastblocktime + 1, txlist=txs)
 141          if with_witness:
 142              add_witness_commitment(block)
 143          block.solve()
 144          assert_equal(None if accept else NULLDUMMY_BLK_ERROR, node.submitblock(block.serialize().hex()))
 145          if accept:
 146              assert_equal(node.getbestblockhash(), block.hash_hex)
 147              self.lastblockhash = block.hash_hex
 148              self.lastblocktime += 1
 149              self.lastblockheight += 1
 150          else:
 151              assert_equal(node.getbestblockhash(), self.lastblockhash)
 152  
 153  
 154  if __name__ == '__main__':
 155      NULLDUMMYTest(__file__).main()
 156