forked from Foundation-Devices/passport-firmware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
psbt.py
1793 lines (1394 loc) · 64.8 KB
/
psbt.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: 2020 Foundation Devices, Inc. <[email protected]>
# SPDX-License-Identifier: GPL-3.0-or-later
#
# SPDX-FileCopyrightText: 2018 Coinkite, Inc. <coldcardwallet.com>
# SPDX-License-Identifier: GPL-3.0-only
#
# (c) Copyright 2018 by Coinkite Inc. This file is part of Coldcard <coldcardwallet.com>
# and is covered by GPLv3 license found in COPYING.
#
# psbt.py - understand PSBT file format: verify and generate them
#
from ustruct import unpack_from, unpack, pack
from utils import xfp2str, B2A, keypath_to_str, swab32
import trezorcrypto, stash, gc, history, sys
from sffile import SizerFile
from sram4 import psbt_tmp256
from multisig import MultisigWallet, MAX_SIGNERS, disassemble_multisig_mn
from exceptions import FatalPSBTIssue, FraudulentChangeOutput
from serializations import ser_compact_size, deser_compact_size, hash160
from serializations import CTxIn, CTxInWitness, CTxOut, SIGHASH_ALL
from serializations import ser_sig_der, uint256_from_str, ser_push_data, uint256_from_str
from serializations import ser_string
from common import system
from public_constants import (
PSBT_GLOBAL_UNSIGNED_TX, PSBT_GLOBAL_XPUB, PSBT_IN_NON_WITNESS_UTXO, PSBT_IN_WITNESS_UTXO,
PSBT_IN_PARTIAL_SIG, PSBT_IN_SIGHASH_TYPE, PSBT_IN_REDEEM_SCRIPT,
PSBT_IN_WITNESS_SCRIPT, PSBT_IN_BIP32_DERIVATION, PSBT_IN_FINAL_SCRIPTSIG,
PSBT_IN_FINAL_SCRIPTWITNESS, PSBT_OUT_REDEEM_SCRIPT, PSBT_OUT_WITNESS_SCRIPT,
PSBT_OUT_BIP32_DERIVATION, MAX_PATH_DEPTH
)
# print some things
# DEBUG = const(1)
# class HashNDump:
# def __init__(self, d=None):
# self.rv = trezorcrypto.sha256()
# print('Hashing: ', end='')
# if d:
# self.update(d)
#
# def update(self, d):
# print(b2a_hex(d), end=' ')
# self.rv.update(d)
#
# def digest(self):
# print(' END')
# return self.rv.digest()
def read_varint(v):
# read "compact sized" int from a few bytes.
assert not isinstance(v, tuple), v
nit = v[0]
if nit == 253:
return unpack_from("<H", v, 1)[0]
elif nit == 254:
return unpack_from("<I", v, 1)[0]
elif nit == 255:
return unpack_from("<Q", v, 1)[0]
return nit
def seq_to_str(seq):
# take a set or list of numbers and show a tidy list in order.
return ', '.join(str(i) for i in sorted(seq))
def _skip_n_objs(fd, n, cls):
# skip N sized objects in the stream, for example a vectors of CTxIns
# - returns starting position
if cls == 'CTxIn':
# output point(hash, n) + script sig + locktime
pat = [32+4, None, 4]
elif cls == 'CTxOut':
# nValue + Script
pat = [8, None]
else:
raise ValueError(cls)
rv = fd.tell()
for i in range(n):
for p in pat:
if p is None:
# variable-length part
sz = deser_compact_size(fd)
fd.seek(sz, 1)
else:
fd.seek(p, 1)
return rv
def calc_txid(fd, poslen, body_poslen=None):
# Given the (pos,len) of a transaction in a file, return the txid for that txn.
# - doesn't validate data
# - does detect witness txn vs. old style
# - simple double-sha256() if old style txn, otherwise witness data must be carefully skipped
# see if witness encoding in effect
fd.seek(poslen[0])
txn_version, marker, flags = unpack("<iBB", fd.read(6))
has_witness = (marker == 0 and flags != 0x0)
if not has_witness:
# txn does not have witness data, so txid==wtxix
return get_hash256(fd, poslen)
rv = trezorcrypto.sha256()
# de/reserialize much of the txn -- but not the witness data
rv.update(pack("<i", txn_version))
if body_poslen is None:
body_start = fd.tell()
# determine how long ins + outs are...
num_in = deser_compact_size(fd)
_skip_n_objs(fd, num_in, 'CTxIn')
num_out = deser_compact_size(fd)
_skip_n_objs(fd, num_out, 'CTxOut')
body_poslen = (body_start, fd.tell() - body_start)
# hash the bulk of txn
get_hash256(fd, body_poslen, hasher=rv)
# assume last 4 bytes are the lock_time
fd.seek(sum(poslen) - 4)
rv.update(fd.read(4))
return trezorcrypto.sha256(rv.digest()).digest()
def get_hash256(fd, poslen, hasher=None):
# return the double-sha256 of a value, without loading it into memory
pos, ll = poslen
rv = hasher or trezorcrypto.sha256()
fd.seek(pos)
while ll:
here = fd.readinto(psbt_tmp256)
if not here: break
if here > ll:
here = ll
rv.update(memoryview(psbt_tmp256)[0:here])
ll -= here
if hasher:
return
return trezorcrypto.sha256(rv.digest()).digest()
class psbtProxy:
# store offsets to values, but track the keys in-memory.
short_values = ()
no_keys = ()
# these fields will return None but are not stored unless a value is set
blank_flds = ('unknown', )
def __init__(self):
self.fd = None
#self.unknown = {}
def __getattr__(self, nm):
if nm in self.blank_flds:
return None
raise AttributeError(nm)
def parse(self, fd):
self.fd = fd
while 1:
ks = deser_compact_size(fd)
if ks is None: break
if ks == 0: break
key = fd.read(ks)
vs = deser_compact_size(fd)
assert vs != None, 'eof'
kt = key[0]
# print('kt={}'.format(kt))
# print('self.no_keys={} 1'.format(self.no_keys))
if kt in self.no_keys:
# print('not expecting key')
assert len(key) == 1 # not expecting key
# storing offset and length only! Mostly.
# print('self.short_values={}'.format(self.short_values))
if kt in self.short_values:
# print('Adding xpub')
actual = fd.read(vs)
self.store(kt, bytes(key), actual)
else:
# skip actual data for now
proxy = (fd.tell(), vs)
fd.seek(vs, 1)
self.store(kt, bytes(key), proxy)
def write(self, out_fd, ktype, val, key=b''):
# serialize helper: write w/ size and key byte
out_fd.write(ser_compact_size(1 + len(key)))
out_fd.write(bytes([ktype]) + key)
if isinstance(val, tuple):
(pos, ll) = val
out_fd.write(ser_compact_size(ll))
self.fd.seek(pos)
while ll:
t = self.fd.read(min(64, ll))
out_fd.write(t)
ll -= len(t)
elif isinstance(val, list):
# for subpaths lists (LE32 ints)
assert ktype in (PSBT_IN_BIP32_DERIVATION, PSBT_OUT_BIP32_DERIVATION)
out_fd.write(ser_compact_size(len(val) * 4))
for i in val:
out_fd.write(pack('<I', i))
else:
out_fd.write(ser_compact_size(len(val)))
out_fd.write(val)
def get(self, val):
# get the raw bytes for a value.
pos, ll = val
self.fd.seek(pos)
return self.fd.read(ll)
def parse_subpaths(self, my_xfp):
# Reformat self.subpaths into a more useful form for us; return # of them
# that are ours (and track that as self.num_our_keys)
# - works in-place, on self.subpaths
# - creates dictionary: pubkey => [xfp, *path]
# - will be single entry for non-p2sh ins and outs
if not self.subpaths:
return 0
if self.num_our_keys != None:
# already been here once
return self.num_our_keys
num_ours = 0
for pk in self.subpaths:
assert len(pk) in {33, 65}, "hdpath pubkey len"
if len(pk) == 33:
assert pk[0] in {0x02, 0x03}, "uncompressed pubkey"
vl = self.subpaths[pk][1]
# force them to use a derived key, never the master
assert vl >= 8, 'too short key path'
assert (vl % 4) == 0, 'corrupt key path'
assert (vl//4) <= MAX_PATH_DEPTH, 'too deep'
# promote to a list of ints
v = self.get(self.subpaths[pk])
curr = list(unpack_from('<%dI' % (vl//4), v))
# update in place
self.subpaths[pk] = curr
if curr[0] == my_xfp or curr[0] == swab32(my_xfp):
num_ours += 1
else:
# Address that isn't based on my seed; might be another leg in a p2sh,
# or an input we're not supposed to be able to sign... and that's okay.
pass
self.num_our_keys = num_ours
return num_ours
# Track details of each output of PSBT
#
class psbtOutputProxy(psbtProxy):
no_keys = { PSBT_OUT_REDEEM_SCRIPT, PSBT_OUT_WITNESS_SCRIPT }
blank_flds = ('unknown', 'subpaths', 'redeem_script', 'witness_script',
'is_change', 'num_our_keys')
def __init__(self, fd, idx):
super().__init__()
# things we track
#self.subpaths = None # a dictionary if non-empty
#self.redeem_script = None
#self.witness_script = None
# this flag is set when we are assuming output will be change (same wallet)
#self.is_change = False
self.parse(fd)
def store(self, kt, key, val):
if kt == PSBT_OUT_BIP32_DERIVATION:
if not self.subpaths:
self.subpaths = {}
self.subpaths[key[1:]] = val
elif kt == PSBT_OUT_REDEEM_SCRIPT:
self.redeem_script = val
elif kt == PSBT_OUT_WITNESS_SCRIPT:
self.witness_script = val
else:
if not self.unknown:
self.unknown = {}
self.unknown[key] = val
def serialize(self, out_fd, my_idx):
wr = lambda *a: self.write(out_fd, *a)
if self.subpaths:
for k in self.subpaths:
wr(PSBT_OUT_BIP32_DERIVATION, self.subpaths[k], k)
if self.redeem_script:
wr(PSBT_OUT_REDEEM_SCRIPT, self.redeem_script)
if self.witness_script:
wr(PSBT_OUT_WITNESS_SCRIPT, self.witness_script)
if self.unknown:
for k in self.unknown:
wr(k[0], self.unknown[k], k[1:])
def validate(self, out_idx, txo, my_xfp, active_multisig):
# Do things make sense for this output?
# NOTE: We might think it's a change output just because the PSBT
# creator has given us a key path. However, we must be **very**
# careful and fully validate all the details.
# - no output info is needed, in general, so
# any output info provided better be right, or fail as "fraud"
# - full key derivation and validation is done during signing, and critical.
# - we raise fraud alarms, since these are not innocent errors
#
num_ours = self.parse_subpaths(my_xfp)
if num_ours == 0:
# - not considered fraud because other signers looking at PSBT may have them
# - user will see them as normal outputs, which they are from our PoV.
return
# - must match expected address for this output, coming from unsigned txn
addr_type, addr_or_pubkey, is_segwit = txo.get_address()
if len(self.subpaths) == 1:
# p2pk, p2pkh, p2wpkh cases
expect_pubkey, = self.subpaths.keys()
else:
# p2wsh/p2sh cases need full set of pubkeys, and therefore redeem script
expect_pubkey = None
if addr_type == 'p2pk':
# output is public key (not a hash, much less common)
assert len(addr_or_pubkey) == 33
if addr_or_pubkey != expect_pubkey:
raise FraudulentChangeOutput(out_idx, "P2PK change output is fraudulent")
self.is_change = True
return
# Figure out what the hashed addr should be
pkh = addr_or_pubkey
if addr_type == 'p2sh':
# P2SH or Multisig output
# Can be both, or either one depending on address type
redeem_script = self.get(self.redeem_script) if self.redeem_script else None
witness_script = self.get(self.witness_script) if self.witness_script else None
if not redeem_script and not witness_script:
# Perhaps an omission, so let's not call fraud on it
# But definitely required, else we don't know what script we're sending to.
raise FatalPSBTIssue("Missing redeem/witness script for output #%d" % out_idx)
if not is_segwit and redeem_script and \
len(redeem_script) == 22 and \
redeem_script[0] == 0 and redeem_script[1] == 20:
# it's actually segwit p2pkh inside p2sh
pkh = redeem_script[2:22]
expect_pkh = hash160(expect_pubkey)
else:
# Multisig change output, for wallet we're supposed to be a part of.
# - our key must be part of it
# - must look like input side redeem script (same fingerprints)
# - assert M/N structure of output to match any inputs we have signed in PSBT!
# - assert all provided pubkeys are in redeem script, not just ours
# - we get all of that by re-constructing the script from our wallet details
# it cannot be change if it doesn't precisely match our multisig setup
if not active_multisig:
# - might be a p2sh output for another wallet that isn't us
# - not fraud, just an output with more details than we need.
self.is_change = False
return
# redeem script must be exactly what we expect
# - pubkeys will be reconstructed from derived paths here
# - BIP45, BIP67 rules applied
# - p2sh-p2wsh needs witness script here, not redeem script value
# - if details provided in output section, must match our multisig wallet
try:
active_multisig.validate_script(witness_script or redeem_script,
subpaths=self.subpaths)
except BaseException as exc:
raise FraudulentChangeOutput(out_idx,
"P2WSH or P2SH change output script: %s" % exc)
if is_segwit:
# p2wsh case
# - need witness script and check it's hash against proposed p2wsh value
assert len(addr_or_pubkey) == 32
expect_wsh = trezorcrypto.sha256(witness_script).digest()
if expect_wsh != addr_or_pubkey:
raise FraudulentChangeOutput(out_idx, "P2WSH witness script has wrong hash")
self.is_change = True
return
if witness_script:
# p2sh-p2wsh case (because it had witness script)
expect_rs = b'\x00\x20' + trezorcrypto.sha256(witness_script).digest()
if redeem_script and expect_rs != redeem_script:
# iff they provide a redeeem script, then it needs to match
# what we expect it to be
raise FraudulentChangeOutput(out_idx,
"P2SH-P2WSH redeem script provided, but doesn't match.")
expect_pkh = hash160(expect_rs)
else:
# old BIP16 style; looks like payment addr
expect_pkh = hash160(redeem_script)
elif addr_type == 'p2pkh':
# input is hash160 of a single public key
assert len(addr_or_pubkey) == 20
expect_pkh = hash160(expect_pubkey)
else:
# we don't know how to "solve" this type of input
return
if pkh != expect_pkh:
raise FraudulentChangeOutput(out_idx, "Change output is fraudulent")
# We will check pubkey value at the last second, during signing.
self.is_change = True
# Track details of each input of PSBT
#
class psbtInputProxy(psbtProxy):
# just need to store a simple number for these
short_values = { PSBT_IN_SIGHASH_TYPE }
# only part-sigs have a key to be stored.
no_keys = { PSBT_IN_NON_WITNESS_UTXO, PSBT_IN_WITNESS_UTXO, PSBT_IN_SIGHASH_TYPE,
PSBT_IN_REDEEM_SCRIPT, PSBT_IN_WITNESS_SCRIPT, PSBT_IN_FINAL_SCRIPTSIG,
PSBT_IN_FINAL_SCRIPTWITNESS }
blank_flds = ('unknown',
'utxo', 'witness_utxo', 'sighash',
'redeem_script', 'witness_script', 'fully_signed',
'is_segwit', 'is_multisig', 'is_p2sh', 'num_our_keys',
'required_key', 'scriptSig', 'amount', 'scriptCode', 'added_sig')
def __init__(self, fd, idx):
super().__init__()
#self.utxo = None
#self.witness_utxo = None
self.part_sig = {}
#self.sighash = None
self.subpaths = {} # will typically be non-empty for all inputs
#self.redeem_script = None
#self.witness_script = None
# Non-zero if one or more of our signing keys involved in input
#self.num_our_keys = None
# things we've learned
#self.fully_signed = False
# we can't really learn this until we take apart the UTXO's scriptPubKey
#self.is_segwit = None
#self.is_multisig = None
#self.is_p2sh = False
#self.required_key = None # which of our keys will be used to sign input
#self.scriptSig = None
#self.amount = None
#self.scriptCode = None # only expected for segwit inputs
# after signing, we'll have a signature to add to output PSBT
#self.added_sig = None
self.parse(fd)
def validate(self, idx, txin, my_xfp):
# Validate this txn input: given deserialized CTxIn and maybe witness
# TODO: tighten these
if self.witness_script:
assert self.witness_script[1] >= 30
if self.redeem_script:
assert self.redeem_script[1] >= 22
# require path for each addr, check some are ours
# rework the pubkey => subpath mapping
self.parse_subpaths(my_xfp)
# sighash, but we're probably going to ignore anyway.
self.sighash = SIGHASH_ALL if self.sighash is None else self.sighash
if self.sighash != SIGHASH_ALL:
# - someday we will expand to other types, but not yet
raise FatalPSBTIssue('Can only do SIGHASH_ALL')
if self.part_sig:
# How complete is the set of signatures so far?
# - assuming PSBT creator doesn't give us extra data not required
# - seems harmless if they fool us into thinking already signed; we do nothing
# - could also look at pubkey needed vs. sig provided
# - could consider structure of MofN in p2sh cases
self.fully_signed = (len(self.part_sig) >= len(self.subpaths))
else:
# No signatures at all yet for this input (typical non multisig)
self.fully_signed = False
if self.utxo:
# Important: they might be trying to trick us with an un-related
# funding transaction (UTXO) that does not match the input signature we're making
# (but if it's segwit, the ploy wouldn't work, Segwit FtW)
# - challenge: it's a straight dsha256() for old serializations, but not for newer
# segwit txn's... plus I don't want to deserialize it here.
try:
observed = uint256_from_str(calc_txid(self.fd, self.utxo))
except:
raise AssertionError("Trouble parsing UTXO given for input #%d" % idx)
assert txin.prevout.hash == observed, "utxo hash mismatch for input #%d" % idx
def has_utxo(self):
# do we have a copy of the corresponding UTXO?
return bool(self.utxo) or bool(self.witness_utxo)
def get_utxo(self, idx):
# Load up the TxOut for specific output of the input txn associated with this in PSBT
# Aka. the "spendable" for this input #.
# - preserve the file pointer
# - nValue needed for total_value_in, but all fields needed for signing
#
fd = self.fd
old_pos = fd.tell()
if self.witness_utxo:
# Going forward? Just what we will witness; no other junk
# - prefer this format, altho does that imply segwit txn must be generated?
# - I don't know why we wouldn't always use this
# - once we use this partial utxo data, we must create witness data out
self.is_segwit = True
fd.seek(self.witness_utxo[0])
utxo = CTxOut()
utxo.deserialize(fd)
fd.seek(old_pos)
return utxo
assert self.utxo, 'no utxo'
# skip over all the parts of the txn we don't care about, without
# fully parsing it... pull out a single TXO
fd.seek(self.utxo[0])
_, marker, flags = unpack("<iBB", fd.read(6))
wit_format = (marker == 0 and flags != 0x0)
if not wit_format:
# rewind back over marker+flags
fd.seek(-2, 1)
# How many ins? We accept zero here because utxo's inputs might have been
# trimmed to save space, and we have test cases like that.
num_in = deser_compact_size(fd)
_skip_n_objs(fd, num_in, 'CTxIn')
num_out = deser_compact_size(fd)
assert idx < num_out, "not enuf outs"
_skip_n_objs(fd, idx, 'CTxOut')
utxo = CTxOut()
utxo.deserialize(fd)
# ... followed by more outs, and maybe witness data, but we don't care ...
fd.seek(old_pos)
return utxo
def determine_my_signing_key(self, my_idx, utxo, my_xfp, psbt):
# See what it takes to sign this particular input
# - type of script
# - which pubkey needed
# - scriptSig value
# - also validates redeem_script when present
self.amount = utxo.nValue
if not self.subpaths or self.fully_signed:
# without xfp+path we will not be able to sign this input
# - okay if fully signed
# - okay if payjoin or other multi-signer (not multisig) txn
self.required_key = None
return
self.is_multisig = False
self.is_p2sh = False
which_key = None
addr_type, addr_or_pubkey, addr_is_segwit = utxo.get_address()
if addr_is_segwit and not self.is_segwit:
self.is_segwit = True
if addr_type == 'p2sh':
# multisig input
self.is_p2sh = True
# we must have the redeem script already (else fail)
ks = self.witness_script or self.redeem_script
if not ks:
raise FatalPSBTIssue("Missing redeem/witness script for input #%d" % my_idx)
redeem_script = self.get(ks)
self.scriptSig = redeem_script
# new cheat: psbt creator probably telling us exactly what key
# to use, by providing exactly one. This is ideal for p2sh wrapped p2pkh
if len(self.subpaths) == 1:
which_key, = self.subpaths.keys()
else:
# Assume we'll be signing with any key we know
# - limitation: we cannot be two legs of a multisig
# - but if partial sig already in place, ignore that one
for pubkey, path in self.subpaths.items():
if self.part_sig and (pubkey in self.part_sig):
# pubkey has already signed, so ignore
continue
if path[0] == my_xfp or path[0] == swab32(my_xfp):
# slight chance of dup xfps, so handle
if not which_key:
which_key = set()
which_key.add(pubkey)
if not addr_is_segwit and \
len(redeem_script) == 22 and \
redeem_script[0] == 0 and redeem_script[1] == 20:
# it's actually segwit p2pkh inside p2sh
addr_type = 'p2sh-p2wpkh'
addr = redeem_script[2:22]
self.is_segwit = True
else:
# multiple keys involved, we probably can't do the finalize step
self.is_multisig = True
if self.witness_script and not self.is_segwit and self.is_multisig:
# bugfix
addr_type = 'p2sh-p2wsh'
self.is_segwit = True
elif addr_type == 'p2pkh':
# input is hash160 of a single public key
self.scriptSig = utxo.scriptPubKey
addr = addr_or_pubkey
for pubkey in self.subpaths:
if hash160(pubkey) == addr:
which_key = pubkey
break
elif addr_type == 'p2pk':
# input is single public key (less common)
self.scriptSig = utxo.scriptPubKey
assert len(addr_or_pubkey) == 33
if addr_or_pubkey in self.subpaths:
which_key = addr_or_pubkey
else:
# we don't know how to "solve" this type of input
pass
if self.is_multisig and which_key:
# We will be signing this input, so
# - find which wallet it is or
# - check it's the right M/N to match redeem script
#print("redeem: %s" % b2a_hex(redeem_script))
M, N = disassemble_multisig_mn(redeem_script)
xfp_paths = list(self.subpaths.values())
xfp_paths.sort()
if not psbt.active_multisig:
# search for multisig wallet
wal = MultisigWallet.find_match(M, N, xfp_paths)
if not wal:
raise FatalPSBTIssue('Unknown multisig wallet')
psbt.active_multisig = wal
else:
# check consistent w/ already selected wallet
psbt.active_multisig.assert_matching(M, N, xfp_paths)
# validate redeem script, by disassembling it and checking all pubkeys
try:
psbt.active_multisig.validate_script(redeem_script, subpaths=self.subpaths)
except BaseException as exc:
sys.print_exception(exc)
raise FatalPSBTIssue('Input #%d: %s' % (my_idx, exc))
# if not which_key and DEBUG:
# print("no key: input #%d: type=%s segwit=%d a_or_pk=%s scriptPubKey=%s" % (
# my_idx, addr_type, self.is_segwit or 0,
# b2a_hex(addr_or_pubkey), b2a_hex(utxo.scriptPubKey)))
self.required_key = which_key
if self.is_segwit:
if ('pkh' in addr_type):
# This comment from <https://bitcoincore.org/en/segwit_wallet_dev/>:
#
# Please note that for a P2SH-P2WPKH, the scriptCode is always 26
# bytes including the leading size byte, as 0x1976a914{20-byte keyhash}88ac,
# NOT the redeemScript nor scriptPubKey
#
# Also need this scriptCode for native segwit p2pkh
#
assert not self.is_multisig
self.scriptCode = b'\x19\x76\xa9\x14' + addr + b'\x88\xac'
elif not self.scriptCode:
# Segwit P2SH. We need the witness script to be provided.
if not self.witness_script:
raise FatalPSBTIssue('Need witness script for input #%d' % my_idx)
# "scriptCode is witnessScript preceeded by a
# compactSize integer for the size of witnessScript"
self.scriptCode = ser_string(self.get(self.witness_script))
# Could probably free self.subpaths and self.redeem_script now, but only if we didn't
# need to re-serialize as a PSBT.
def store(self, kt, key, val):
# Capture what we are interested in.
if kt == PSBT_IN_NON_WITNESS_UTXO:
self.utxo = val
elif kt == PSBT_IN_WITNESS_UTXO:
self.witness_utxo = val
elif kt == PSBT_IN_PARTIAL_SIG:
self.part_sig[key[1:]] = val
elif kt == PSBT_IN_BIP32_DERIVATION:
self.subpaths[key[1:]] = val
elif kt == PSBT_IN_REDEEM_SCRIPT:
self.redeem_script = val
elif kt == PSBT_IN_WITNESS_SCRIPT:
self.witness_script = val
elif kt == PSBT_IN_SIGHASH_TYPE:
self.sighash = unpack('<I', val)[0]
else:
# including: PSBT_IN_FINAL_SCRIPTSIG, PSBT_IN_FINAL_SCRIPTWITNESS
if not self.unknown:
self.unknown = {}
self.unknown[key] = val
def serialize(self, out_fd, my_idx):
# Output this input's values; might include signatures that weren't there before
wr = lambda *a: self.write(out_fd, *a)
if self.utxo:
wr(PSBT_IN_NON_WITNESS_UTXO, self.utxo)
if self.witness_utxo:
wr(PSBT_IN_WITNESS_UTXO, self.witness_utxo)
if self.part_sig:
for pk in self.part_sig:
wr(PSBT_IN_PARTIAL_SIG, self.part_sig[pk], pk)
if self.added_sig:
pubkey, sig = self.added_sig
wr(PSBT_IN_PARTIAL_SIG, sig, pubkey)
if self.sighash is not None:
wr(PSBT_IN_SIGHASH_TYPE, pack('<I', self.sighash))
for k in self.subpaths:
wr(PSBT_IN_BIP32_DERIVATION, self.subpaths[k], k)
if self.redeem_script:
wr(PSBT_IN_REDEEM_SCRIPT, self.redeem_script)
if self.witness_script:
wr(PSBT_IN_WITNESS_SCRIPT, self.witness_script)
if self.unknown:
for k in self.unknown:
wr(k[0], self.unknown[k], k[1:])
class psbtObject(psbtProxy):
"Just? parse and store"
no_keys = { PSBT_GLOBAL_UNSIGNED_TX }
def __init__(self):
super().__init__()
# global objects
self.txn = None
self.xpubs = [] # tuples(xfp_path, xpub)
from common import settings, dis
self.my_xfp = settings.get('xfp', 0)
# details that we discover as we go
self.inputs = None
self.outputs = None
self.had_witness = None
self.num_inputs = None
self.num_outputs = None
self.vin_start = None
self.vout_start = None
self.wit_start = None
self.txn_version = None
self.lock_time = None
self.total_value_out = None
self.total_value_in = None
self.presigned_inputs = set()
# when signing segwit stuff, there is some re-use of hashes
self.hashPrevouts = None
self.hashSequence = None
self.hashOutputs = None
# this points to a MS wallet, during operation
# - we are only supporting a single multisig wallet during signing
self.active_multisig = None
self.warnings = []
def store(self, kt, key, val):
# capture the values we care about
if kt == PSBT_GLOBAL_UNSIGNED_TX:
self.txn = val
elif kt == PSBT_GLOBAL_XPUB:
# list of tuples(xfp_path, xpub)
self.xpubs.append( (self.get(val), key[1:]) )
assert len(self.xpubs) <= MAX_SIGNERS
else:
self.unknowns[key] = val
def output_iter(self):
# yield the txn's outputs: index, (CTxOut object) for each
assert self.vout_start is not None # must call input_iter/validate first
fd = self.fd
fd.seek(self.vout_start)
total_out = 0
tx_out = CTxOut()
for idx in range(self.num_outputs):
tx_out.deserialize(fd)
total_out += tx_out.nValue
cont = fd.tell()
yield idx, tx_out
fd.seek(cont)
if self.total_value_out is None:
self.total_value_out = total_out
else:
assert self.total_value_out == total_out
def parse_txn(self):
# Need to semi-parse in unsigned transaction.
# - learn number of ins/outs so rest of PSBT can be understood
# - also captures lots of position details
# - called right after globals section is read
fd = self.fd
old_pos = fd.tell()
fd.seek(self.txn[0])
# see serializations.py:CTransaction.deserialize()
# and BIP-144 ... we expect witness serialization, but
# don't force that
self.txn_version, marker, flags = unpack("<iBB", fd.read(6))
self.had_witness = (marker == 0 and flags != 0x0)
assert self.txn_version in {1,2}, "bad txn version"
if not self.had_witness:
# rewind back over marker+flags
fd.seek(-2, 1)
num_in = deser_compact_size(fd)
assert num_in > 0, "no ins?"
self.num_inputs = num_in
# print('self.num_inputs = {}'.format(self.num_inputs ))
# all the ins are in sequence starting at this position
self.vin_start = _skip_n_objs(fd, num_in, 'CTxIn')
# next is outputs
self.num_outputs = deser_compact_size(fd)
# print('self.num_outputs = {}'.format(self.num_outputs ))
self.vout_start = _skip_n_objs(fd, self.num_outputs, 'CTxOut')
end_pos = sum(self.txn)
# remainder is the witness data, and then the lock time
if self.had_witness:
# we'll need to come back to this pos if we
# want to read the witness data later.
self.wit_start = _skip_n_objs(fd, num_in, 'CTxInWitness')
# we are at end of outputs, and no witness data, so locktime is here
self.lock_time = unpack("<I", fd.read(4))[0]
assert fd.tell() == end_pos, 'txn read end wrong'
fd.seek(old_pos)
def input_iter(self):
# Yield each of the txn's inputs, as a tuple:
#
# (index, CTxIn)
#
# - we also capture much data about the txn on the first pass thru here
#
fd = self.fd
assert self.vin_start # call parse_txn() first!
# stream out the inputs
fd.seek(self.vin_start)
txin = CTxIn()
for idx in range(self.num_inputs):
txin.deserialize(fd)
cont = fd.tell()
yield idx, txin
fd.seek(cont)
def input_witness_iter(self):
# yield all the witness data, in order by input
if not self.had_witness:
# original txn had no witness data, so provide placeholder objs
for in_idx in range(self.num_inputs):
yield in_idx, CTxInWitness()
return
fd.seek(self.wit_start)
for idx in range(num_in):
wit = CTxInWitness()
wit.deserialize(fd)
cont = fd.tell()
yield idx, wit
fd.seek(cont)
def guess_M_of_N(self):