forked from Foundation-Devices/passport-firmware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultisig.py
1374 lines (1097 loc) · 48.2 KB
/
multisig.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.
#
# multisig.py - support code for multisig signing and p2sh in general.
#
import stash, chains, ustruct, ure, uio, sys
import trezorcrypto
import tcc
from ubinascii import hexlify as b2a_hex
from utils import bytes_to_hex_str, xfp2str, str2xfp, cleanup_deriv_path, keypath_to_str, str_to_keypath
from ux import ux_show_story, ux_confirm, ux_enter_text
from files import CardSlot, CardMissingError
from public_constants import AF_P2SH, AF_P2WSH_P2SH, AF_P2WSH, AFC_SCRIPT, MAX_PATH_DEPTH
from constants import MAX_MULTISIG_NAME_LEN
from menu import MenuSystem, MenuItem
from opcodes import OP_CHECKMULTISIG
from actions import needs_microsd
from exceptions import FatalPSBTIssue
from data_codecs.qr_type import QRType
import common
# Bitcoin limitation: max number of signatures in CHECK_MULTISIG
# - 520 byte redeem script limit <= 15*34 bytes per pubkey == 510 bytes
# - serializations of M/N in redeem scripts assume this range
MAX_SIGNERS = const(15)
# PSBT Xpub trust policies
TRUST_VERIFY = const(0)
TRUST_OFFER = const(1)
TRUST_PSBT = const(2)
class MultisigOutOfSpace(RuntimeError):
pass
def disassemble_multisig_mn(redeem_script):
# pull out just M and N from script. Simple, faster, no memory.
assert MAX_SIGNERS == 15
assert redeem_script[-1] == OP_CHECKMULTISIG, 'need CHECKMULTISIG'
M = redeem_script[0] - 80
N = redeem_script[-2] - 80
return M, N
def disassemble_multisig(redeem_script):
# Take apart a standard multisig's redeem/witness script, and return M/N and public keys
# - only for multisig scripts, not general purpose
# - expect OP_1 (pk1) (pk2) (pk3) OP_3 OP_CHECKMULTISIG for 1 of 3 case
# - returns M, N, (list of pubkeys)
# - for very unlikely/impossible asserts, dont document reason; otherwise do.
from serializations import disassemble
M, N = disassemble_multisig_mn(redeem_script)
assert 1 <= M <= N <= MAX_SIGNERS, 'M/N range'
assert len(redeem_script) == 1 + (N * 34) + 1 + 1, 'bad len'
# generator function
from utils import bytes_to_hex_str
# print('redeem_script=\n{}'.format(bytes_to_hex_str(redeem_script, 16)))
dis = disassemble(redeem_script)
# expect M value first
ex_M, opcode = next(dis)
assert ex_M == M and opcode == None, 'bad M'
# need N pubkeys
pubkeys = []
for idx in range(N):
data, opcode = next(dis)
# print('idx={} opcode={} len(data)={}'.format(idx, opcode, len(data)))
assert opcode == None and len(data) == 33, 'data'
assert data[0] == 0x02 or data[0] == 0x03, 'Y val'
pubkeys.append(data)
assert len(pubkeys) == N
# next is N value
ex_N, opcode = next(dis)
# print('N={}'.format(N))
assert ex_N == N and opcode == None, 'Wrong N: ex_N={} N={}'.format(ex_N, N)
# finally, the opcode: CHECKMULTISIG
data, opcode = next(dis)
assert opcode == OP_CHECKMULTISIG, 'Not OP_CHECKMULTISIG'
# must have reached end of script at this point
try:
next(dis)
raise AssertionError("too long")
except StopIteration:
# expected, since we're reading past end
pass
return M, N, pubkeys
def make_redeem_script(M, nodes, subkey_idx):
# take a list of BIP32 nodes, and derive Nth subkey (subkey_idx) and make
# a standard M-of-N redeem script for that. Always applies BIP67 sorting.
N = len(nodes)
assert 1 <= M <= N <= MAX_SIGNERS
pubkeys = []
for n in nodes:
copy = n.clone()
copy.derive(subkey_idx, True)
# 0x21 = 33 = len(pubkey) = OP_PUSHDATA(33)
pubkeys.append(b'\x21' + copy.public_key())
pubkeys.sort()
# serialize redeem script
pubkeys.insert(0, bytes([80 + M]))
pubkeys.append(bytes([80 + N, OP_CHECKMULTISIG]))
return b''.join(pubkeys)
class MultisigWallet:
# Capture the info we need to store long-term in order to participate in a
# multisig wallet as a co-signer.
# - can be saved to nvram
# - can be imported from a simple text file
# - can be displayed to user in a menu (and deleted)
# - required during signing to verify change outputs
# - can reconstruct any redeem script from this
# Challenges:
# - can be big, taking big % of 4k storage in nvram
# - complex object, want to have flexibility going forward
FORMAT_NAMES = [
(AF_P2SH, 'p2sh'),
(AF_P2WSH, 'p2wsh'),
(AF_P2WSH_P2SH, 'p2sh-p2wsh'), # new name
(AF_P2WSH_P2SH, 'p2wsh-p2sh'), # old name
]
def __init__(self, name, m_of_n, xpubs, id, addr_fmt=AF_P2SH, chain_type='BTC', deriv=None):
self.storage_idx = -1
self.name = name[:MAX_MULTISIG_NAME_LEN]
assert len(m_of_n) == 2
self.M, self.N = m_of_n
self.chain_type = chain_type or 'BTC'
assert len(xpubs[0]) == 3
self.xpubs = xpubs # list of (xfp(int), deriv, xpub(str))
self.id = id # Unique id to associate multisig info with an account
self.addr_fmt = addr_fmt # address format for wallet
self.my_deriv = deriv
# calc useful cache value: numeric xfp+subpath, with lookup
self.xfp_paths = {}
for xfp, deriv, _ in self.xpubs:
self.xfp_paths[xfp] = str_to_keypath(xfp, deriv)
assert len(self.xfp_paths) == self.N, 'dup XFP' # not supported
@classmethod
def render_addr_fmt(cls, addr_fmt):
for k, v in cls.FORMAT_NAMES:
if k == addr_fmt:
return v.upper()
return '?'
@property
def chain(self):
return chains.get_chain(self.chain_type)
@classmethod
def get_trust_policy(cls):
from common import settings
which = settings.get('multisig_policy', None)
if which is None:
which = TRUST_VERIFY if cls.exists() else TRUST_OFFER
return which
def serialize(self):
# return a JSON-able object
from common import noise
from noise_source import NoiseSource
opts = dict()
if self.addr_fmt != AF_P2SH:
opts['ft'] = self.addr_fmt
if self.chain_type != 'BTC':
opts['ch'] = self.chain_type
# Data compression: most legs will all use same derivation.
# put a int(0) in place and set option 'pp' to be derivation
# (used to be common_prefix assumption)
pp = list(sorted(set(d for _,d,_ in self.xpubs)))
if len(pp) == 1:
# generate old-format data, to preserve firmware downgrade path
xp = [(a, c) for a,deriv,c in self.xpubs]
opts['pp'] = pp[0]
else:
# allow for distinct deriv paths on each leg
opts['d'] = pp
xp = [(a, pp.index(deriv),c) for a,deriv,c in self.xpubs]
return (self.name, (self.M, self.N), xp, opts, self.id, self.my_deriv)
@classmethod
def deserialize(cls, vals, idx=-1):
# take json object, make instance.
name, m_of_n, xpubs, opts, id, deriv = vals
# TODO: This looks like CC legacy code - we can probably remove
if len(xpubs[0]) == 2:
# promote from old format to new: assume common prefix is the derivation
# for all of them
# PROBLEM: we don't have enough info if no common prefix can be assumed
common_prefix = opts.get('pp', None)
if not common_prefix:
# TODO: this should raise a warning, not supported anymore
common_prefix = 'm'
xpubs = [(a, common_prefix, b) for a,b in xpubs]
else:
# new format decompression
if 'd' in opts:
derivs = opts.get('d', None)
xpubs = [(a, derivs[b], c) for a,b,c in xpubs]
rv = cls(name, m_of_n, xpubs, id, addr_fmt=opts.get('ft', AF_P2SH),
chain_type=opts.get('ch', 'BTC'), deriv=deriv)
rv.storage_idx = idx
return rv
@classmethod
def iter_wallets(cls, M=None, N=None, not_idx=None, addr_fmt=None):
# yield MS wallets we know about, that match at least right M,N if known.
# - this is only place we should be searching this list, please!!
from common import settings
lst = settings.get('multisig', [])
for idx, rec in enumerate(lst):
if idx == not_idx:
# ignore one by index
continue
if M or N:
# peek at M/N
has_m, has_n = tuple(rec[1])
if M is not None and has_m != M: continue
if N is not None and has_n != N: continue
if addr_fmt is not None:
opts = rec[3]
af = opts.get('ft', AF_P2SH)
if af != addr_fmt: continue
yield cls.deserialize(rec, idx)
def get_xfp_paths(self):
# return list of lists [xfp, *deriv]
return list(self.xfp_paths.values())
@classmethod
def find_match(cls, M, N, xfp_paths, addr_fmt=None):
# Find index of matching wallet
# - xfp_paths is list of lists: [xfp, *path] like in psbt files
# - M and N must be known
# - returns instance, or None if not found
for rv in cls.iter_wallets(M, N, addr_fmt=addr_fmt):
if rv.matching_subpaths(xfp_paths):
return rv
return None
@classmethod
def find_candidates(cls, xfp_paths, addr_fmt=None, M=None):
# Return a list of matching wallets for various M values.
# - xpfs_paths hsould already be sorted
# - returns set of matches, of any M value
# we know N, but not M at this point.
N = len(xfp_paths)
matches = []
for rv in cls.iter_wallets(M=M, addr_fmt=addr_fmt):
if rv.matching_subpaths(xfp_paths):
matches.append(rv)
return matches
def matching_subpaths(self, xfp_paths):
# Does this wallet use same set of xfp values, and
# the same prefix path per-each xfp, as indicated
# xfp_paths (unordered)?
# - could also check non-prefix part is all non-hardened
for x in xfp_paths:
if x[0] not in self.xfp_paths:
return False
prefix = self.xfp_paths[x[0]]
if len(x) < len(prefix):
# PSBT specs a path shorter than wallet's xpub
#print('path len: %d vs %d' % (len(prefix), len(x)))
return False
comm = len(prefix)
if tuple(prefix[:comm]) != tuple(x[:comm]):
# xfp => maps to wrong path
#print('path mismatch:\n%r\n%r\ncomm=%d' % (prefix[:comm], x[:comm], comm))
return False
return True
def assert_matching(self, M, N, xfp_paths):
# compare in-memory wallet with details recovered from PSBT
# - xfp_paths must be sorted already
assert (self.M, self.N) == (M, N), "M/N mismatch"
assert len(xfp_paths) == N, "XFP count"
assert self.matching_subpaths(xfp_paths), "wrong XFP/derivs"
@classmethod
def quick_check(cls, M, N, xfp_xor):
# quicker? USB method.
rv = []
for ms in cls.iter_wallets(M, N):
x = 0
for xfp in ms.xfp_paths.keys():
x ^= xfp
if x != xfp_xor: continue
return True
return False
@classmethod
def get_all(cls):
# return them all, as a generator
return cls.iter_wallets()
@classmethod
def exists(cls):
# are there any wallets defined?
from common import settings
return bool(settings.get('multisig', False))
@classmethod
def get_count(cls):
from common import settings
lst = settings.get('multisig', [])
return len(lst)
@classmethod
def get_by_idx(cls, nth):
# instance from index number (used in menu)
from common import settings
lst = settings.get('multisig', [])
try:
obj = lst[nth]
except IndexError:
return None
return cls.deserialize(obj, nth)
@classmethod
def get_by_id(cls, id):
# instance from unique id
from common import settings
lst = settings.get('multisig', [])
# print('get_by_id(): settings.multisig={}'.format(lst))
for idx, v in enumerate(lst):
if v[4] == id:
return cls.deserialize(v, idx)
return None
@classmethod
def delete_by_id(cls, id):
from utils import to_str
from common import settings
lst = settings.get('multisig', [])
# print('delete_by_id(): BEFORE: settings.multisig={}'.format(to_str(lst)))
for idx, v in enumerate(lst):
if v[4] == id:
del lst[idx]
# print('delete_by_id(): AFTER: settings.multisig={}'.format(to_str(lst)))
settings.set('multisig', lst)
# Assumes caller will call save if it's important to do immediately
# We do this as part of updating 'accounts' too, so we only want one save call.
async def commit(self):
# data to save
# - important that this fails immediately when nvram overflows
from common import settings
from export import auto_backup
obj = self.serialize()
v = settings.get('multisig', [])
orig = v.copy()
if not v or self.storage_idx == -1:
# create
self.storage_idx = len(v)
v.append(obj)
else:
# update in place
v[self.storage_idx] = obj
settings.set('multisig', v)
# Hacky way to communicate back to the New Account flow
common.new_multisig_wallet = self
# print('new_multisig_wallet={}'.format(self))
# save now, rather than in background, so we can recover
# from out-of-space situation
try:
await settings.save()
except:
# back out change; no longer sure of NVRAM state
try:
settings.set('multisig', orig)
await settings.save()
# Shouldn't need to do this since we are going back to the previous values
# await auto_backup()
except:
pass # give up on recovery
raise MultisigOutOfSpace
def has_similar(self):
# check if we already have a saved duplicate to this proposed wallet
# - return (name_change, diff_items, count_similar) where:
# - name_change is existing wallet that has exact match, different name
# - diff_items: text list of similarity/differences
# - count_similar: same N, same xfp+paths
lst = self.get_xfp_paths()
c = self.find_match(self.M, self.N, lst, addr_fmt=self.addr_fmt)
if c:
# All details are same: M/N, paths, addr fmt
if self.xpubs != c.xpubs:
return None, ['xpubs'], 0
elif self.name == c.name:
return None, [], 1
else:
return c, ['name'], 0
similar = MultisigWallet.find_candidates(lst)
if not similar:
# no matches, good.
return None, [], 0
# See if the xpubs are changing, which is risky... other differences like
# name are okay.
diffs = set()
name_diff = None
for c in similar:
if c.M != self.M:
diffs.add('M differs')
if c.addr_fmt != self.addr_fmt:
diffs.add('address type')
if c.name != self.name:
diffs.add('name')
if c.xpubs != self.xpubs:
diffs.add('xpubs')
return None, diffs, len(similar)
async def rename(self, new_name):
from common import settings
from export import auto_backup
# safety check
existing = self.find_match(self.M, self.N, self.get_xfp_paths())
assert existing
assert existing.storage_idx == self.storage_idx
new_name = new_name[:MAX_MULTISIG_NAME_LEN]
lst = settings.get('multisig', [])
self.name = new_name
# Can't modify tuple in place to make it a list, modify, then make a new tuple
w = lst[self.storage_idx]
w = list(w)
w[0] = new_name
w = tuple(w)
lst[self.storage_idx] = w
settings.set('multisig', lst)
await settings.save()
await auto_backup()
self.storage_idx = -1
async def delete(self):
# remove saved entry
# - important: not expecting more than one instance of this class in memory
from common import settings
from export import auto_backup
assert self.storage_idx >= 0
# safety check
existing = self.find_match(self.M, self.N, self.get_xfp_paths())
assert existing
assert existing.storage_idx == self.storage_idx
lst = settings.get('multisig', [])
del lst[self.storage_idx]
settings.set('multisig', lst)
await settings.save()
await auto_backup()
self.storage_idx = -1
def xpubs_with_xfp(self, xfp):
# return set of indexes of xpubs with indicated xfp
return set(xp_idx for xp_idx, (wxfp, _, _) in enumerate(self.xpubs)
if wxfp == xfp)
def yield_addresses(self, start_idx, count, change_idx=0):
# Assuming a suffix of /0/0 on the defined prefix's, yield
# possible deposit addresses for this wallet. Never show
# user the resulting addresses because we cannot be certain
# they are valid and could be signed. And yet, dont blank too many
# spots or else an attacker could grid out a suitable replacement.
ch = self.chain
assert self.addr_fmt, 'no addr fmt known'
# setup
nodes = []
paths = []
for xfp, deriv, xpub in self.xpubs:
# print('xfp={}'.format(xfp))
# print('deriv={}'.format(deriv))
# print('xpub={}'.format(xpub))
# load bip32 node for each cosigner, derive /0/ based on change idx
node = ch.deserialize_node(xpub, AF_P2SH)
node.derive(change_idx, True)
nodes.append(node)
# indicate path used (for UX)
path = "(m=%s)/%s/%d/{idx}" % (xfp2str(xfp), deriv, change_idx)
paths.append(path)
idx = start_idx
while count:
# make the redeem script, convert into address
script = make_redeem_script(self.M, nodes, idx) # idx is the address index
addr = ch.p2sh_address(self.addr_fmt, script)
# addr = addr[0:12] + '___' + addr[12+3:]
yield idx, [p.format(idx=idx) for p in paths], addr, script
idx += 1
count -= 1
def validate_script(self, redeem_script, subpaths=None, xfp_paths=None):
# Check we can generate all pubkeys in the redeem script, raise on errors.
# - working from pubkeys in the script, because duplicate XFP can happen
#
# redeem_script: what we expect and we were given
# subpaths: pubkey => (xfp, *path)
# xfp_paths: (xfp, *path) in same order as pubkeys in redeem script
subpath_help = []
used = set()
ch = self.chain
M, N, pubkeys = disassemble_multisig(redeem_script)
assert M==self.M and N == self.N, 'wrong M/N in script'
for pk_order, pubkey in enumerate(pubkeys):
check_these = []
if subpaths:
# in PSBT, we are given a map from pubkey to xfp/path, use it
# while remembering it's potentially one-2-many
# TODO: this could be simpler now
assert pubkey in subpaths, "unexpected pubkey"
xfp, *path = subpaths[pubkey]
for xp_idx, (wxfp, _, xpub) in enumerate(self.xpubs):
if wxfp != xfp: continue
if xp_idx in used: continue # only allow once
check_these.append((xp_idx, path))
else:
# Without PSBT, USB caller must provide xfp+path
# in same order as they occur inside redeem script.
# Working solely from the redeem script's pubkeys, we
# wouldn't know which xpub to use, nor correct path for it.
xfp, *path = xfp_paths[pk_order]
for xp_idx in self.xpubs_with_xfp(xfp):
if xp_idx in used: continue # only allow once
check_these.append((xp_idx, path))
here = None
too_shallow = False
for xp_idx, path in check_these:
# matched fingerprint, try to make pubkey that needs to match
# print('xpubs={}'.format(self.xpubs))
xpub = self.xpubs[xp_idx][-1]
node = ch.deserialize_node(xpub, AF_P2SH); assert node
dp = node.depth()
#print("%s => deriv=%s dp=%d len(path)=%d path=%s" %
# (xfp2str(xfp), self.xpubs[xp_idx][1], dp, len(path), path))
if not (0 <= dp <= len(path)):
# obscure case: xpub isn't deep enough to represent
# indicated path... not wrong really.
too_shallow = True
continue
for sp in path[dp:]:
assert not (sp & 0x80000000), 'hard deriv'
node.derive(sp, True) # works in-place
found_pk = node.public_key()
# Document path(s) used. Not sure this is useful info to user tho.
# - Do not show what we can't verify: we don't really know the hardeneded
# part of the path from fingerprint to here.
here = '(m=%s)\n' % xfp2str(xfp)
if dp != len(path):
here += 'm' + ('/_'*dp) + keypath_to_str(path[dp:], '/', 0)
if found_pk != pubkey:
# Not a match but not an error by itself, since might be
# another dup xfp to look at still.
#print('pk mismatch: %s => %s != %s' % (
# here, b2a_hex(found_pk), b2a_hex(pubkey)))
continue
subpath_help.append(here)
used.add(xp_idx)
break
else:
msg = 'pk#%d wrong' % (pk_order+1)
if not check_these:
msg += ', unknown XFP'
elif here:
msg += ', tried: ' + here
if too_shallow:
msg += ', too shallow'
raise AssertionError(msg)
if pk_order:
# verify sorted order
assert bytes(pubkey) > bytes(pubkeys[pk_order-1]), 'BIP67 violation'
assert len(used) == self.N, 'not all keys used: %d of %d' % (len(used), self.N)
return subpath_help
@classmethod
def from_file(cls, config, name=None):
# Given a simple text file, parse contents and create instance (unsaved).
# format is: label: value
# where label is:
# name: nameforwallet
# policy: M of N
# format: p2sh (+etc)
# derivation: m/45'/0 (common prefix)
# (8digithex): xpub of cosigner
#
# quick checks:
# - name: 1-20 ascii chars
# - M of N line (assume N of N if not spec'd)
# - xpub: any bip32 serialization we understand, but be consistent
#
from common import settings
my_xfp = settings.get('xfp')
deriv = None
xpubs = []
M, N = -1, -1
has_mine = 0
addr_fmt = AF_P2SH
my_deriv = None
expect_chain = chains.current_chain().ctype
lines = config.split('\n')
for ln in lines:
# remove comments
comm = ln.find('#')
if comm == 0:
if ':' in ln: # Could be a derivation path in a comment
# Strip off the comment and let the line get trimmed/parsed below
ln = ln[1:]
else:
continue
elif comm != -1:
if not ln[comm+1:comm+2].isdigit():
ln = ln[0:comm]
ln = ln.strip()
if ':' not in ln:
if 'pub' in ln:
# pointless optimization: allow bare xpub if we can calc xfp
label = '0'*8
value = ln
else:
# complain?
#if ln: print("no colon: " + ln)
continue
else:
label, value = ln.split(':', 1)
label = label.lower()
value = value.strip()
if label == 'name':
name = value
elif label == 'policy':
try:
# accepts: 2 of 3 2/3 2,3 2 3 etc
mat = ure.search(r'(\d+)\D*(\d+)', value)
assert mat
M = int(mat.group(1))
N = int(mat.group(2))
assert 1 <= M <= N <= MAX_SIGNERS
except:
raise AssertionError('bad policy line')
elif label == 'derivation':
# reveal the path derivation for following key(s)
try:
assert value, 'blank'
deriv = cleanup_deriv_path(value)
except BaseException as exc:
raise AssertionError('bad derivation line: ' + str(exc))
elif label == 'format':
# pick segwit vs. classic vs. wrapped version
value = value.lower()
for fmt_code, fmt_label in cls.FORMAT_NAMES:
if value == fmt_label:
addr_fmt = fmt_code
break
else:
raise AssertionError('bad format line')
elif len(label) == 8:
try:
xfp = str2xfp(label)
except:
# complain?
#print("Bad xfp: " + ln)
continue
# deserialize, update list and lots of checks
is_mine = cls.check_xpub(xfp, value, deriv, expect_chain, my_xfp, xpubs)
if is_mine:
# HACK: We need to know which deriv path is for our XPUB when creating a new account
# This is ugly, but avoids
my_deriv = deriv # Use the last-parsed (pattern is Derivation, then XFP: XPUB
has_mine += 1
assert len(xpubs), 'No XPUBS found.'
if M == N == -1:
# default policy: all keys
N = M = len(xpubs)
if not name:
# provide a default name
name = '%d-of-%d' % (M, N)
try:
name = str(name, 'ascii')
name = name[:MAX_MULTISIG_NAME_LEN]
except:
raise AssertionError('Name must be ASCII, and 1 to 20 characters long.')
assert 1 <= M <= N <= MAX_SIGNERS, 'M/N range'
assert N == len(xpubs), 'wrong # of xpubs, expect %d' % N
assert addr_fmt & AFC_SCRIPT, 'script style addr fmt'
# check we're included... do not insert ourselves, even tho we
# have enough info, simply because other signers need to know my xpubkey anyway
assert has_mine != 0, 'File does not include a key owned by this Passport'
assert has_mine == 1 # 'my key included more than once'
from common import noise
from noise_source import NoiseSource
# Hacky way to give the wallet a unique ID and pass it back to the New Account flow for correlation
unique_id = bytearray(8)
noise.random_bytes(unique_id, NoiseSource.MCU)
unique_id = b2a_hex(unique_id).decode('utf-8')
# done. have all the parts
return cls(name, (M, N), xpubs, unique_id, addr_fmt=addr_fmt, chain_type=expect_chain, deriv=my_deriv)
@classmethod
def check_xpub(cls, xfp, xpub, deriv, expect_chain, my_xfp, xpubs):
# Shared code: consider an xpub for inclusion into a wallet, if ok, append
# to list: xpubs with a tuple: (xfp, deriv, xpub)
# return T if it's our own key
# - deriv can be None, and in very limited cases can recover derivation path
# - could enforce all same depth, and/or all depth >= 1, but
# seems like more restrictive than needed, so "m" is allowed
try:
# Note: addr fmt detected here via SLIP-132 isn't useful
node, txn_chain, _ = import_xpub(xpub)
except:
raise AssertionError('unable to parse xpub')
# print('node={}'.format(node))
# print('node.private_key()={}'.format(node.private_key()))
# print('xfp={}'.format(xfp))
# print('xpub={}'.format(xpub))
# print('expect_chain={}'.format(expect_chain))
# print('txn_chain.ctype={}'.format(txn_chain.ctype))
# print('my_xfp={}'.format(my_xfp))
# print('xpubs={}'.format(xpubs))
# assert node.private_key() == None # 'no privkeys plz'
# Check that they are on the right chain
if txn_chain.ctype != expect_chain:
device_chain_name = 'Mainnet' if expect_chain == 'BTC' else 'Testnet'
txn_chain_name = 'Mainnet' if txn_chain.ctype == 'BTC' else 'Testnet'
raise FatalPSBTIssue('Attempting to sign a {} transaction on {}.'.format(
txn_chain_name, device_chain_name))
depth = node.depth()
if depth == 1:
if not xfp:
# allow a shortcut: zero/omit xfp => use observed parent value
xfp = node.fingerprint()
else:
# generally cannot check fingerprint values, but if we can, do so.
assert node.fingerprint() == xfp, 'xfp depth=1 wrong'
assert xfp, 'need fingerprint' # happens if bare xpub given
# In most cases, we cannot verify the derivation path because it's hardened
# and we know none of the private keys involved.
if depth == 1:
# but derivation is implied at depth==1
guess = keypath_to_str([node.child_num()], skip=0)
if deriv:
assert guess == deriv, '%s != %s' % (guess, deriv)
else:
deriv = guess # reachable? doubt it
assert deriv, 'empty deriv' # or force to be 'm'?
assert deriv[0] == 'm'
# path length of derivation given needs to match xpub's depth
p_len = deriv.count('/')
assert p_len == depth, 'deriv %d != %d xpub depth (xfp=%s)' % (
p_len, depth, xfp2str(xfp))
if xfp == my_xfp:
# its supposed to be my key, so I should be able to generate pubkey
# - might indicate collision on xfp value between co-signers,
# and that's not supported
with stash.SensitiveValues() as sv:
chk_node = sv.derive_path(deriv)
assert node.public_key() == chk_node.public_key(), \
"(m=%s)/%s wrong pubkey" % (xfp2str(xfp), deriv[2:])
# serialize xpub w/ BIP32 standard now.
# - this has effect of stripping SLIP-132 confusion away
xpubs.append((xfp, deriv, txn_chain.serialize_public(node, AF_P2SH)))
return (xfp == my_xfp)
def make_fname(self, prefix, suffix='txt'):
rv = '%s-%s.%s' % (prefix, self.name, suffix)
return rv.replace(' ', '_')
async def export_electrum(self):
# Generate and save an Electrum JSON file.
from export import make_json_wallet
def doit():
rv = dict(seed_version=17, use_encryption=False,
wallet_type='%dof%d' % (self.M, self.N))
ch = self.chain
# the important stuff.
for idx, (xfp, deriv, xpub) in enumerate(self.xpubs):
node = None
if self.addr_fmt != AF_P2SH:
# CHALLENGE: we must do slip-132 format [yz]pubs here when not p2sh mode.
node = ch.deserialize_node(xpub, AF_P2SH); assert node
xp = ch.serialize_public(node, self.addr_fmt)
else:
xp = xpub
rv['x%d/' % (idx+1)] = dict(
hw_type='passport', type='hardware',
ckcc_xfp=xfp,
label='Passport %s' % xfp2str(xfp),
derivation=deriv, xpub=xp)
return rv
await make_json_wallet('Electrum multisig wallet', doit,
fname_pattern=self.make_fname('el', 'json'))
async def export_wallet_file(self, mode="exported from", extra_msg=None):
# create a text file with the details; ready for import to next Coldcard
from common import settings
my_xfp = xfp2str(settings.get('xfp'))
fname_pattern = self.make_fname('export')
try:
with CardSlot() as card:
fname, nice = card.pick_filename(fname_pattern)
# do actual write
with open(fname, 'wt') as fp:
# print("# Passport Multisig setup file (%s %s)\n#" % (mode, my_xfp), file=fp)
self.render_export(fp)
msg = '''Passport multisig setup file written:\n\n%s''' % nice
if extra_msg:
msg += extra_msg
await ux_show_story(msg)
except CardMissingError:
await needs_microsd()
return
except Exception as e:
await ux_show_story('Unable to write!\n\n\n'+str(e))
return
def render_export(self, fp):
# print("Name: %s\nPolicy: %d of %d" % (self.name, self.M, self.N), file=fp)
if self.addr_fmt != AF_P2SH:
pass
# print("Format: " + self.render_addr_fmt(self.addr_fmt), file=fp)
last_deriv = None
for xfp, deriv, val in self.xpubs:
if last_deriv != deriv:
# print("\nDerivation: %s\n" % deriv, file=fp)
last_deriv = deriv
# print('%s: %s' % (xfp2str(xfp), val), file=fp)
@classmethod
def guess_addr_fmt(cls, npath):
# Assuming the bips are being respected, what address format will be used,
# based on indicated numeric subkey path observed.
# - return None if unsure, no errors
#
#( "m/45'", 'p2sh', AF_P2SH),
#( "m/48'/{coin}'/0'/1'", 'p2sh_p2wsh', AF_P2WSH_P2SH),
#( "m/48'/{coin}'/0'/2'", 'p2wsh', AF_P2WSH)
top = npath[0] & 0x7fffffff
if top == npath[0]:
# non-hardened top? rare/bad
return
if top == 45:
return AF_P2SH
if top == 48:
if len(npath) < 4: return
last = npath[3] & 0x7fffffff
if last == 1:
return AF_P2WSH_P2SH
if last == 2:
return AF_P2WSH
@classmethod
def import_from_psbt(cls, M, N, xpubs_list):
# given the raw data for PSBT global header, offer the user
# the details, and/or bypass that all and just trust the data.
# - xpubs_list is a list of (xfp+path, binary BIP32 xpub)
# - already know not in our records.
from common import settings