-
Notifications
You must be signed in to change notification settings - Fork 10
/
utils.py
1564 lines (1200 loc) · 42.3 KB
/
utils.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.
#
# utils.py
#
import lvgl as lv
from constants import NUM_BACKUP_CODE_SECTIONS, NUM_DIGITS_PER_BACKUP_CODE_SECTION
from public_constants import DIR_BACKUPS, MUSIG_DEFAULT, MUSIG_TEMP_DEFAULT
from files import CardSlot
from styles.colors import DEFAULT_LARGE_ICON_COLOR
import ustruct
import uos
import trezorcrypto
import stash
from ubinascii import hexlify as b2a_hex
from ubinascii import unhexlify as a2b_hex
from ubinascii import a2b_base64, b2a_base64
from uasyncio import get_event_loop, sleep_ms
import common
import passport
ENABLE_LOGGING = True
def log(*args, **kwargs):
global ENABLE_LOGGING
if ENABLE_LOGGING:
print(*args, **kwargs)
def read_user_firmware_pubkey():
from common import system
pubkey = bytearray(64)
result = system.get_user_firmware_pubkey(pubkey)
return result, pubkey
# We cache this here to avoid slowing down the menus, since the menu items in the Developer Pubkey
# menu look up this value to decide when to become visible/hidden.
def has_dev_pubkey():
if common.cached_pubkey is None:
result, common.cached_pubkey = read_user_firmware_pubkey()
if not result:
return False
return not is_all_zero(common.cached_pubkey)
def clear_cached_pubkey():
common.cached_pubkey = None
def is_all_zero(buf):
for b in buf:
if b != 0:
return False
return True
def time_now_ms():
import utime
return utime.ticks_ms()
# Lookup version number from header
def get_fw_version():
# TODO: Implement version number function
return '2020-08-30', '0.1.0', '???'
def start_task(task):
loop = get_event_loop()
return loop.create_task(task)
async def spinner_task(text, task, args=(), left_micron=None, right_micron=None, min_duration_ms=1000, no_anim=False):
from pages import SpinnerPage, StatusPage
from uasyncio import sleep_ms
from utime import ticks_ms
from common import ui
# Disable left/right navigation and icons
prev_top_level = ui.set_is_top_level(False)
start_time = ticks_ms()
if no_anim:
spinner = StatusPage(text, left_micron=left_micron, right_micron=right_micron,
icon=lv.LARGE_ICON_STATIC_PIN_SPINNER, icon_color=DEFAULT_LARGE_ICON_COLOR)
else:
spinner = SpinnerPage(text, left_micron=left_micron, right_micron=right_micron)
task_result = None
# User can pass a variable number of arguments, which we return as the result
async def on_done(*args):
# print('on_done() args="{}"'.format(args))
nonlocal task_result
task_result = args
# The last arg is always the error
error = args[-1] if len(args) > 0 else None
# Enforce minimum delay so that the message is at least briefly seed
end_time = ticks_ms()
if end_time - start_time < min_duration_ms:
await sleep_ms(min_duration_ms - (end_time - start_time))
ui.set_is_top_level(prev_top_level)
spinner.set_result(error is None)
start_task(task(on_done, *args))
# Can handle the user pressing a key here by just showing the spinner again
while True:
await spinner.show()
if task_result is not None:
break
return task_result
def call_later_ms(delay_ms, coro):
async def delay_fn():
await sleep_ms(delay_ms)
await coro
loop = get_event_loop()
loop.create_task(delay_fn())
def save_error_log(msg, filename):
from files import CardSlot
wrote_to_sd = False
try:
with CardSlot() as card:
# Full path and short filename
fname, _ = card.get_file_path(filename)
with open(fname, 'wb') as fd:
fd.write(msg)
wrote_to_sd = True
except Exception:
return wrote_to_sd
return wrote_to_sd
async def save_error_log_to_microsd_task(msg, filename):
import common
sd_card_change = False
def sd_card_cb():
nonlocal sd_card_change
if not sd_card_change:
sd_card_change = True
# Activate SD card hook
CardSlot.set_sd_card_change_cb(sd_card_cb)
while True:
if sd_card_change:
sd_card_change = False
saved = save_error_log(msg, filename)
if saved:
common.ui.set_card_header(title='Saved to microSD', icon='ICON_MICROSD')
await sleep_ms(100)
def handle_fatal_error(exc):
import common
from styles.colors import BLACK
from pages import LongTextPage
from flows import PageFlow
import microns
from tasks import card_task
import sys
sys.print_exception(exc)
# if isinstance(exc, KeyboardInterrupt):
# # preserve GUI state, but want to see where we are
# print("KeyboardInterrupt")
# raise
if isinstance(exc, SystemExit):
# Ctrl-D and warm reboot cause this, not bugs
raise
else:
print("Exception:")
# show stacktrace for debug photos
try:
import uio
tmp = uio.StringIO()
sys.print_exception(exc, tmp)
msg = tmp.getvalue()
del tmp
print('===============================================================')
print(msg)
print('===============================================================')
filename = 'error.log'
saved = save_error_log(msg, filename)
# Switch immediately to a new card to show the error
fatal_error_card = {
'statusbar': {'title': 'FATAL ERROR', 'icon': 'ICON_INFO'},
'page_micron': microns.PageDot,
'bg_color': BLACK,
'flow': PageFlow,
'args': {'args': {'page_class': LongTextPage, 'text': msg,
'left_micron': None, 'right_micron': None}}
}
common.ui.set_cards([fatal_error_card])
if saved:
common.ui.set_card_header(title='Saved to microSD', icon='ICON_MICROSD')
else:
common.ui.set_card_header(title='Insert microSD', icon='ICON_MICROSD')
loop = get_event_loop()
_fatal_card_task = loop.create_task(card_task(fatal_error_card))
_microsd_task = loop.create_task(save_error_log_to_microsd_task(msg, filename))
except Exception as exc2:
sys.print_exception(exc2)
def get_file_list(path=None, include_folders=False, include_parent=False,
suffix=None, filter_fn=None, show_hidden=False):
file_list = []
with CardSlot() as card:
if path is None:
path = card.get_sd_root()
# Ensure path is build properly
if not path.startswith(card.get_sd_root()):
# print('ERROR: The path for get_file_list() must start with "{}"'.format(card.get_sd_root()))
return []
# Make sure this path exists and that it is a folder
if not folder_exists(path):
# print('ERROR: The path "{}" does not exist'.format(path))
return []
files = uos.ilistdir(path)
for filename, file_type, *var in files:
# print("filename={} file_type={} var={} suffix={}".format(filename, file_type, var, suffix))
# Don't include folders if requested
is_folder = file_type == 0x4000
if not include_folders and is_folder:
continue
# Skip files with the wrong suffix
if not is_folder and suffix is not None and not filename.lower().endswith(suffix):
continue
# Skip "hidden" files that start with "."
if filename[0] == '.' and not show_hidden:
continue
# Apply file filter, if given (only to files -- folder are included by default)
if not is_folder and filter_fn is not None and not filter_fn(filename, path):
continue
full_path = "{}/{}".format(path, filename)
file_list.append((filename, full_path, is_folder))
return file_list
def delete_file(path):
with CardSlot() as card:
if path is None:
return
# Ensure path is build properly
if not path.startswith(card.get_sd_root()):
# print('ERROR: The path for get_file_list() must start with "{}"'.format(card.get_sd_root()))
return
if folder_exists(path):
uos.rmdir(path)
if file_exists(path):
uos.remove(path)
class InputMode():
UPPER_ALPHA = 0
LOWER_ALPHA = 1
NUMERIC = 2
PUNCTUATION = 3
@ classmethod
def to_str(cls, mode):
if mode == InputMode.UPPER_ALPHA:
return 'A-Z'
elif mode == InputMode.LOWER_ALPHA:
return 'a-z'
elif mode == InputMode.NUMERIC:
return '0-9'
elif mode == InputMode.PUNCTUATION:
return '&$?'
else:
return ''
@ classmethod
def cycle_to_next(cls, mode):
if mode == InputMode.NUMERIC:
return InputMode.LOWER_ALPHA
elif mode == InputMode.LOWER_ALPHA:
return InputMode.UPPER_ALPHA
else:
return InputMode.NUMERIC
@ classmethod
def get_icon(cls, mode):
if mode == InputMode.UPPER_ALPHA:
return lv.ICON_INPUT_MODE_UPPER_ALPHA
elif mode == InputMode.LOWER_ALPHA:
return lv.ICON_INPUT_MODE_LOWER_ALPHA
elif mode == InputMode.NUMERIC:
return lv.ICON_INPUT_MODE_NUMERIC
elif mode == InputMode.PUNCTUATION:
return lv.ICON_INPUT_MODE_PUNCTUATION
def B2A(x):
return str(b2a_hex(x), 'ascii')
# class imported:
# # Context manager that temporarily imports
# # a list of modules.
# # LATER: doubtful this saves any memory when all the code is frozen.
#
# def __init__(self, *modules):
# self.modules = modules
#
# def __enter__(self):
# # import everything required
# rv = tuple(__import__(n) for n in self.modules)
#
# return rv[0] if len(self.modules) == 1 else rv
#
# def __exit__(self, exc_type, exc_value, traceback):
#
# for n in self.modules:
# if n in sys.modules:
# del sys.modules[n]
#
# # recovery that tasty memory.
# gc.collect()
#
#
# def pretty_delay(n):
# # decode # of seconds into various ranges, need not be precise.
# if n < 120:
# return '%d seconds' % n
# n /= 60
# if n < 60:
# return '%d minutes' % n
# n /= 60
# if n < 48:
# return '%.1f hours' % n
# n /= 24
# return 'about %d days' % n
#
#
# def pretty_short_delay(sec):
# # precise, shorter on screen display
# if sec >= 3600:
# return '%2dh %2dm %2ds' % (sec // 3600, (sec//60) % 60, sec % 60)
# else:
# return '%2dm %2ds' % ((sec//60) % 60, sec % 60)
#
#
# def pop_count(i):
# # 32-bit population count for integers
# # from <https://stackoverflow.com/questions/9829578>
# i = i - ((i >> 1) & 0x55555555)
# i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
#
# return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24
def get_filesize(fn):
# like os.path.getsize()
import uos
return uos.stat(fn)[6]
# def is_dir(fn):
# from stat import S_ISDIR
# import uos
# mode = uos.stat(fn)[0]
# # print('is_dir() mode={}'.format(mode))
# return S_ISDIR(mode)
class HexWriter:
# Emulate a file/stream but convert binary to hex as they write
def __init__(self, fd):
self.fd = fd
self.pos = 0
self.checksum = trezorcrypto.sha256()
def __enter__(self):
self.fd.__enter__()
return self
def __exit__(self, *a, **k):
self.fd.seek(0, 3) # go to end
self.fd.write(b'\r\n')
return self.fd.__exit__(*a, **k)
def tell(self):
return self.pos
def write(self, b):
self.checksum.update(b)
self.pos += len(b)
self.fd.write(b2a_hex(b))
def seek(self, offset, whence=0):
assert whence == 0 # limited support
self.pos = offset
self.fd.seek((2 * offset), 0)
def read(self, ll):
b = self.fd.read(ll * 2)
if not b:
return b
assert len(b) % 2 == 0
self.pos += len(b) // 2
return a2b_hex(b)
def readinto(self, buf):
b = self.read(len(buf))
buf[0:len(b)] = b
return len(b)
def getvalue(self):
return self.fd.getvalue()
class Base64Writer:
# Emulate a file/stream but convert binary to Base64 as they write
def __init__(self, fd):
self.fd = fd
self.runt = b''
def __enter__(self):
self.fd.__enter__()
return self
def __exit__(self, *a, **k):
if self.runt:
self.fd.write(b2a_base64(self.runt))
self.fd.write(b'\r\n')
return self.fd.__exit__(*a, **k)
def write(self, buf):
if self.runt:
buf = self.runt + buf
rl = len(buf) % 3
self.runt = buf[-rl:] if rl else b''
if rl < len(buf):
tmp = b2a_base64(buf[:(-rl if rl else None)])
# library puts in newlines!?
assert tmp[-1:] == b'\n', tmp
assert tmp[-2:-1] != b'=', tmp
self.fd.write(tmp[:-1])
def getvalue(self):
return self.fd.getvalue()
def swab32(n):
# endian swap: 32 bits
return ustruct.unpack('>I', ustruct.pack('<I', n))[0]
def xfp2str(xfp):
# Standardized way to show an xpub's fingerprint... it's a 4-byte string
# and not really an integer. Used to show as '0x%08x' but that's wrong endian.
return b2a_hex(ustruct.pack('<I', xfp)).decode().upper()
def str2xfp(txt):
# Inverse of xfp2str
return ustruct.unpack('<I', a2b_hex(txt))[0]
# def problem_file_line(exc):
# # return a string of just the filename.py and line number where
# # an exception occured. Best used on AssertionError.
# import uio
# import sys
# import ure
#
# tmp = uio.StringIO()
# sys.print_exception(exc, tmp)
# lines = tmp.getvalue().split('\n')[-3:]
# del tmp
#
# # convert:
# # File "main.py", line 63, in interact
# # into just:
# # main.py:63
# #
# # on simulator, huge path is included, remove that too
#
# rv = None
# for ln in lines:
# mat = ure.match(r'.*"(/.*/|)(.*)", line (.*), ', ln)
# if mat:
# try:
# rv = mat.group(2) + ':' + mat.group(3)
# except:
# pass
#
# return rv or str(exc) or 'Exception'
def cleanup_deriv_path(bin_path, allow_star=False):
# Clean-up path notation as string.
# - raise exceptions on junk
# - standardize on 'prime' notation (34' not 34p, or 34h)
# - assume 'm' prefix, so '34' becomes 'm/34', etc
# - do not assume /// is m/0/0/0
# - if allow_star, then final position can be * or *' (wildcard)
import ure
from public_constants import MAX_PATH_DEPTH
try:
s = str(bin_path, 'ascii').lower()
except UnicodeError:
raise AssertionError('must be ascii')
# empty string is valid
if s == '':
return 'm'
s = s.replace('p', "'").replace('h', "'")
mat = ure.match(r"(m|m/|)[0-9/']*" + ('' if not allow_star else r"(\*'|\*|)"), s)
assert mat.group(0) == s, "invalid characters"
parts = s.split('/')
# the m/ prefix is optional
if parts and parts[0] == 'm':
parts = parts[1:]
if not parts:
# rather than: m/
return 'm'
assert len(parts) <= MAX_PATH_DEPTH, "too deep"
for p in parts:
assert p != '' and p != "'", "empty path component"
if allow_star and '*' in p:
# - star or star' can be last only (checked by regex above)
assert p == '*' or p == "*'", "bad wildcard"
continue
if p[-1] == "'":
p = p[0:-1]
try:
ip = int(p, 10)
except Exception:
ip = -1
assert 0 <= ip < 0x80000000 and p == str(ip), "bad component: {}".format(p)
return 'm/{}'.format('/'.join(parts))
def keypath_to_str(bin_path, prefix='m/', skip=1):
# take binary path, like from a PSBT and convert into text notation
rv = prefix + '/'.join(str(i & 0x7fffffff) + ("'" if i & 0x80000000 else "")
for i in bin_path[skip:])
return 'm' if rv == 'm/' else rv
def str_to_keypath(xfp, path):
# Take a numeric xfp, and string derivation, and make a list of numbers,
# like occurs in a PSBT.
# - no error checking here
rv = [xfp]
for i in path.split('/'):
if i == 'm':
continue
if not i:
continue # trailing or duplicated slashes
if i[-1] == "'":
here = int(i[:-1]) | 0x80000000
else:
here = int(i)
rv.append(here)
return rv
# def match_deriv_path(patterns, path):
# # check for exact string match, or wildcard match (star in last position)
# # - both args must be cleaned by cleanup_deriv_path() already
# # - will accept any path, if 'any' in patterns
# if 'any' in patterns:
# return True
#
# for pat in patterns:
# if pat == path:
# return True
#
# if pat.endswith("/*") or pat.endswith("/*'"):
# if pat[-1] == "'" and path[-1] != "'":
# continue
# if pat[-1] == "*" and path[-1] == "'":
# continue
#
# # same hardness so check up to last component of path
# if pat.split('/')[:-1] == path.split('/')[:-1]:
# return True
#
# return False
class DecodeStreamer:
def __init__(self):
self.runt = bytearray()
def more(self, buf):
# Generator:
# - accumulate into mod-N groups
# - strip whitespace
for ch in buf:
if chr(ch).isspace():
continue
self.runt.append(ch)
if len(self.runt) == 128 * self.mod:
yield self.a2b(self.runt)
self.runt = bytearray()
here = len(self.runt) - (len(self.runt) % self.mod)
if here:
yield self.a2b(self.runt[0:here])
self.runt = self.runt[here:]
class HexStreamer(DecodeStreamer):
# be a generator that converts hex digits into binary
# NOTE: mpy a2b_hex doesn't care about unicode vs bytes
mod = 2
def a2b(self, x):
return a2b_hex(x)
class Base64Streamer(DecodeStreamer):
# be a generator that converts Base64 into binary
mod = 4
def a2b(self, x):
return a2b_base64(x)
def get_month_str(month):
if month == 1:
return "January"
elif month == 2:
return "February"
elif month == 3:
return "March"
elif month == 4:
return "April"
elif month == 5:
return "May"
elif month == 6:
return "June"
elif month == 7:
return "July"
elif month == 8:
return "August"
elif month == 9:
return "September"
elif month == 10:
return "October"
elif month == 11:
return "November"
elif month == 12:
return "December"
def randint(a, b):
import struct
from common import noise
buf = bytearray(4)
noise.random_bytes(buf, noise.MCU)
num = struct.unpack_from(">I", buf)[0]
result = a + (num % (b - a + 1))
return result
def bytes_to_hex_str(s):
return str(b2a_hex(s).upper(), 'ascii')
# # Pass a string pattern like 'foo-{}.txt' and the {} will be replaced by a random 4 bytes hex number
# def random_filename(card, pattern):
# buf = bytearray(4)
# common.noise.random_bytes(buf, common.noise.MCU)
# fn = pattern.format(b2a_hex(buf).decode('utf-8'))
# return '{}/{}'.format(card.get_sd_root(), fn)
#
#
# def to_json(o):
# import ujson
# s = ujson.dumps(o)
# parts = s.split(', ')
# lines = ',\n'.join(parts)
# return lines
def to_str(o):
s = '{}'.format(o)
parts = s.split(', ')
lines = ',\n'.join(parts)
return lines
def random_hex(num_chars):
import urandom
rand = bytearray((num_chars + 1) // 2)
for i in range(len(rand)):
rand[i] = urandom.randint(0, 255)
s = b2a_hex(rand).decode('utf-8').upper()
return s[:num_chars]
def recolor(color, text):
# Recolor a fragment of text
h = '{0:0{1}x}'.format(color, 6)
return '#{} {}#'.format(h, text)
# def truncate_string_to_width(name, font, max_pixel_width):
# from common import dis
# if max_pixel_width <= 0:
# # print('WARNING: Invalid max_pixel_width passed to truncate_string_to_width(). Must be > 0.')
# return name
#
# while True:
# actual_width = dis.width(name, font)
# if actual_width < max_pixel_width:
# return name
# name = name[0:-1]
#
# # The multisig import code is implemented as a menu, and we are coming from a state machine.
# # We want to be able to show the topmost menu that was pushed onto the stack here and wait for it to exit.
# # This is a hack. Side effect is that the top menu shows briefly after menu exits.
#
#
# async def show_top_menu():
# from ux import the_ux
# c = the_ux.top_of_stack()
# await c.interact()
#
# # TODO: For now this just checks the front bytes, but it could ensure the whole thing is valid
def is_valid_address(address):
import chains
chain = chains.current_chain()
if chain.ctype == 'BTC':
return (len(address) > 3) and (address[0] == '1' or address[0] == '3' or
(address[0] == 'b' and address[1] == 'c' and address[2] == '1'))
else:
return (len(address) > 3) and (address[0] == 'm' or address[0] == 'n' or address[0] == '2' or
(address[0] == 't' and address[1] == 'b' and address[2] == '1'))
# Return array of bytewords where each byte in buf maps to a word
# There are 256 bytewords, so this maps perfectly.
def get_bytewords_for_buf(buf):
from ur2.bytewords import get_word
words = []
for b in buf:
words.append(get_word(b))
return words
# # We need an async way for the chooser menu to be shown. This does a local call to interact(), which gives
# # us exactly that. Once the chooser completes, the menu stack returns to the way it was.
#
#
# async def run_chooser(chooser, title, show_checks=True):
# from ux import the_ux
# from menu import start_chooser
# start_chooser(chooser, title=title, show_checks=show_checks)
# c = the_ux.top_of_stack()
# await c.interact()
#
# # Return the elements of a list in a random order in a new list
#
#
# def shuffle(list):
# import urandom
# new_list = []
# list_len = len(list)
# while list_len > 0:
# i = urandom.randint(0, list_len-1)
# element = list.pop(i)
# new_list.append(element)
# list_len = len(list)
#
# return new_list
def ensure_folder_exists(path):
import uos
try:
# print('Creating folder: {}'.format(path))
uos.mkdir(path)
except Exception as e:
# print('Folder already exists: {}'.format(e))
return
def file_exists(path):
import os
from stat import S_ISREG
try:
s = os.stat(path)
mode = s[0]
return S_ISREG(mode)
except OSError as e:
return False
def folder_exists(path):
import os
from stat import S_ISDIR
try:
s = os.stat(path)
mode = s[0]
return S_ISDIR(mode)
except OSError as e:
return False
def get_accounts():
from common import settings
accounts = settings.get('accounts', [])
accounts.sort(key=lambda a: a.get('acct_num', 0))
return accounts
def get_accounts_by_xfp(xfp):
accounts = get_accounts()
return [acct for acct in accounts if acct.get('xfp', None) == xfp]
def get_account_by_name(name, xfp):
accounts = get_accounts_by_xfp(xfp)
for account in accounts:
if account.get('name') == name:
return account
return None
def get_account_by_number(acct_num, xfp):
from constants import DEFAULT_ACCOUNT_ENTRY
accounts = get_accounts_by_xfp(xfp)
for account in accounts:
if account.get('acct_num') == acct_num:
return account
if acct_num == 0:
return DEFAULT_ACCOUNT_ENTRY
return None
def get_derived_keys():
from common import settings
keys = settings.get('derived_keys', [])
keys.sort(key=lambda a: (a.get('name', '').lower(), a.get('tn', 0), a.get('index', 0)))
return keys
def get_derived_key_by_name(name, key_tn, xfp):
keys = get_derived_keys()
for key in keys:
if key['name'] == name and key['tn'] == key_tn and key['xfp'] == xfp:
return key
return None
def get_derived_key_by_index(index, key_tn, xfp):
keys = get_derived_keys()
for key in keys:
if key['index'] == index and key['tn'] == key_tn and key['xfp'] == xfp:
return key
return None
def get_width_from_num_words(num_words):
return (num_words - 1) * 11 // 8 + 1
# Only call when there is an active account
# def set_next_addr(new_addr):
# if not common.active_account:
# return
#
# common.active_account.next_addr = new_addr
#
# accounts = get_accounts()
# for account in accounts:
# if account('id') == common.active_account.id:
# account['next_addr'] = new_addr
# common.settings.set('accounts', accounts)
# common.settings.save()
# break
#
# # Only call when there is an active account
#
#
# def account_exists(name):
# accounts = get_accounts()
# for account in accounts:
# if account.get('name') == name:
# return True
#
# return False
def make_next_addr_key(acct_num, addr_type, xfp, chain_type, is_change):
return '{}.{}.{}/{}{}'.format(chain_type, xfp, acct_num, addr_type, '/1' if is_change else '')
def get_next_addr(acct_num, addr_type, xfp, chain_type, is_change):
from common import settings
next_addrs = settings.get('next_addrs', {})
key = make_next_addr_key(acct_num, addr_type, xfp, chain_type, is_change)
return next_addrs.get(key, 0)
# Save the next address to use for the specific account and address type
def save_next_addr(acct_num, addr_type, addr_idx, xfp, chain_type, is_change, force_update=False):
from common import settings
next_addrs = settings.get('next_addrs', {})
key = make_next_addr_key(acct_num, addr_type, xfp, chain_type, is_change)
# Only save the found index if it's newer
if next_addrs.get(key, -1) < addr_idx or force_update:
next_addrs[key] = addr_idx
settings.set('next_addrs', next_addrs)
def get_prev_address_range(range, max_size):
low, high = range
size = min(max_size, low)
return ((low - size, low), size)
def get_next_address_range(range, max_size):
low, high = range
return ((high, high + max_size), max_size)
def is_valid_btc_address(address):
# Strip prefix if present
if address[0:8].lower() == 'bitcoin:':
# Find the parameters part and strip it.
bitcoinparams_start = address.find('?')