Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1#!/usr/bin/env python32# Copyright (c) 2015-present The Bitcoin Core developers3# Distributed under the MIT software license, see the accompanying4# file COPYING or http://www.opensource.org/licenses/mit-license.php.5"""Test multisig RPCs"""6import decimal7import itertools8import json9import os11from test_framework.address import address_to_scriptpubkey12from test_framework.descriptors import descsum_create13from test_framework.key import ECPubKey14from test_framework.messages import COIN15from test_framework.script_util import keys_to_multisig_script16from test_framework.test_framework import BitcoinTestFramework17from test_framework.util import (18assert_raises_rpc_error,19assert_equal,20)21from test_framework.wallet_util import generate_keypair22from test_framework.wallet import (23MiniWallet,24getnewdestination,25)27class RpcCreateMultiSigTest(BitcoinTestFramework):28def set_test_params(self):29self.setup_clean_chain = True30self.num_nodes = 332def create_keys(self, num_keys):33self.pub = []34self.priv = []35for _ in range(num_keys):36privkey, pubkey = generate_keypair(wif=True)37self.pub.append(pubkey.hex())38self.priv.append(privkey)40def run_test(self):41node0, node1, _node2 = self.nodes42self.wallet = MiniWallet(test_node=node0)44self.log.info('Generating blocks ...')45self.generate(self.wallet, 149)47self.create_keys(21) # max number of allowed keys + 148m_of_n = [(2, 3), (3, 3), (2, 5), (3, 5), (10, 15), (15, 15)]49for (sigs, keys) in m_of_n:50for output_type in ["bech32", "p2sh-segwit", "legacy"]:51self.do_multisig(keys, sigs, output_type)53self.test_combinerawtransaction_preconditions()54self.test_multisig_script_limit()55self.test_mixing_uncompressed_and_compressed_keys(node0)56self.test_sortedmulti_descriptors_bip67()58# Check that bech32m is currently not allowed59assert_raises_rpc_error(-5, "createmultisig cannot create bech32m multisig addresses", self.nodes[0].createmultisig, 2, self.pub, "bech32m")61self.log.info('Check correct encoding of multisig script for all n (1..20)')62for nkeys in range(1, 20+1):63keys = [self.pub[0]]*nkeys64expected_ms_script = keys_to_multisig_script(keys, k=nkeys) # simply use n-of-n65# note that the 'legacy' address type fails for n values larger than 1566# due to exceeding the P2SH size limit (520 bytes), so we use 'bech32' instead67# (for the purpose of this encoding test, we don't care about the resulting address)68res = self.nodes[0].createmultisig(nrequired=nkeys, keys=keys, address_type='bech32')69assert_equal(res['redeemScript'], expected_ms_script.hex())71def test_multisig_script_limit(self):72node1 = self.nodes[1]73pubkeys = self.pub[0:20]75self.log.info('Test legacy redeem script max size limit')76assert_raises_rpc_error(-8, "redeemScript exceeds size limit: 684 > 520", node1.createmultisig, 16, pubkeys, 'legacy')78self.log.info('Test valid 16-20 multisig p2sh-legacy and bech32 (no wallet)')79self.do_multisig(nkeys=20, nsigs=16, output_type="p2sh-segwit")80self.do_multisig(nkeys=20, nsigs=16, output_type="bech32")82self.log.info('Test invalid 16-21 multisig p2sh-legacy and bech32 (no wallet)')83assert_raises_rpc_error(-8, "Number of keys involved in the multisignature address creation > 20", node1.createmultisig, 16, self.pub, 'p2sh-segwit')84assert_raises_rpc_error(-8, "Number of keys involved in the multisignature address creation > 20", node1.createmultisig, 16, self.pub, 'bech32')86def test_combinerawtransaction_preconditions(self):87self.log.info('Test combinerawtransaction preconditions')88# Note that preconditions don't depend on the output type, choosing bech3289self.do_multisig(nkeys=3, nsigs=2, output_type="bech32", assert_mergeability=True)91def do_multisig(self, nkeys, nsigs, output_type, assert_mergeability=False):92node0, _node1, node2 = self.nodes93pub_keys = self.pub[0: nkeys]94priv_keys = self.priv[0: nkeys]96# Construct the expected descriptor97desc = 'multi({},{})'.format(nsigs, ','.join(pub_keys))98if output_type == 'legacy':99desc = 'sh({})'.format(desc)100elif output_type == 'p2sh-segwit':101desc = 'sh(wsh({}))'.format(desc)102elif output_type == 'bech32':103desc = 'wsh({})'.format(desc)104desc = descsum_create(desc)106msig = node2.createmultisig(nsigs, pub_keys, output_type)107assert 'warnings' not in msig108madd = msig["address"]109mredeem = msig["redeemScript"]110assert_equal(desc, msig['descriptor'])111if output_type == 'bech32':112assert_equal(madd[0:4], "bcrt") # actually a bech32 address114spk = address_to_scriptpubkey(madd)115value = decimal.Decimal("0.00004000")116tx = self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=spk, amount=int(value * COIN))117prevtxs = [{"txid": tx["txid"], "vout": tx["sent_vout"], "scriptPubKey": spk.hex(), "redeemScript": mredeem, "amount": value}]119self.generate(node0, 1)121outval = value - decimal.Decimal("0.00002000") # deduce fee (must be higher than the min relay fee)122out_addr = getnewdestination('bech32')[2]123rawtx = node2.createrawtransaction([{"txid": tx["txid"], "vout": tx["sent_vout"]}], [{out_addr: outval}])125prevtx_err = dict(prevtxs[0])126del prevtx_err["redeemScript"]128assert_raises_rpc_error(-8, "Missing redeemScript/witnessScript", node2.signrawtransactionwithkey, rawtx, priv_keys[0:nsigs-1], [prevtx_err])130# if witnessScript specified, all ok131prevtx_err["witnessScript"] = prevtxs[0]["redeemScript"]132node2.signrawtransactionwithkey(rawtx, priv_keys[0:nsigs-1], [prevtx_err])134# both specified, also ok135prevtx_err["redeemScript"] = prevtxs[0]["redeemScript"]136node2.signrawtransactionwithkey(rawtx, priv_keys[0:nsigs-1], [prevtx_err])138# redeemScript mismatch to witnessScript139prevtx_err["redeemScript"] = "6a" # OP_RETURN140assert_raises_rpc_error(-8, "redeemScript does not correspond to witnessScript", node2.signrawtransactionwithkey, rawtx, priv_keys[0:nsigs-1], [prevtx_err])142# redeemScript does not match scriptPubKey143del prevtx_err["witnessScript"]144assert_raises_rpc_error(-8, "redeemScript/witnessScript does not match scriptPubKey", node2.signrawtransactionwithkey, rawtx, priv_keys[0:nsigs-1], [prevtx_err])146# witnessScript does not match scriptPubKey147prevtx_err["witnessScript"] = prevtx_err["redeemScript"]148del prevtx_err["redeemScript"]149assert_raises_rpc_error(-8, "redeemScript/witnessScript does not match scriptPubKey", node2.signrawtransactionwithkey, rawtx, priv_keys[0:nsigs-1], [prevtx_err])151rawtx2 = node2.signrawtransactionwithkey(rawtx, priv_keys[0:nsigs - 1], prevtxs)152assert_equal(rawtx2["complete"], False)153rawtx3 = node2.signrawtransactionwithkey(rawtx, [priv_keys[-1]], prevtxs)154assert_equal(rawtx3["complete"], False)156if assert_mergeability:157# Test boundary conditions158assert_raises_rpc_error(-22, "TX decode failed", node2.combinerawtransaction, [rawtx2['hex'], rawtx3['hex'] + "00"])159assert_raises_rpc_error(-22, "Missing transactions. At least two transactions required.", node2.combinerawtransaction, [])160assert_raises_rpc_error(-22, "Missing transactions. At least two transactions required.", node2.combinerawtransaction, [rawtx2['hex']])162out_addr2 = getnewdestination('bech32')[2]163unmergeable_transaction_args = [164([[{"txid": tx["txid"], "vout": tx["sent_vout"]}], [{out_addr: outval * 2}]], {}), # similar transaction but with different amount to send165([[{"txid": tx["txid"], "vout": tx["sent_vout"]}], [{out_addr: outval}]], {"version": 1}), # similar transaction but with different version166([[{"txid": tx["txid"], "vout": tx["sent_vout"]}], [{out_addr: outval}]], {"locktime": 1}), # similar transaction but with different locktime167([[{"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 number169([[{"txid": tx["txid"], "vout": tx["sent_vout"] + 1}], [{out_addr: outval}]], {}) # similar transaction but with different input vout index170]172for rpc_args, rpc_kwargs in unmergeable_transaction_args:173unrelated_tx = node2.createrawtransaction(*rpc_args, **rpc_kwargs)174assert_raises_rpc_error(-8, "Transaction number 2 not compatible with first transaction", node0.combinerawtransaction, [rawtx2['hex'], unrelated_tx])176# Accept duplicate transactions in combinerawtransaction177dupe_merged_tx = node2.combinerawtransaction([rawtx2['hex'], rawtx2['hex']])178assert_equal(rawtx2['hex'], dupe_merged_tx)180combined_rawtx = node2.combinerawtransaction([rawtx2["hex"], rawtx3["hex"]])181tx = node0.sendrawtransaction(combined_rawtx, 0)182blk = self.generate(node0, 1)[0]183assert tx in node0.getblock(blk)["tx"]185assert_raises_rpc_error(-25, "Input not found or already spent", node2.combinerawtransaction, [rawtx2['hex'], rawtx3['hex']])187txinfo = node0.getrawtransaction(tx, True, blk)188self.log.info("n/m=%d/%d %s size=%d vsize=%d weight=%d" % (nsigs, nkeys, output_type, txinfo["size"], txinfo["vsize"], txinfo["weight"]))190def test_mixing_uncompressed_and_compressed_keys(self, node):191self.log.info('Mixed compressed and uncompressed multisigs are not allowed')192pk0, pk1, pk2 = [getnewdestination('bech32')[0][1].hex() for _ in range(3)]194# decompress pk2195pk_obj = ECPubKey()196pk_obj.set(bytes.fromhex(pk2))197pk_obj.compressed = False198pk2 = pk_obj.get_bytes().hex()200# Check all permutations of keys because order matters apparently201for keys in itertools.permutations([pk0, pk1, pk2]):202# Results should be the same as this legacy one203legacy_addr = node.createmultisig(2, keys, 'legacy')['address']205# Generate addresses with the segwit types. These should all make legacy addresses206err_msg = ["Unable to make chosen address type, please ensure no uncompressed public keys are present."]208for addr_type in ['bech32', 'p2sh-segwit']:209result = self.nodes[0].createmultisig(nrequired=2, keys=keys, address_type=addr_type)210assert_equal(legacy_addr, result['address'])211assert_equal(result['warnings'], err_msg)213def test_sortedmulti_descriptors_bip67(self):214self.log.info('Testing sortedmulti descriptors with BIP 67 test vectors')215with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/rpc_bip67.json')) as f:216vectors = json.load(f)218for t in vectors:219key_str = ','.join(t['keys'])220desc = descsum_create('sh(sortedmulti(2,{}))'.format(key_str))221assert_equal(self.nodes[0].deriveaddresses(desc)[0], t['address'])222sorted_key_str = ','.join(t['sorted_keys'])223sorted_key_desc = descsum_create('sh(multi(2,{}))'.format(sorted_key_str))224assert_equal(self.nodes[0].deriveaddresses(sorted_key_desc)[0], t['address'])227if __name__ == '__main__':228RpcCreateMultiSigTest(__file__).main()
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.