PageRenderTime 118ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/test/functional/rpc_createmultisig.py

https://github.com/bitcoin/bitcoin
Python | 232 lines | 210 code | 13 blank | 9 comment | 8 complexity | 1682a7787c70c102cfccf36174b6411f MD5 | raw file
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2015-2021 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. from test_framework.blocktools import COINBASE_MATURITY
  11. from test_framework.authproxy import JSONRPCException
  12. from test_framework.descriptors import descsum_create, drop_origins
  13. from test_framework.key import ECPubKey, ECKey
  14. from test_framework.test_framework import BitcoinTestFramework
  15. from test_framework.util import (
  16. assert_raises_rpc_error,
  17. assert_equal,
  18. )
  19. from test_framework.wallet_util import bytes_to_wif
  20. class RpcCreateMultiSigTest(BitcoinTestFramework):
  21. def set_test_params(self):
  22. self.setup_clean_chain = True
  23. self.num_nodes = 3
  24. self.supports_cli = False
  25. def skip_test_if_missing_module(self):
  26. self.skip_if_no_wallet()
  27. def get_keys(self):
  28. self.pub = []
  29. self.priv = []
  30. node0, node1, node2 = self.nodes
  31. for _ in range(self.nkeys):
  32. k = ECKey()
  33. k.generate()
  34. self.pub.append(k.get_pubkey().get_bytes().hex())
  35. self.priv.append(bytes_to_wif(k.get_bytes(), k.is_compressed))
  36. self.final = node2.getnewaddress()
  37. def run_test(self):
  38. node0, node1, node2 = self.nodes
  39. self.check_addmultisigaddress_errors()
  40. self.log.info('Generating blocks ...')
  41. self.generate(node0, 149)
  42. self.moved = 0
  43. for self.nkeys in [3, 5]:
  44. for self.nsigs in [2, 3]:
  45. for self.output_type in ["bech32", "p2sh-segwit", "legacy"]:
  46. self.get_keys()
  47. self.do_multisig()
  48. self.checkbalances()
  49. # Test mixed compressed and uncompressed pubkeys
  50. self.log.info('Mixed compressed and uncompressed multisigs are not allowed')
  51. pk0 = node0.getaddressinfo(node0.getnewaddress())['pubkey']
  52. pk1 = node1.getaddressinfo(node1.getnewaddress())['pubkey']
  53. pk2 = node2.getaddressinfo(node2.getnewaddress())['pubkey']
  54. # decompress pk2
  55. pk_obj = ECPubKey()
  56. pk_obj.set(bytes.fromhex(pk2))
  57. pk_obj.compressed = False
  58. pk2 = pk_obj.get_bytes().hex()
  59. node0.createwallet(wallet_name='wmulti0', disable_private_keys=True)
  60. wmulti0 = node0.get_wallet_rpc('wmulti0')
  61. # Check all permutations of keys because order matters apparently
  62. for keys in itertools.permutations([pk0, pk1, pk2]):
  63. # Results should be the same as this legacy one
  64. legacy_addr = node0.createmultisig(2, keys, 'legacy')['address']
  65. result = wmulti0.addmultisigaddress(2, keys, '', 'legacy')
  66. assert_equal(legacy_addr, result['address'])
  67. assert 'warnings' not in result
  68. # Generate addresses with the segwit types. These should all make legacy addresses
  69. for addr_type in ['bech32', 'p2sh-segwit']:
  70. result = wmulti0.createmultisig(2, keys, addr_type)
  71. assert_equal(legacy_addr, result['address'])
  72. assert_equal(result['warnings'], ["Unable to make chosen address type, please ensure no uncompressed public keys are present."])
  73. result = wmulti0.addmultisigaddress(2, keys, '', addr_type)
  74. assert_equal(legacy_addr, result['address'])
  75. assert_equal(result['warnings'], ["Unable to make chosen address type, please ensure no uncompressed public keys are present."])
  76. self.log.info('Testing sortedmulti descriptors with BIP 67 test vectors')
  77. with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/rpc_bip67.json'), encoding='utf-8') as f:
  78. vectors = json.load(f)
  79. for t in vectors:
  80. key_str = ','.join(t['keys'])
  81. desc = descsum_create('sh(sortedmulti(2,{}))'.format(key_str))
  82. assert_equal(self.nodes[0].deriveaddresses(desc)[0], t['address'])
  83. sorted_key_str = ','.join(t['sorted_keys'])
  84. sorted_key_desc = descsum_create('sh(multi(2,{}))'.format(sorted_key_str))
  85. assert_equal(self.nodes[0].deriveaddresses(sorted_key_desc)[0], t['address'])
  86. # Check that bech32m is currently not allowed
  87. assert_raises_rpc_error(-5, "createmultisig cannot create bech32m multisig addresses", self.nodes[0].createmultisig, 2, self.pub, "bech32m")
  88. def check_addmultisigaddress_errors(self):
  89. if self.options.descriptors:
  90. return
  91. self.log.info('Check that addmultisigaddress fails when the private keys are missing')
  92. addresses = [self.nodes[1].getnewaddress(address_type='legacy') for _ in range(2)]
  93. assert_raises_rpc_error(-5, 'no full public key for address', lambda: self.nodes[0].addmultisigaddress(nrequired=1, keys=addresses))
  94. for a in addresses:
  95. # Importing all addresses should not change the result
  96. self.nodes[0].importaddress(a)
  97. assert_raises_rpc_error(-5, 'no full public key for address', lambda: self.nodes[0].addmultisigaddress(nrequired=1, keys=addresses))
  98. # Bech32m address type is disallowed for legacy wallets
  99. pubs = [self.nodes[1].getaddressinfo(addr)["pubkey"] for addr in addresses]
  100. assert_raises_rpc_error(-5, "Bech32m multisig addresses cannot be created with legacy wallets", self.nodes[0].addmultisigaddress, 2, pubs, "", "bech32m")
  101. def checkbalances(self):
  102. node0, node1, node2 = self.nodes
  103. self.generate(node0, COINBASE_MATURITY)
  104. bal0 = node0.getbalance()
  105. bal1 = node1.getbalance()
  106. bal2 = node2.getbalance()
  107. height = node0.getblockchaininfo()["blocks"]
  108. assert 150 < height < 350
  109. total = 149 * 50 + (height - 149 - 100) * 25
  110. assert bal1 == 0
  111. assert bal2 == self.moved
  112. assert bal0 + bal1 + bal2 == total
  113. def do_multisig(self):
  114. node0, node1, node2 = self.nodes
  115. if 'wmulti' not in node1.listwallets():
  116. try:
  117. node1.loadwallet('wmulti')
  118. except JSONRPCException as e:
  119. path = os.path.join(self.options.tmpdir, "node1", "regtest", "wallets", "wmulti")
  120. if e.error['code'] == -18 and "Wallet file verification failed. Failed to load database path '{}'. Path does not exist.".format(path) in e.error['message']:
  121. node1.createwallet(wallet_name='wmulti', disable_private_keys=True)
  122. else:
  123. raise
  124. wmulti = node1.get_wallet_rpc('wmulti')
  125. # Construct the expected descriptor
  126. desc = 'multi({},{})'.format(self.nsigs, ','.join(self.pub))
  127. if self.output_type == 'legacy':
  128. desc = 'sh({})'.format(desc)
  129. elif self.output_type == 'p2sh-segwit':
  130. desc = 'sh(wsh({}))'.format(desc)
  131. elif self.output_type == 'bech32':
  132. desc = 'wsh({})'.format(desc)
  133. desc = descsum_create(desc)
  134. msig = node2.createmultisig(self.nsigs, self.pub, self.output_type)
  135. madd = msig["address"]
  136. mredeem = msig["redeemScript"]
  137. assert_equal(desc, msig['descriptor'])
  138. if self.output_type == 'bech32':
  139. assert madd[0:4] == "bcrt" # actually a bech32 address
  140. # compare against addmultisigaddress
  141. msigw = wmulti.addmultisigaddress(self.nsigs, self.pub, None, self.output_type)
  142. maddw = msigw["address"]
  143. mredeemw = msigw["redeemScript"]
  144. assert_equal(desc, drop_origins(msigw['descriptor']))
  145. # addmultisigiaddress and createmultisig work the same
  146. assert maddw == madd
  147. assert mredeemw == mredeem
  148. txid = node0.sendtoaddress(madd, 40)
  149. tx = node0.getrawtransaction(txid, True)
  150. vout = [v["n"] for v in tx["vout"] if madd == v["scriptPubKey"]["address"]]
  151. assert len(vout) == 1
  152. vout = vout[0]
  153. scriptPubKey = tx["vout"][vout]["scriptPubKey"]["hex"]
  154. value = tx["vout"][vout]["value"]
  155. prevtxs = [{"txid": txid, "vout": vout, "scriptPubKey": scriptPubKey, "redeemScript": mredeem, "amount": value}]
  156. self.generate(node0, 1)
  157. outval = value - decimal.Decimal("0.00001000")
  158. rawtx = node2.createrawtransaction([{"txid": txid, "vout": vout}], [{self.final: outval}])
  159. prevtx_err = dict(prevtxs[0])
  160. del prevtx_err["redeemScript"]
  161. assert_raises_rpc_error(-8, "Missing redeemScript/witnessScript", node2.signrawtransactionwithkey, rawtx, self.priv[0:self.nsigs-1], [prevtx_err])
  162. # if witnessScript specified, all ok
  163. prevtx_err["witnessScript"] = prevtxs[0]["redeemScript"]
  164. node2.signrawtransactionwithkey(rawtx, self.priv[0:self.nsigs-1], [prevtx_err])
  165. # both specified, also ok
  166. prevtx_err["redeemScript"] = prevtxs[0]["redeemScript"]
  167. node2.signrawtransactionwithkey(rawtx, self.priv[0:self.nsigs-1], [prevtx_err])
  168. # redeemScript mismatch to witnessScript
  169. prevtx_err["redeemScript"] = "6a" # OP_RETURN
  170. assert_raises_rpc_error(-8, "redeemScript does not correspond to witnessScript", node2.signrawtransactionwithkey, rawtx, self.priv[0:self.nsigs-1], [prevtx_err])
  171. # redeemScript does not match scriptPubKey
  172. del prevtx_err["witnessScript"]
  173. assert_raises_rpc_error(-8, "redeemScript/witnessScript does not match scriptPubKey", node2.signrawtransactionwithkey, rawtx, self.priv[0:self.nsigs-1], [prevtx_err])
  174. # witnessScript does not match scriptPubKey
  175. prevtx_err["witnessScript"] = prevtx_err["redeemScript"]
  176. del prevtx_err["redeemScript"]
  177. assert_raises_rpc_error(-8, "redeemScript/witnessScript does not match scriptPubKey", node2.signrawtransactionwithkey, rawtx, self.priv[0:self.nsigs-1], [prevtx_err])
  178. rawtx2 = node2.signrawtransactionwithkey(rawtx, self.priv[0:self.nsigs - 1], prevtxs)
  179. rawtx3 = node2.signrawtransactionwithkey(rawtx2["hex"], [self.priv[-1]], prevtxs)
  180. self.moved += outval
  181. tx = node0.sendrawtransaction(rawtx3["hex"], 0)
  182. blk = self.generate(node0, 1)[0]
  183. assert tx in node0.getblock(blk)["tx"]
  184. txinfo = node0.getrawtransaction(tx, True, blk)
  185. self.log.info("n/m=%d/%d %s size=%d vsize=%d weight=%d" % (self.nsigs, self.nkeys, self.output_type, txinfo["size"], txinfo["vsize"], txinfo["weight"]))
  186. wmulti.unloadwallet()
  187. if __name__ == '__main__':
  188. RpcCreateMultiSigTest().main()