Skip to content

Commit 57b47c4

Browse files
committed
test: Test MuSig2 in the wallet
1 parent fea4a11 commit 57b47c4

File tree

2 files changed

+191
-0
lines changed

2 files changed

+191
-0
lines changed

test/functional/test_runner.py

+1
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,7 @@
387387
'mempool_datacarrier.py',
388388
'feature_coinstatsindex.py',
389389
'wallet_orphanedreward.py',
390+
'wallet_musig.py --descriptors',
390391
'wallet_timelock.py',
391392
'p2p_permissions.py',
392393
'feature_blocksdir.py',

test/functional/wallet_musig.py

+190
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2024 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+
6+
import re
7+
8+
from test_framework.descriptors import descsum_create
9+
from test_framework.key import H_POINT
10+
from test_framework.test_framework import BitcoinTestFramework
11+
from test_framework.util import assert_equal
12+
13+
PRIVKEY_RE = re.compile(r"^tr\((.+?)/.+\)#.{8}$")
14+
PUBKEY_RE = re.compile(r"^tr\((\[.+?\].+?)/.+\)#.{8}$")
15+
ORIGIN_PATH_RE = re.compile(r"^\[\w{8}(/.*)\].*$")
16+
MULTIPATH_RE = re.compile(r"(.*?)<(\d+);(\d+)>")
17+
18+
19+
class WalletMuSigTest(BitcoinTestFramework):
20+
WALLET_NUM = 0
21+
def add_options(self, parser):
22+
self.add_wallet_options(parser, legacy=False)
23+
24+
def set_test_params(self):
25+
self.num_nodes = 1
26+
27+
def skip_test_if_missing_module(self):
28+
self.skip_if_no_wallet()
29+
30+
def do_test(self, comment, pattern):
31+
self.log.info(f"Testing {comment}")
32+
def_wallet = self.nodes[0].get_wallet_rpc(self.default_wallet_name)
33+
has_int = "<" in pattern and ">" in pattern
34+
35+
wallets = []
36+
keys = []
37+
38+
pat = pattern.replace("$H", H_POINT)
39+
40+
# Figure out how many wallets are needed and create them
41+
exp_key_leaf = 0
42+
for i in range(10):
43+
if f"${i}" in pat:
44+
exp_key_leaf += pat.count(f"${i}")
45+
wallet_name = f"musig_{self.WALLET_NUM}"
46+
self.WALLET_NUM += 1
47+
self.nodes[0].createwallet(wallet_name)
48+
wallet = self.nodes[0].get_wallet_rpc(wallet_name)
49+
wallets.append(wallet)
50+
51+
for priv_desc in wallet.listdescriptors(True)["descriptors"]:
52+
desc = priv_desc["desc"]
53+
if not desc.startswith("tr("):
54+
continue
55+
privkey = PRIVKEY_RE.search(desc).group(1)
56+
break
57+
for pub_desc in wallet.listdescriptors()["descriptors"]:
58+
desc = pub_desc["desc"]
59+
if not desc.startswith("tr("):
60+
continue
61+
pubkey = PUBKEY_RE.search(desc).group(1)
62+
# Since the pubkey is derived from the private key that we have, we need
63+
# to extract and insert the origin path from the pubkey as well.
64+
privkey += ORIGIN_PATH_RE.search(pubkey).group(1)
65+
break
66+
keys.append((privkey, pubkey))
67+
68+
# Construct and import each wallet's musig descriptor
69+
for i, wallet in enumerate(wallets):
70+
desc = pat
71+
import_descs = []
72+
for j, (priv, pub) in enumerate(keys):
73+
if j == i:
74+
desc = desc.replace(f"${i}", priv)
75+
else:
76+
desc = desc.replace(f"${j}", pub)
77+
78+
# Deal with the multipath descriptor syntax for external and internal
79+
if has_int:
80+
ext_desc = ""
81+
int_desc = ""
82+
for m in MULTIPATH_RE.finditer(desc):
83+
ext_desc += m.group(1) + m.group(2)
84+
int_desc += m.group(1) + m.group(3)
85+
postfix = desc.split(">")[-1]
86+
ext_desc += postfix
87+
int_desc += postfix
88+
89+
import_descs.append({
90+
"desc": descsum_create(int_desc),
91+
"active": True,
92+
"internal": True,
93+
"timestamp": "now",
94+
})
95+
else:
96+
ext_desc = desc
97+
98+
import_descs.append({
99+
"desc": descsum_create(ext_desc),
100+
"active": True,
101+
"internal": False,
102+
"timestamp": "now",
103+
})
104+
105+
res = wallet.importdescriptors(import_descs)
106+
for r in res:
107+
assert_equal(r["success"], True)
108+
109+
# Check that the wallets agree on the same musig address
110+
addr = None
111+
change_addr = None
112+
for wallet in wallets:
113+
if addr is None:
114+
addr = wallet.getnewaddress(address_type="bech32m")
115+
else:
116+
assert_equal(addr, wallet.getnewaddress(address_type="bech32m"))
117+
if has_int:
118+
if change_addr is None:
119+
change_addr = wallet.getrawchangeaddress(address_type="bech32m")
120+
else:
121+
assert_equal(change_addr, wallet.getrawchangeaddress(address_type="bech32m"))
122+
123+
# Fund that address
124+
def_wallet.sendtoaddress(addr, 10)
125+
self.generate(self.nodes[0], 1)
126+
127+
# Spend that UTXO
128+
utxo = wallets[0].listunspent()[0]
129+
psbt = wallets[0].send(outputs=[{def_wallet.getnewaddress(): 5}], inputs=[utxo], change_type="bech32m")["psbt"]
130+
131+
dec_psbt = self.nodes[0].decodepsbt(psbt)
132+
assert_equal(len(dec_psbt["inputs"]), 1)
133+
assert_equal(len(dec_psbt["inputs"][0]["musig2_participant_pubkeys"]), pattern.count("musig("))
134+
135+
# Retrieve all participant pubkeys
136+
part_pks = set()
137+
for agg in dec_psbt["inputs"][0]["musig2_participant_pubkeys"]:
138+
for part_pub in agg["participant_pubkeys"]:
139+
part_pks.add(part_pub[2:])
140+
# Check that there are as many participants as we expected
141+
assert_equal(len(part_pks), len(keys))
142+
# Check that each participant has a derivation path
143+
for deriv_path in dec_psbt["inputs"][0]["taproot_bip32_derivs"]:
144+
if deriv_path["pubkey"] in part_pks:
145+
part_pks.remove(deriv_path["pubkey"])
146+
assert_equal(len(part_pks), 0)
147+
148+
# Add pubnonces
149+
nonce_psbts = []
150+
for wallet in wallets:
151+
proc = wallet.walletprocesspsbt(psbt)
152+
assert_equal(proc["complete"], False)
153+
nonce_psbts.append(proc["psbt"])
154+
155+
comb_nonce_psbt = self.nodes[0].combinepsbt(nonce_psbts)
156+
157+
# Add partial sigs
158+
dec_psbt = self.nodes[0].decodepsbt(comb_nonce_psbt)
159+
assert_equal(len(dec_psbt["inputs"][0]["musig2_pubnonces"]), exp_key_leaf)
160+
161+
psig_psbts = []
162+
for wallet in wallets:
163+
proc = wallet.walletprocesspsbt(comb_nonce_psbt)
164+
assert_equal(proc["complete"], False)
165+
psig_psbts.append(proc["psbt"])
166+
167+
comb_psig_psbt = self.nodes[0].combinepsbt(psig_psbts)
168+
169+
dec_psbt = self.nodes[0].decodepsbt(comb_psig_psbt)
170+
assert_equal(len(dec_psbt["inputs"][0]["musig2_pubnonces"]), exp_key_leaf)
171+
172+
# Non-participant aggregates partial sigs and send
173+
finalized = self.nodes[0].finalizepsbt(comb_psig_psbt)
174+
assert_equal(finalized["complete"], True)
175+
assert "hex" in finalized
176+
self.nodes[0].sendrawtransaction(finalized["hex"])
177+
178+
def run_test(self):
179+
self.do_test("rawtr(musig(keys/*))", "rawtr(musig($0/<0;1>/*,$1/<1;2>/*,$2/<2;3>/*))")
180+
self.do_test("tr(musig(keys/*))", "tr(musig($0/<0;1>/*,$1/<1;2>/*,$2/<2;3>/*))")
181+
self.do_test("rawtr(musig/*)", "rawtr(musig($0,$1,$2)/<0;1>/*)")
182+
self.do_test("tr(musig/*)", "tr(musig($0,$1,$2)/<0;1>/*)")
183+
self.do_test("tr(H, pk(musig(keys/*)))", "tr($H,pk(musig($0/<0;1>/*,$1/<1;2>/*,$2/<2;3>/*)))")
184+
self.do_test("tr(H,pk(musig/*))", "tr($H,pk(musig($0,$1,$2)/<0;1>/*))")
185+
self.do_test("tr(H,{pk(musig/*), pk(musig/*)})", "tr($H,{pk(musig($0,$1,$2)/<0;1>/*),pk(musig($3,$4,$5)/0/*)})")
186+
self.do_test("tr(H,{pk(musig/*), pk(same keys different musig/*)})", "tr($H,{pk(musig($0,$1,$2)/<0;1>/*),pk(musig($1,$2)/0/*)})")
187+
188+
189+
if __name__ == '__main__':
190+
WalletMuSigTest(__file__).main()

0 commit comments

Comments
 (0)