rpc_createmultisig.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 2015-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 multisig RPCs"""
   6  import decimal
   7  import itertools
   8  import json
   9  import os
  10  
  11  from test_framework.address import address_to_scriptpubkey
  12  from test_framework.descriptors import descsum_create
  13  from test_framework.key import ECPubKey
  14  from test_framework.messages import COIN
  15  from test_framework.script_util import keys_to_multisig_script
  16  from test_framework.test_framework import BitcoinTestFramework
  17  from test_framework.util import (
  18      assert_raises_rpc_error,
  19      assert_equal,
  20  )
  21  from test_framework.wallet_util import generate_keypair
  22  from test_framework.wallet import (
  23      MiniWallet,
  24      getnewdestination,
  25  )
  26  
  27  class RpcCreateMultiSigTest(BitcoinTestFramework):
  28      def set_test_params(self):
  29          self.setup_clean_chain = True
  30          self.num_nodes = 3
  31  
  32      def create_keys(self, num_keys):
  33          self.pub = []
  34          self.priv = []
  35          for _ in range(num_keys):
  36              privkey, pubkey = generate_keypair(wif=True)
  37              self.pub.append(pubkey.hex())
  38              self.priv.append(privkey)
  39  
  40      def run_test(self):
  41          node0, node1, _node2 = self.nodes
  42          self.wallet = MiniWallet(test_node=node0)
  43  
  44          self.log.info('Generating blocks ...')
  45          self.generate(self.wallet, 149)
  46  
  47          self.create_keys(21)  # max number of allowed keys + 1
  48          m_of_n = [(2, 3), (3, 3), (2, 5), (3, 5), (10, 15), (15, 15)]
  49          for (sigs, keys) in m_of_n:
  50              for output_type in ["bech32", "p2sh-segwit", "legacy"]:
  51                  self.do_multisig(keys, sigs, output_type)
  52  
  53          self.test_combinerawtransaction_preconditions()
  54          self.test_multisig_script_limit()
  55          self.test_mixing_uncompressed_and_compressed_keys(node0)
  56          self.test_sortedmulti_descriptors_bip67()
  57  
  58          # Check that bech32m is currently not allowed
  59          assert_raises_rpc_error(-5, "createmultisig cannot create bech32m multisig addresses", self.nodes[0].createmultisig, 2, self.pub, "bech32m")
  60  
  61          self.log.info('Check correct encoding of multisig script for all n (1..20)')
  62          for nkeys in range(1, 20+1):
  63              keys = [self.pub[0]]*nkeys
  64              expected_ms_script = keys_to_multisig_script(keys, k=nkeys)  # simply use n-of-n
  65              # note that the 'legacy' address type fails for n values larger than 15
  66              # due to exceeding the P2SH size limit (520 bytes), so we use 'bech32' instead
  67              # (for the purpose of this encoding test, we don't care about the resulting address)
  68              res = self.nodes[0].createmultisig(nrequired=nkeys, keys=keys, address_type='bech32')
  69              assert_equal(res['redeemScript'], expected_ms_script.hex())
  70  
  71      def test_multisig_script_limit(self):
  72          node1 = self.nodes[1]
  73          pubkeys = self.pub[0:20]
  74  
  75          self.log.info('Test legacy redeem script max size limit')
  76          assert_raises_rpc_error(-8, "redeemScript exceeds size limit: 684 > 520", node1.createmultisig, 16, pubkeys, 'legacy')
  77  
  78          self.log.info('Test valid 16-20 multisig p2sh-legacy and bech32 (no wallet)')
  79          self.do_multisig(nkeys=20, nsigs=16, output_type="p2sh-segwit")
  80          self.do_multisig(nkeys=20, nsigs=16, output_type="bech32")
  81  
  82          self.log.info('Test invalid 16-21 multisig p2sh-legacy and bech32 (no wallet)')
  83          assert_raises_rpc_error(-8, "Number of keys involved in the multisignature address creation > 20", node1.createmultisig, 16, self.pub, 'p2sh-segwit')
  84          assert_raises_rpc_error(-8, "Number of keys involved in the multisignature address creation > 20", node1.createmultisig, 16, self.pub, 'bech32')
  85  
  86      def test_combinerawtransaction_preconditions(self):
  87          self.log.info('Test combinerawtransaction preconditions')
  88          # Note that preconditions don't depend on the output type, choosing bech32
  89          self.do_multisig(nkeys=3, nsigs=2, output_type="bech32", assert_mergeability=True)
  90  
  91      def do_multisig(self, nkeys, nsigs, output_type, assert_mergeability=False):
  92          node0, _node1, node2 = self.nodes
  93          pub_keys = self.pub[0: nkeys]
  94          priv_keys = self.priv[0: nkeys]
  95  
  96          # Construct the expected descriptor
  97          desc = 'multi({},{})'.format(nsigs, ','.join(pub_keys))
  98          if output_type == 'legacy':
  99              desc = 'sh({})'.format(desc)
 100          elif output_type == 'p2sh-segwit':
 101              desc = 'sh(wsh({}))'.format(desc)
 102          elif output_type == 'bech32':
 103              desc = 'wsh({})'.format(desc)
 104          desc = descsum_create(desc)
 105  
 106          msig = node2.createmultisig(nsigs, pub_keys, output_type)
 107          assert 'warnings' not in msig
 108          madd = msig["address"]
 109          mredeem = msig["redeemScript"]
 110          assert_equal(desc, msig['descriptor'])
 111          if output_type == 'bech32':
 112              assert_equal(madd[0:4], "bcrt")  # actually a bech32 address
 113  
 114          spk = address_to_scriptpubkey(madd)
 115          value = decimal.Decimal("0.00004000")
 116          tx = self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=spk, amount=int(value * COIN))
 117          prevtxs = [{"txid": tx["txid"], "vout": tx["sent_vout"], "scriptPubKey": spk.hex(), "redeemScript": mredeem, "amount": value}]
 118  
 119          self.generate(node0, 1)
 120  
 121          outval = value - decimal.Decimal("0.00002000")  # deduce fee (must be higher than the min relay fee)
 122          out_addr = getnewdestination('bech32')[2]
 123          rawtx = node2.createrawtransaction([{"txid": tx["txid"], "vout": tx["sent_vout"]}], [{out_addr: outval}])
 124  
 125          prevtx_err = dict(prevtxs[0])
 126          del prevtx_err["redeemScript"]
 127  
 128          assert_raises_rpc_error(-8, "Missing redeemScript/witnessScript", node2.signrawtransactionwithkey, rawtx, priv_keys[0:nsigs-1], [prevtx_err])
 129  
 130          # if witnessScript specified, all ok
 131          prevtx_err["witnessScript"] = prevtxs[0]["redeemScript"]
 132          node2.signrawtransactionwithkey(rawtx, priv_keys[0:nsigs-1], [prevtx_err])
 133  
 134          # both specified, also ok
 135          prevtx_err["redeemScript"] = prevtxs[0]["redeemScript"]
 136          node2.signrawtransactionwithkey(rawtx, priv_keys[0:nsigs-1], [prevtx_err])
 137  
 138          # redeemScript mismatch to witnessScript
 139          prevtx_err["redeemScript"] = "6a" # OP_RETURN
 140          assert_raises_rpc_error(-8, "redeemScript does not correspond to witnessScript", node2.signrawtransactionwithkey, rawtx, priv_keys[0:nsigs-1], [prevtx_err])
 141  
 142          # redeemScript does not match scriptPubKey
 143          del prevtx_err["witnessScript"]
 144          assert_raises_rpc_error(-8, "redeemScript/witnessScript does not match scriptPubKey", node2.signrawtransactionwithkey, rawtx, priv_keys[0:nsigs-1], [prevtx_err])
 145  
 146          # witnessScript does not match scriptPubKey
 147          prevtx_err["witnessScript"] = prevtx_err["redeemScript"]
 148          del prevtx_err["redeemScript"]
 149          assert_raises_rpc_error(-8, "redeemScript/witnessScript does not match scriptPubKey", node2.signrawtransactionwithkey, rawtx, priv_keys[0:nsigs-1], [prevtx_err])
 150  
 151          rawtx2 = node2.signrawtransactionwithkey(rawtx, priv_keys[0:nsigs - 1], prevtxs)
 152          assert_equal(rawtx2["complete"], False)
 153          rawtx3 = node2.signrawtransactionwithkey(rawtx, [priv_keys[-1]], prevtxs)
 154          assert_equal(rawtx3["complete"], False)
 155  
 156          if assert_mergeability:
 157              # Test boundary conditions
 158              assert_raises_rpc_error(-22, "TX decode failed", node2.combinerawtransaction, [rawtx2['hex'], rawtx3['hex'] + "00"])
 159              assert_raises_rpc_error(-22, "Missing transactions. At least two transactions required.", node2.combinerawtransaction, [])
 160              assert_raises_rpc_error(-22, "Missing transactions. At least two transactions required.", node2.combinerawtransaction, [rawtx2['hex']])
 161  
 162              out_addr2 = getnewdestination('bech32')[2]
 163              unmergeable_transaction_args = [
 164                  ([[{"txid": tx["txid"], "vout": tx["sent_vout"]}], [{out_addr: outval * 2}]], {}), # similar transaction but with different amount to send
 165                  ([[{"txid": tx["txid"], "vout": tx["sent_vout"]}], [{out_addr: outval}]], {"version": 1}), # similar transaction but with different version
 166                  ([[{"txid": tx["txid"], "vout": tx["sent_vout"]}], [{out_addr: outval}]], {"locktime": 1}), # similar transaction but with different locktime
 167                  ([[{"txid": tx["txid"], "vout": tx["sent_vout"]}], [{out_addr2: outval}]], {}), # similar transaction but with different output address (scriptPubKey)
 168                  ([[{"txid": tx["txid"], "vout": tx["sent_vout"], "sequence": 1}], [{out_addr: outval}]], {}), # similar transaction but with different sequence number
 169                  ([[{"txid": tx["txid"], "vout": tx["sent_vout"] + 1}], [{out_addr: outval}]], {}) # similar transaction but with different input vout index
 170              ]
 171  
 172              for rpc_args, rpc_kwargs in unmergeable_transaction_args:
 173                  unrelated_tx = node2.createrawtransaction(*rpc_args, **rpc_kwargs)
 174                  assert_raises_rpc_error(-8, "Transaction number 2 not compatible with first transaction", node0.combinerawtransaction, [rawtx2['hex'], unrelated_tx])
 175  
 176              # Accept duplicate transactions in combinerawtransaction
 177              dupe_merged_tx = node2.combinerawtransaction([rawtx2['hex'], rawtx2['hex']])
 178              assert_equal(rawtx2['hex'], dupe_merged_tx)
 179  
 180          combined_rawtx = node2.combinerawtransaction([rawtx2["hex"], rawtx3["hex"]])
 181          tx = node0.sendrawtransaction(combined_rawtx, 0)
 182          blk = self.generate(node0, 1)[0]
 183          assert tx in node0.getblock(blk)["tx"]
 184  
 185          assert_raises_rpc_error(-25, "Input not found or already spent", node2.combinerawtransaction, [rawtx2['hex'], rawtx3['hex']])
 186  
 187          txinfo = node0.getrawtransaction(tx, True, blk)
 188          self.log.info("n/m=%d/%d %s size=%d vsize=%d weight=%d" % (nsigs, nkeys, output_type, txinfo["size"], txinfo["vsize"], txinfo["weight"]))
 189  
 190      def test_mixing_uncompressed_and_compressed_keys(self, node):
 191          self.log.info('Mixed compressed and uncompressed multisigs are not allowed')
 192          pk0, pk1, pk2 = [getnewdestination('bech32')[0][1].hex() for _ in range(3)]
 193  
 194          # decompress pk2
 195          pk_obj = ECPubKey()
 196          pk_obj.set(bytes.fromhex(pk2))
 197          pk_obj.compressed = False
 198          pk2 = pk_obj.get_bytes().hex()
 199  
 200          # Check all permutations of keys because order matters apparently
 201          for keys in itertools.permutations([pk0, pk1, pk2]):
 202              # Results should be the same as this legacy one
 203              legacy_addr = node.createmultisig(2, keys, 'legacy')['address']
 204  
 205              # Generate addresses with the segwit types. These should all make legacy addresses
 206              err_msg = ["Unable to make chosen address type, please ensure no uncompressed public keys are present."]
 207  
 208              for addr_type in ['bech32', 'p2sh-segwit']:
 209                  result = self.nodes[0].createmultisig(nrequired=2, keys=keys, address_type=addr_type)
 210                  assert_equal(legacy_addr, result['address'])
 211                  assert_equal(result['warnings'], err_msg)
 212  
 213      def test_sortedmulti_descriptors_bip67(self):
 214          self.log.info('Testing sortedmulti descriptors with BIP 67 test vectors')
 215          with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/rpc_bip67.json')) as f:
 216              vectors = json.load(f)
 217  
 218          for t in vectors:
 219              key_str = ','.join(t['keys'])
 220              desc = descsum_create('sh(sortedmulti(2,{}))'.format(key_str))
 221              assert_equal(self.nodes[0].deriveaddresses(desc)[0], t['address'])
 222              sorted_key_str = ','.join(t['sorted_keys'])
 223              sorted_key_desc = descsum_create('sh(multi(2,{}))'.format(sorted_key_str))
 224              assert_equal(self.nodes[0].deriveaddresses(sorted_key_desc)[0], t['address'])
 225  
 226  
 227  if __name__ == '__main__':
 228      RpcCreateMultiSigTest(__file__).main()
 229