forked from stepansnigirev/testvectors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_pset.py
366 lines (331 loc) · 13.3 KB
/
test_pset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
from typing import OrderedDict
from embit import bip32, bip39
from embit.liquid.networks import get_network
from embit.liquid import slip77
from embit.descriptor.checksum import add_checksum
from embit.descriptor import Descriptor
from embit.liquid.pset import PSET
from embit.liquid.finalizer import finalize_psbt
from embit.liquid.transaction import LSIGHASH as SIGHASH
import random
import pytest
# liquid regtest can have any name except main, test, regtest, liquidv1 and liquidtestnet
NET = get_network("liquidregtest")
MNEMONIC = "glory promote mansion idle axis finger extra february uncover one trip resource lawn turtle enact monster seven myth punch hobby comfort wild raise skin"
SEED = bip39.mnemonic_to_seed(MNEMONIC)
ROOTKEY = bip32.HDKey.from_seed(SEED, version=NET["xprv"])
FGP = ROOTKEY.my_fingerprint.hex() # fingerprint for derivation
MBK = slip77.master_blinding_from_seed(SEED) # master blinding key
MBK_WIF = MBK.wif()
# some random cosigner xpubs
SEEDS = [bytes([i]*32) for i in range(1,5)]
COSIGNERS = [bip32.HDKey.from_seed(seed, version=NET["xprv"]) for seed in SEEDS]
# uncomment more lines to add more sighashes
BASIC_SIGHASHES = [SIGHASH.ALL, SIGHASH.NONE, SIGHASH.SINGLE]
ALL_SIGHASHES = BASIC_SIGHASHES
ALL_SIGHASHES = ALL_SIGHASHES + [sh | SIGHASH.ANYONECANPAY for sh in BASIC_SIGHASHES]
ALL_SIGHASHES = ALL_SIGHASHES + [sh | SIGHASH.RANGEPROOF for sh in BASIC_SIGHASHES]
ALL_SIGHASHES = ALL_SIGHASHES + [sh | SIGHASH.ANYONECANPAY | SIGHASH.RANGEPROOF for sh in BASIC_SIGHASHES]
def sighash_to_str(sh: int) -> str:
if sh is None or sh == -1:
return "DEFAULT"
base = sh & ~(SIGHASH.ANYONECANPAY|SIGHASH.RANGEPROOF)
base_str = {
SIGHASH.DEFAULT: "DEFAULT",
SIGHASH.ALL: "ALL",
SIGHASH.NONE: "NONE",
SIGHASH.SINGLE: "SINGLE"
}
try:
res = base_str[base]
except KeyError:
raise ValueError("invalid SIGHASH flags")
if sh & SIGHASH.ANYONECANPAY:
res += "|ANYONECANPAY"
if sh & SIGHASH.RANGEPROOF:
res += "|RANGEPROOF"
return res
def sign_psbt(wallet_rpc, psbt:str, sighash=None):
"""Replace with your tested functionality"""
sighash_str = sighash_to_str(sighash) if sighash is not None else "DEFAULT"
signed_psbt = wallet_rpc.walletprocesspsbt(psbt, True, sighash_str)['psbt']
return signed_psbt
def sign_psbt_embit(psbt:str, root=ROOTKEY):
"""Replace with your tested functionality"""
psbt = PSET.from_string(psbt)
psbt.sign_with(root, sighash=None) # tell embit to sign with whatever sighash is provided
return str(psbt)
############
def random_wallet_name():
return "test"+random.randint(0,0xFFFFFFFF).to_bytes(4,'big').hex()
def create_wallet(erpc, d1, d2, mbk=MBK):
wname = random_wallet_name()
# to derive addresses
desc1 = Descriptor.from_string(d1)
desc2 = Descriptor.from_string(d2)
# to add checksums
d1 = add_checksum(str(d1))
d2 = add_checksum(str(d2))
erpc.createwallet(wname, False, True, "", False, True, False)
w = erpc.wallet(wname)
res = w.importdescriptors([{
"desc": d1,
"active": True,
"internal": False,
"timestamp": "now",
"range": 20,
},{
"desc": d2,
"active": True,
"internal": True,
"timestamp": "now",
"range": 20,
}])
assert all([k["success"] for k in res])
w.importmasterblindingkey(mbk.secret.hex())
# detect addr type as Bitcoin Core is stupid
if desc1.is_wrapped:
w.addr_type = "p2sh-segwit"
elif desc1.is_legacy:
w.addr_type = "legacy"
else:
w.addr_type = "bech32"
return w
def fund_wallet(erpc, w, amount=1, confidential=True):
addr = w.getnewaddress("", w.addr_type)
if not confidential:
addr = w.getaddressinfo(addr)["unconfidential"]
wdefault = erpc.wallet()
wdefault.sendtoaddress(addr, amount)
wdefault.mine(1)
def inject_sighash(psbt, sighash):
psbt = PSET.from_string(psbt)
for inp in psbt.inputs:
inp.sighash_type = sighash
return str(psbt)
def create_psbt(erpc, w, amount=0.1, destination=None, confidential=True, confidential_change=True, sighash=None):
wdefault = erpc.wallet()
if not destination:
destination = wdefault.getnewaddress()
change = w.getrawchangeaddress(w.addr_type)
if not confidential:
destination = w.getaddressinfo(destination)["unconfidential"]
if not confidential_change:
change = w.getaddressinfo(change)["unconfidential"]
psbt = w.walletcreatefundedpsbt([], [{destination: amount}], 0, {"includeWatching": True, "changeAddress": change, "fee_rate": 1}, True)
unblinded = psbt["psbt"]
try:
blinded = w.blindpsbt(unblinded)
except:
try:
blinded = w.walletprocesspsbt(unblinded, False)['psbt']
except:
blinded = None
# inject sighash for all inputs
if sighash is not None:
unblinded = inject_sighash(unblinded, sighash)
if blinded:
blinded = inject_sighash(blinded, sighash)
return unblinded, blinded
def check_psbt(erpc, unsigned, signed, sighash=None):
if sighash:
psbt = PSET.from_string(signed)
for inp in psbt.inputs:
for sig in inp.partial_sigs.values():
assert sig[-1] == sighash
combined = erpc.combinepsbt([unsigned, signed])
final = erpc.finalizepsbt(combined)
if final["complete"]:
raw = final["hex"]
else: # finalize in elements is buggy, may not finalize
tx = finalize_psbt(PSET.from_string(combined))
assert tx is not None
raw = str(tx)
# test accept
assert erpc.testmempoolaccept([raw])[0]["allowed"]
def sighash_from_signed_pset(signed: str) -> int:
sighash = -1
psbt = PSET.from_string(signed)
for inp in psbt.inputs:
for sig in inp.partial_sigs.values():
if sighash < 0:
sighash = sig[-1]
else:
assert sig[-1] == sighash
if inp.final_scriptwitness:
sig_items = inp.final_scriptwitness.items
sig = sig_items[0] if sig_items[0] else sig_items[1]
if sig:
if sighash < 0:
sighash = sig[-1]
else:
assert sig[-1] == sighash
return sighash
def get_signatures(signed_pset: str) -> dict:
psbt = PSET.from_string(signed_pset)
sigs = OrderedDict()
for inp_idx, inp in enumerate(psbt.inputs):
sigs[inp_idx] = OrderedDict()
if inp.partial_sigs:
sigs[inp_idx]['partial_sigs'] = [sig.hex() for sig in inp.partial_sigs.values()]
if inp.final_scriptwitness:
sigs[inp_idx]['final_scriptwitness'] = [item.hex() for item in inp.final_scriptwitness.items]
if inp.final_scriptsig:
sigs[inp_idx]['final_scriptsig'] = inp.final_scriptsig.data.hex()
return sigs
def bulk_check(erpc, descriptors, collector, mode: str = 'all'):
w = create_wallet(erpc, *descriptors)
fund_wallet(erpc, w, 10, confidential=True)
if mode in ['sighashes', 'all']:
for sh in ALL_SIGHASHES:
unblinded, blinded = create_psbt(erpc, w, sighash=sh)
# blinding may fail if all inputs and outputs are confidential, so fund_wallet will return None in blinded
unsigned = blinded or unblinded
signed = sign_psbt(w, unsigned, sighash=sh)
check_psbt(erpc, unsigned, signed, sighash=sh)
collector.add_test(
pset=unsigned,
signatures=get_signatures(signed),
sighash=sh,
description=f"Confidential: both, sighash: {sighash_to_str(sh)}"
)
# test all confidential-unconfidential pairs
conf_status = {
(False, False): "none",
(True, False): "input",
(False, True): "output",
(True, True): "both"
}
if mode in ['blinded_unblinded', 'all']:
for conf_input in [True, False]:
w = create_wallet(erpc, *descriptors)
fund_wallet(erpc, w, 10, confidential=conf_input)
for conf_destination in [True, False]:
unblinded, blinded = create_psbt(erpc, w, confidential=conf_destination)
# blinding may fail if all inputs and outputs are confidential, so fund_wallet will return None in blinded
unsigned = blinded or unblinded
signed = sign_psbt(w, unsigned)
check_psbt(erpc, unsigned, signed)
sh = sighash_from_signed_pset(signed)
collector.add_test(
pset=unsigned,
signatures=get_signatures(signed),
sighash=sh,
description=(f"Confidential: {conf_status[(conf_input, conf_destination)]}, "
f"sighash: {sighash_to_str(sh)}")
)
def derivation_quote(path: str) -> str:
return path.replace("h", "'")
##########################
@pytest.mark.parametrize("mode", ['sighashes', 'blinded_unblinded'])
def test_wpkh(erpc, collector, mode):
derivation = "84h/1h/0h"
xprv = ROOTKEY.derive(f"m/{derivation}")
xpub = xprv.to_public()
# change and receive descriptors
descriptors = (
f"wpkh([{FGP}/{derivation}]{xprv}/0/*)",
f"wpkh([{FGP}/{derivation}]{xprv}/1/*)"
)
collector.define_suite(
kind="valid",
name="wpkh",
mbk=MBK_WIF,
policy_map="wpkh(@0)",
keys_info=[f"[{FGP}/{derivation_quote(derivation)}]{xpub}/**"],
description="Single signature P2WPKH"
)
bulk_check(erpc, descriptors, collector, mode)
@pytest.mark.parametrize("mode", ['sighashes', 'blinded_unblinded'])
def test_sh_wpkh(erpc, collector, mode):
derivation = "49h/1h/0h"
xprv = ROOTKEY.derive(f"m/{derivation}")
xpub = xprv.to_public()
# change and receive descriptors
descriptors = (
f"sh(wpkh([{FGP}/{derivation}]{xprv}/0/*))",
f"sh(wpkh([{FGP}/{derivation}]{xprv}/1/*))"
)
collector.define_suite(
kind="valid",
name="sh_wpkh",
mbk=MBK_WIF,
policy_map="sh(wpkh(@0))",
keys_info=[f"[{FGP}/{derivation_quote(derivation)}]{xpub}/**"],
description="Single signature P2SH-P2WPKH"
)
bulk_check(erpc, descriptors, collector, mode)
@pytest.mark.parametrize("mode", ['sighashes', 'blinded_unblinded'])
def test_pkh(erpc, collector, mode):
derivation = "44h/1h/0h"
xprv = ROOTKEY.derive(f"m/{derivation}")
xpub = xprv.to_public()
# change and receive descriptors
descriptors = (
f"pkh([{FGP}/{derivation}]{xprv}/0/*)",
f"pkh([{FGP}/{derivation}]{xprv}/1/*)"
)
collector.skip_suite() # Legacy transactions are not currently supported
bulk_check(erpc, descriptors, collector, mode)
@pytest.mark.parametrize("mode", ['sighashes', 'blinded_unblinded'])
def test_wsh(erpc, collector, mode):
# 1-of-2 multisig
derivation = "48h/1h/0h/2h"
xprv = ROOTKEY.derive(f"m/{derivation}")
xpub = xprv.to_public()
cosigner = COSIGNERS[0].derive(f"m/{derivation}").to_public()
# change and receive descriptors
descriptors = (
f"wsh(sortedmulti(1,[12345678/{derivation}]{cosigner},[{FGP}/{derivation}]{xprv}/0/*))",
f"wsh(sortedmulti(1,[12345678/{derivation}]{cosigner},[{FGP}/{derivation}]{xprv}/1/*))"
)
collector.define_suite(
kind="valid",
name="wsh_sortedmulti",
mbk=MBK_WIF,
policy_map="wsh(sortedmulti(1,@0,@1))",
keys_info=[
f"[12345678/{derivation_quote(derivation)}]{cosigner}/**",
f"[{FGP}/{derivation_quote(derivation)}]{xpub}/**",
],
description="Multiple signature 1-of-2 P2WSH"
)
bulk_check(erpc, descriptors, collector, mode)
@pytest.mark.parametrize("mode", ['sighashes', 'blinded_unblinded'])
def test_sh_wsh(erpc, collector, mode):
# 1-of-2 multisig
derivation = "48h/1h/0h/1h"
xprv = ROOTKEY.derive(f"m/{derivation}")
xpub = xprv.to_public()
cosigner = COSIGNERS[0].derive(f"m/{derivation}").to_public()
# change and receive descriptors
descriptors = (
f"sh(wsh(sortedmulti(1,[12345678/{derivation}]{cosigner},[{FGP}/{derivation}]{xprv}/0/*)))",
f"sh(wsh(sortedmulti(1,[12345678/{derivation}]{cosigner},[{FGP}/{derivation}]{xprv}/1/*)))"
)
collector.define_suite(
kind="valid",
name="sh_wsh_sortedmulti",
mbk=MBK_WIF,
policy_map="sh(wsh(sortedmulti(1,@0,@1)))",
keys_info=[
f"[12345678/{derivation_quote(derivation)}]{cosigner}/**",
f"[{FGP}/{derivation_quote(derivation)}]{xpub}/**",
],
description="Multiple signature 1-of-2 P2SH-P2WSH"
)
bulk_check(erpc, descriptors, collector, mode)
@pytest.mark.parametrize("mode", ['sighashes', 'blinded_unblinded'])
def test_sh(erpc, collector, mode):
# 1-of-2 multisig
derivation = "45h"
xprv = ROOTKEY.derive(f"m/{derivation}")
xpub = xprv.to_public()
cosigner = COSIGNERS[0].derive(f"m/{derivation}").to_public()
# change and receive descriptors
descriptors = (
f"sh(sortedmulti(1,[12345678/{derivation}]{cosigner},[{FGP}/{derivation}]{xprv}/0/*))",
f"sh(sortedmulti(1,[12345678/{derivation}]{cosigner},[{FGP}/{derivation}]{xprv}/1/*))"
)
collector.skip_suite() # Legacy transactions are not currently supported
bulk_check(erpc, descriptors, collector, mode)