forked from BitBoxSwiss/bitbox02-firmware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
send_message.py
executable file
·1473 lines (1338 loc) · 56.6 KB
/
send_message.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
#!/usr/bin/env python3
# Copyright 2019 Shift Cryptosecurity AG
# Copyright 2020 Shift Crypto AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Script for interacting with bitbox v2"""
# pylint: disable=too-many-lines
import argparse
import pprint
import sys
from typing import List, Any, Optional, Callable, Union, Tuple, Sequence
import base64
import binascii
import textwrap
import json
import requests # type: ignore
import hid
import semver
from tzlocal import get_localzone # type: ignore
from bitbox02 import util
from bitbox02 import bitbox02
from bitbox02.communication import (
devices,
HARDENED,
Bitbox02Exception,
UserAbortException,
FirmwareVersionOutdatedException,
u2fhid,
bitbox_api_protocol,
)
import u2f
import u2f.bitbox02
def eprint(*args: Any, **kwargs: Any) -> None:
"""
Like print, but defaults to stderr.
"""
kwargs.setdefault("file", sys.stderr)
print(*args, **kwargs)
def ask_user(
choices: Sequence[Tuple[str, Callable[[], None]]]
) -> Union[Callable[[], None], bool, None]:
"""Ask user to choose one of the choices, q quits"""
print("What would you like to do?")
for (idx, choice) in enumerate(choices):
print(f"- ({idx+1}) {choice[0]}")
print("- (q) Quit")
ans_str = input("")
if ans_str == "q":
return False
try:
ans = int(ans_str)
if ans < 1 or ans > len(choices):
raise ValueError("Out of range")
except ValueError:
print("Invalid input")
return None
return choices[ans - 1][1]
def _btc_demo_inputs_outputs(
bip44_account: int,
) -> Tuple[List[bitbox02.BTCInputType], List[bitbox02.BTCOutputType]]:
"""
Returns a sample btc tx.
"""
inputs: List[bitbox02.BTCInputType] = [
{
"prev_out_hash": binascii.unhexlify(
"c58b7e3f1200e0c0ec9a5e81e925baface2cc1d4715514f2d8205be2508b48ee"
),
"prev_out_index": 0,
"prev_out_value": int(1e8 * 0.60005),
"sequence": 0xFFFFFFFF,
"keypath": [84 + HARDENED, 0 + HARDENED, bip44_account, 0, 0],
"script_config_index": 0,
"prev_tx": {
"version": 1,
"locktime": 0,
"inputs": [
{
"prev_out_hash": b"11111111111111111111111111111111",
"prev_out_index": 0,
"signature_script": b"some signature script",
"sequence": 0xFFFFFFFF,
}
],
"outputs": [
{
"value": int(1e8 * 0.60005),
"pubkey_script": b"some pubkey script",
}
],
},
},
{
"prev_out_hash": binascii.unhexlify(
"c58b7e3f1200e0c0ec9a5e81e925baface2cc1d4715514f2d8205be2508b48ee"
),
"prev_out_index": 1,
"prev_out_value": int(1e8 * 0.60005),
"sequence": 0xFFFFFFFF,
"keypath": [49 + HARDENED, 0 + HARDENED, bip44_account, 0, 1],
"script_config_index": 1,
"prev_tx": {
"version": 1,
"locktime": 0,
"inputs": [
{
"prev_out_hash": b"11111111111111111111111111111111",
"prev_out_index": 0,
"signature_script": b"some signature script",
"sequence": 0xFFFFFFFF,
}
],
"outputs": [
{
"value": int(1e8 * 0.60005),
"pubkey_script": b"some pubkey script",
}
],
},
},
]
outputs: List[bitbox02.BTCOutputType] = [
bitbox02.BTCOutputInternal(
keypath=[84 + HARDENED, 0 + HARDENED, bip44_account, 1, 0],
value=int(1e8 * 1),
script_config_index=0,
),
bitbox02.BTCOutputExternal(
output_type=bitbox02.btc.P2WSH,
output_payload=b"11111111111111111111111111111111",
value=int(1e8 * 0.2),
),
]
return inputs, outputs
class SendMessage:
"""SendMessage"""
def __init__(self, device: bitbox02.BitBox02, debug: bool):
self._device = device
self._debug = debug
self._stop = False
def _change_name_workflow(self, name: Optional[str] = None) -> None:
"""
Invoke change name workfow.
"""
if name is None:
name = input("Enter a name [Mia] (max 64 bytes): ")
if not name:
name = "Mia"
info = self._device.device_info()
print(f"Old device name: {info['name']}")
try:
self._device.set_device_name(name)
except UserAbortException:
eprint("Aborted by user")
else:
print("Setting new device name.")
info = self._device.device_info()
print(f"New device name: {info['name']}")
def _setup_workflow(self) -> None:
"""TODO: Document"""
self._change_name_workflow()
print(
"Please choose a password of the BitBox02. "
+ "This password will be used to unlock your BitBox02."
)
while not self._device.set_password():
eprint("Passwords did not match. please try again")
print("Your BitBox02 will now create a backup of your wallet...")
def backup_sd() -> None:
if not self._device.create_backup():
eprint("Creating the backup failed")
return
print("Backup created sucessfully")
print("Please Remove SD Card")
self._device.remove_sdcard()
def backup_mnemonic() -> None:
if self._device.version < semver.VersionInfo(9, 13, 0):
eprint("Backing up using recovery words is supported from firmware version 9.13.0")
return
try:
self._device.show_mnemonic()
except Bitbox02Exception:
eprint("Creating the backup failed")
return
print("Backup created sucessfully")
choice = ask_user(
(
("Backup onto a microSD card", backup_sd),
("Backup manually by writing down recovey words", backup_mnemonic),
),
)
if callable(choice):
try:
choice()
except UserAbortException:
eprint("Aborted by user")
def _print_backups(self, backups: Optional[Sequence[bitbox02.Backup]] = None) -> None:
local_timezone = get_localzone()
if backups is None:
backups = list(self._device.list_backups())
if not backups:
print("No backups found.")
return
fmt = "%Y-%m-%d %H:%M:%S %z"
for (i, (backup_id, backup_name, date)) in enumerate(backups):
date = local_timezone.localize(date)
date_str = date.strftime(fmt)
print(f"[{i+1}] Backup Name: {backup_name}, Time: {date_str}, ID: {backup_id}")
def _restore_backup_workflow(self) -> None:
"""TODO: Document"""
backups = list(self._device.list_backups())
self._print_backups(backups)
if not backups:
return
ans = input(f"Choose a backup [1-{len(backups)}]: ")
try:
item = int(ans)
if item < 1 or item > len(backups):
raise ValueError("Out of range")
except ValueError:
eprint("Invalid input")
return
backup_id, _, _ = backups[item - 1]
print(f"ID: {backup_id}")
try:
self._device.restore_backup(backup_id)
except UserAbortException:
eprint("Aborted by user")
return
except Bitbox02Exception:
eprint("Restoring backup failed")
return
print("Please Remove SD Card")
self._device.remove_sdcard()
def _restore_from_mnemonic(self) -> None:
try:
self._device.restore_from_mnemonic()
print("Restore successful")
except UserAbortException:
print("Aborted by user")
def _list_device_info(self) -> None:
print(f"All info: {self._device.device_info()}")
def _reboot(self) -> None:
inp = input("Select one of: 1=upgrade; 2=go to startup settings: ").strip()
purpose = {
"1": bitbox02.system.RebootRequest.Purpose.UPGRADE, # pylint: disable=no-member
"2": bitbox02.system.RebootRequest.Purpose.SETTINGS, # pylint: disable=no-member
}[inp]
if self._device.reboot(purpose=purpose):
print("Device rebooted")
self._stop = True
else:
print("User aborted")
def _check_sd_presence(self) -> None:
print(f"SD Card inserted: {self._device.check_sdcard()}")
def _insert_sdcard(self) -> None:
self._device.insert_sdcard()
def _remove_sdcard(self) -> None:
self._device.remove_sdcard()
def _get_root_fingerprint(self) -> None:
print(f"Root fingerprint: {self._device.root_fingerprint().hex()}")
def _display_zpub(self) -> None:
try:
print(
"m/84'/0'/0' zpub: ",
self._device.btc_xpub(
keypath=[84 + HARDENED, 0 + HARDENED, 0 + HARDENED],
xpub_type=bitbox02.btc.BTCPubRequest.ZPUB, # pylint: disable=no-member
),
)
except UserAbortException:
eprint("Aborted by user")
def _get_electrum_encryption_key(self) -> None:
print(
"Electrum wallet encryption xpub at keypath m/4541509'/1112098098':",
self._device.electrum_encryption_key(
keypath=[4541509 + HARDENED, 1112098098 + HARDENED]
),
)
def _btc_address(self) -> None:
def address(display: bool) -> str:
# pylint: disable=no-member
return self._device.btc_address(
keypath=[84 + HARDENED, 0 + HARDENED, 0 + HARDENED, 0, 0],
script_config=bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH
),
display=display,
)
print("m/84'/0'/0'/0/0 address: ", address(False))
address(True)
def _btc_multisig_config(self, coin: "bitbox02.btc.BTCCoin.V") -> bitbox02.btc.BTCScriptConfig:
"""
Get a mock multisig 1-of-2 multisig with the current device and some other arbitrary xpub.
Registers it on the device if not already registered.
"""
account_keypath = [48 + HARDENED, 0 + HARDENED, 0 + HARDENED, 2 + HARDENED]
my_xpub = self._device.btc_xpub(
keypath=account_keypath,
coin=coin,
xpub_type=bitbox02.btc.BTCPubRequest.XPUB, # pylint: disable=no-member,
display=False,
)
multisig_config = bitbox02.btc.BTCScriptConfig(
multisig=bitbox02.btc.BTCScriptConfig.Multisig(
threshold=1,
xpubs=[
util.parse_xpub(my_xpub),
util.parse_xpub(
"xpub6FEZ9Bv73h1vnE4TJG4QFj2RPXJhhsPbnXgFyH3ErLvpcZrDcynY65bhWga8PazW"
"HLSLi23PoBhGcLcYW6JRiJ12zXZ9Aop4LbAqsS3gtcy"
),
],
our_xpub_index=0,
)
)
is_registered = self._device.btc_is_script_config_registered(
coin, multisig_config, account_keypath
)
if is_registered:
print("Multisig account already registered on the device.")
else:
multisig_name = input("Enter a name for the multisig account: ").strip()
self._device.btc_register_script_config(
coin=coin,
script_config=multisig_config,
keypath=account_keypath,
name=multisig_name,
)
return multisig_config
def _btc_multisig_address(self) -> None:
try:
coin = bitbox02.btc.BTC
print(
self._device.btc_address(
coin=coin,
keypath=[
48 + HARDENED,
0 + HARDENED,
0 + HARDENED,
2 + HARDENED,
1,
2,
],
script_config=self._btc_multisig_config(coin),
display=True,
)
)
except UserAbortException:
print("Aborted by user")
def _sign_btc_normal(self) -> None:
# pylint: disable=no-member
bip44_account: int = 0 + HARDENED
inputs, outputs = _btc_demo_inputs_outputs(bip44_account)
sigs = self._device.btc_sign(
bitbox02.btc.BTC,
[
bitbox02.btc.BTCScriptConfigWithKeypath(
script_config=bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH
),
keypath=[84 + HARDENED, 0 + HARDENED, bip44_account],
),
bitbox02.btc.BTCScriptConfigWithKeypath(
script_config=bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH_P2SH
),
keypath=[49 + HARDENED, 0 + HARDENED, bip44_account],
),
],
inputs=inputs,
outputs=outputs,
)
for input_index, sig in sigs:
print("Signature for input {}: {}".format(input_index, sig.hex()))
def _sign_btc_multiple_changes(self) -> None:
# pylint: disable=no-member
bip44_account: int = 0 + HARDENED
inputs, outputs = _btc_demo_inputs_outputs(bip44_account)
# Add a change output.
outputs.append(
bitbox02.BTCOutputInternal(
keypath=[84 + HARDENED, 0 + HARDENED, bip44_account, 1, 0],
value=int(1),
script_config_index=0,
)
)
sigs = self._device.btc_sign(
bitbox02.btc.BTC,
[
bitbox02.btc.BTCScriptConfigWithKeypath(
script_config=bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH
),
keypath=[84 + HARDENED, 0 + HARDENED, bip44_account],
),
bitbox02.btc.BTCScriptConfigWithKeypath(
script_config=bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH_P2SH
),
keypath=[49 + HARDENED, 0 + HARDENED, bip44_account],
),
],
inputs=inputs,
outputs=outputs,
)
for input_index, sig in sigs:
print("Signature for input {}: {}".format(input_index, sig.hex()))
def _sign_btc_locktime_rbf(self) -> None:
# pylint: disable=no-member
bip44_account: int = 0 + HARDENED
inputs, outputs = _btc_demo_inputs_outputs(bip44_account)
inputs[0]["sequence"] = 0xFFFFFFFF - 2
sigs = self._device.btc_sign(
bitbox02.btc.BTC,
[
bitbox02.btc.BTCScriptConfigWithKeypath(
script_config=bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH
),
keypath=[84 + HARDENED, 0 + HARDENED, bip44_account],
),
bitbox02.btc.BTCScriptConfigWithKeypath(
script_config=bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH_P2SH
),
keypath=[49 + HARDENED, 0 + HARDENED, bip44_account],
),
],
inputs=inputs,
outputs=outputs,
locktime=10,
)
for input_index, sig in sigs:
print("Signature for input {}: {}".format(input_index, sig.hex()))
def _sign_btc_taproot_inputs(self) -> None:
# pylint: disable=no-member
bip44_account: int = 0 + HARDENED
inputs, outputs = _btc_demo_inputs_outputs(bip44_account)
for inp in inputs:
inp["keypath"] = [86 + HARDENED] + list(inp["keypath"][1:])
inp["prev_tx"] = None
inp["script_config_index"] = 0
for outp in outputs:
if isinstance(outp, bitbox02.BTCOutputInternal):
outp.keypath = [86 + HARDENED] + list(outp.keypath[1:])
script_configs = [
bitbox02.btc.BTCScriptConfigWithKeypath(
script_config=bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2TR
),
keypath=[86 + HARDENED, 0 + HARDENED, bip44_account],
),
]
assert not bitbox02.btc_sign_needs_prevtxs(script_configs)
sigs = self._device.btc_sign(
bitbox02.btc.BTC,
script_configs,
inputs=inputs,
outputs=outputs,
)
for input_index, sig in sigs:
print("Signature for input {}: {}".format(input_index, sig.hex()))
def _sign_btc_taproot_output(self) -> None:
# pylint: disable=no-member
bip44_account: int = 0 + HARDENED
inputs, outputs = _btc_demo_inputs_outputs(bip44_account)
assert isinstance(outputs[1], bitbox02.BTCOutputExternal)
outputs[1].type = bitbox02.btc.P2TR
outputs[1].payload = bytes.fromhex(
"a60869f0dbcf1dc659c9cecbaf8050135ea9e8cdc487053f1dc6880949dc684c"
)
sigs = self._device.btc_sign(
bitbox02.btc.BTC,
[
bitbox02.btc.BTCScriptConfigWithKeypath(
script_config=bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH
),
keypath=[84 + HARDENED, 0 + HARDENED, bip44_account],
),
bitbox02.btc.BTCScriptConfigWithKeypath(
script_config=bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH_P2SH
),
keypath=[49 + HARDENED, 0 + HARDENED, bip44_account],
),
],
inputs=inputs,
outputs=outputs,
)
for input_index, sig in sigs:
print("Signature for input {}: {}".format(input_index, sig.hex()))
def _sign_btc_tx_from_raw(self) -> None:
"""
Experiment with testnet transactions.
Uses blockchair.com to convert a testnet transaction to the input required by btc_sign(),
including the previous transactions.
"""
# pylint: disable=no-member
def get(tx_id: str) -> Any:
return requests.get(
"https://api.blockchair.com/bitcoin/testnet/dashboards/transaction/{}".format(tx_id)
).json()["data"][tx_id]
tx_id = input("Paste a btc testnet tx ID: ").strip()
tx = get(tx_id)
inputs: List[bitbox02.BTCInputType] = []
outputs: List[bitbox02.BTCOutputType] = []
bip44_account: int = 0 + HARDENED
for inp in tx["inputs"]:
print("Downloading prev tx")
prev_tx = get(inp["transaction_hash"])
print("Downloaded prev tx")
prev_inputs: List[bitbox02.BTCPrevTxInputType] = []
prev_outputs: List[bitbox02.BTCPrevTxOutputType] = []
for prev_inp in prev_tx["inputs"]:
prev_inputs.append(
{
"prev_out_hash": binascii.unhexlify(prev_inp["transaction_hash"])[::-1],
"prev_out_index": prev_inp["index"],
"signature_script": binascii.unhexlify(prev_inp["spending_signature_hex"]),
"sequence": prev_inp["spending_sequence"],
}
)
for prev_outp in prev_tx["outputs"]:
prev_outputs.append(
{
"value": prev_outp["value"],
"pubkey_script": binascii.unhexlify(prev_outp["script_hex"]),
}
)
inputs.append(
{
"prev_out_hash": binascii.unhexlify(inp["transaction_hash"])[::-1],
"prev_out_index": inp["index"],
"prev_out_value": inp["value"],
"sequence": inp["spending_sequence"],
"keypath": [84 + HARDENED, 1 + HARDENED, bip44_account, 0, 0],
"script_config_index": 0,
"prev_tx": {
"version": prev_tx["transaction"]["version"],
"locktime": prev_tx["transaction"]["lock_time"],
"inputs": prev_inputs,
"outputs": prev_outputs,
},
}
)
for outp in tx["outputs"]:
outputs.append(
bitbox02.BTCOutputExternal(
# TODO: parse pubkey script
output_type=bitbox02.btc.P2WSH,
output_payload=b"11111111111111111111111111111111",
value=outp["value"],
)
)
print("Start signing...")
self._device.btc_sign(
bitbox02.btc.TBTC,
[
bitbox02.btc.BTCScriptConfigWithKeypath(
script_config=bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH
),
keypath=[84 + HARDENED, 1 + HARDENED, bip44_account],
)
],
inputs=inputs,
outputs=outputs,
)
def _sign_btc_tx(self) -> None:
"""btc signing demos"""
choices = (
("Normal tx", self._sign_btc_normal),
("Multiple change outputs", self._sign_btc_multiple_changes),
("Locktime/RBF", self._sign_btc_locktime_rbf),
("Taproot inputs", self._sign_btc_taproot_inputs),
("Taproot output", self._sign_btc_taproot_output),
("From testnet tx ID", self._sign_btc_tx_from_raw),
)
choice = ask_user(choices)
if callable(choice):
try:
choice()
except UserAbortException:
eprint("Aborted by user")
def _sign_btc_message(self) -> None:
# pylint: disable=no-member
keypath = [49 + HARDENED, 0 + HARDENED, 0 + HARDENED, 0, 0]
script_config = bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH_P2SH
)
address = self._device.btc_address(
keypath=keypath, script_config=script_config, display=False
)
print("Address:", address)
msg = input(r"Message to sign (\n = newline): ")
if msg.startswith("0x"):
msg_bytes = binascii.unhexlify(msg[2:])
else:
msg_bytes = msg.replace(r"\n", "\n").encode("utf-8")
try:
_, _, sig65 = self._device.btc_sign_msg(
bitbox02.btc.BTC,
bitbox02.btc.BTCScriptConfigWithKeypath(
script_config=script_config, keypath=keypath
),
msg_bytes,
)
print("Signature:", base64.b64encode(sig65).decode("ascii"))
except UserAbortException:
print("Aborted by user")
def _check_backup(self) -> None:
print("Your BitBox02 will now perform a backup check")
try:
backup_id = self._device.check_backup()
except UserAbortException:
print("Aborted by user")
else:
if backup_id:
print(f"Check successful. Backup with ID {backup_id} matches")
else:
print("No matching backup found")
def _show_mnemnoic_seed(self) -> None:
print("Your BitBox02 will now show the mnemonic seed phrase")
try:
self._device.show_mnemonic()
print("Success")
except UserAbortException:
print("Aborted by user")
def _create_backup(self) -> None:
if self._device.check_backup(silent=True) is not None:
if input("A backup already exists, continue? Y/n: ") not in ("", "Y", "y"):
return
try:
if not self._device.create_backup():
eprint("Creating the backup failed")
else:
print("Backup created sucessfully")
except UserAbortException:
print("Aborted by user")
def _toggle_mnemonic_passphrase(self) -> None:
enabled = self._device.device_info()["mnemonic_passphrase_enabled"]
try:
if enabled:
if input("Mnemonic passprase enabled, disable? Y/n: ") not in (
"",
"Y",
"y",
):
return
self._device.disable_mnemonic_passphrase()
else:
if input("Mnemonic passprase disabled, enable? Y/n: ") not in (
"",
"Y",
"y",
):
return
self._device.enable_mnemonic_passphrase()
enabled = not enabled
except UserAbortException:
print("Aborted by user")
print("Success.")
if enabled:
print("You can enter a mnemonic passphrase on the next unlock.")
print("Replug your BitBox02.")
def _get_eth_xpub(self) -> None:
try:
xpub = self._device.eth_pub(
keypath=[44 + HARDENED, 60 + HARDENED, 0 + HARDENED, 0],
output_type=bitbox02.eth.ETHPubRequest.XPUB, # pylint: disable=no-member
display=False,
)
except UserAbortException:
eprint("Aborted by user")
print("Ethereum xpub: {}".format(xpub))
def _display_eth_address(self, contract_address: bytes = b"") -> None:
def address(display: bool = False) -> str:
return self._device.eth_pub(
keypath=[44 + HARDENED, 60 + HARDENED, 0 + HARDENED, 0, 0],
output_type=bitbox02.eth.ETHPubRequest.ADDRESS, # pylint: disable=no-member
contract_address=contract_address,
display=display,
)
print("Ethereum address: {}".format(address(display=False)))
try:
address(display=True)
except UserAbortException:
eprint("Aborted by user")
def _sign_eth_tx(self) -> None:
# pylint: disable=line-too-long
inp = input(
"Select one of: 1=normal; 2=erc20; 3=erc721; 4=unknown erc20; 5=large data field; 6=BSC; 7=unknown network: "
).strip()
chain_id = 1 # mainnet
if inp == "6":
chain_id = 56
elif inp == "7":
chain_id = 123456
if inp in ("1", "6", "7"):
# fmt: off
tx = bytes([0xf8, 0x6e, 0x82, 0x1f, 0xdc, 0x85, 0x01, 0x65, 0xa0, 0xbc, 0x00, 0x82, 0x52,
0x08, 0x94, 0x04, 0xf2, 0x64, 0xcf, 0x34, 0x44, 0x03, 0x13, 0xb4, 0xa0, 0x19, 0x2a,
0x35, 0x28, 0x14, 0xfb, 0xe9, 0x27, 0xb8, 0x85, 0x88, 0x07, 0x5c, 0xf1, 0x25, 0x9e,
0x9c, 0x40, 0x00, 0x80, 0x25, 0xa0, 0x15, 0xc9, 0x4c, 0x1a, 0x3d, 0xa0, 0xab, 0xc0,
0xa9, 0x12, 0x4d, 0x28, 0x37, 0x80, 0x9c, 0xcc, 0x49, 0x3c, 0x41, 0x50, 0x4e, 0x45,
0x71, 0xbc, 0xc3, 0x40, 0xee, 0xb6, 0x8a, 0x91, 0xf6, 0x41, 0xa0, 0x35, 0x99, 0x01,
0x1d, 0x4c, 0xda, 0x2c, 0x33, 0xdd, 0x3b, 0x00, 0x07, 0x1e, 0xc1, 0x45, 0x33, 0x5e,
0x5d, 0x2d, 0xd5, 0xed, 0x81, 0x2d, 0x5e, 0xeb, 0xee, 0xcb, 0xa5, 0x26, 0x4e, 0xd1,
0xbf])
# fmt: on
elif inp == "2":
tx = binascii.unhexlify(
"f8ac82236785027aca1a808301d04894dac17f958d2ee523a2206206994597c13d831ec780b844a9059cbb000000000000000000000000e6ce0a092a99700cd4ccccbb1fedc39cf53e6330000000000000000000000000000000000000000000000000000000000365c0401ca0265f70103c605eaa1b64c3200d2e7934d7744a3068b377e26c4b080795c744c0a020bbcd34a306621fa8965040390bc240d6d0e3b88915ccdb309d15f1caba81b1"
)
elif inp == "3":
tx = binascii.unhexlify(
"f87282750b8502cb42fea0830927c0942cab2d282e588f00beabe2bf5577c7644972e10f808b00009470ff1c8de91c861d1ca0f07bca4f43eb1c461ca3cf208e920b60cb393dd37489a14e9f92632acb17dd7ca0694523c8b72052cf6a8b9f93719a664fbbbe59e731cefb1331b2d21ee80b5268"
)
elif inp == "4":
tx = binascii.unhexlify(
"f8aa81b9843b9aca0083010985949c23d67aea7b95d80942e3836bcdf7e708a747c180b844a9059cbb000000000000000000000000857b3d969eacb775a9f79cabc62ec4bb1d1cd60e000000000000000000000000000000000000000000000098a63cbeb859d027b026a0d3b1a9ba4aff7ebf81dca7dafdbe6d803d174f7805276f45530f2c30e74f5ffca02d86d5290f6ba2c5100e08764d8ab34cf33b03dff3f63219fd839ac9a95f7068"
)
elif inp == "5":
tx = binascii.unhexlify(
"f9016881b9843b9aca0083010985949c23d67aea7b95d80942e3836bcdf7e708a747c180b90141ef3f3d0b000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee0000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000009be6769ef4fc4ccda30e0e39052070d90d3f0bfe000000000000000000000000000000000000000000000000000000e8d4a51000000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000001a000000000000000000000000000000000000000000000000000000000000001e0000000000000000000000000000000000000000000000000000000000000026000000000000000000000000000000000000000000000000000000000000002c0000000000000000000000000000000000000000000000000000179fc8e808080"
)
else:
print("None selected")
return
try:
sig = self._device.eth_sign(
tx,
keypath=[44 + HARDENED, 60 + HARDENED, 0 + HARDENED, 0, 0],
chain_id=chain_id,
)
print("Signature: {}".format(sig.hex()))
except UserAbortException:
eprint("Aborted by user")
def _sign_eth_message(self) -> None:
msg = input(r"Message to sign (\n = newline): ")
if msg.startswith("0x"):
msg_bytes = binascii.unhexlify(msg[2:])
else:
msg_bytes = msg.replace(r"\n", "\n").encode("utf-8")
msg_hex = binascii.hexlify(msg_bytes).decode("utf-8")
print(f"signing\nbytes: {repr(msg_bytes)}\nhex: 0x{msg_hex}")
sig = self._device.eth_sign_msg(
msg=msg_bytes,
keypath=[44 + HARDENED, 60 + HARDENED, 0 + HARDENED, 0, 0],
)
print("Signature: 0x{}".format(binascii.hexlify(sig).decode("utf-8")))
def _sign_eth_typed_message(self) -> None:
msg = """{
"types": {
"EIP712Domain": [
{ "name": "name", "type": "string" },
{ "name": "version", "type": "string" },
{ "name": "chainId", "type": "uint256" },
{ "name": "verifyingContract", "type": "address" }
],
"Attachment": [
{ "name": "contents", "type": "string" }
],
"Person": [
{ "name": "name", "type": "string" },
{ "name": "wallet", "type": "address" }
],
"Mail": [
{ "name": "from", "type": "Person" },
{ "name": "to", "type": "Person" },
{ "name": "contents", "type": "string" },
{ "name": "attachments", "type": "Attachment[]" }
]
},
"primaryType": "Mail",
"domain": {
"name": "Ether Mail",
"version": "1",
"chainId": 1,
"verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"
},
"message": {
"from": {
"name": "Cow",
"wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"
},
"to": {
"name": "Bob",
"wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"
},
"contents": "Hello, Bob!",
"attachments": [{ "contents": "attachment1" }, { "contents": "attachment2" }]
}
}"""
print("Signing:\n{}".format(msg))
sig = self._device.eth_sign_typed_msg(
keypath=[44 + HARDENED, 60 + HARDENED, 0 + HARDENED, 0, 0], msg=json.loads(msg)
)
print("Signature: 0x{}".format(binascii.hexlify(sig).decode("utf-8")))
def _cardano(self) -> None:
def xpubs() -> None:
xpubs = self._device.cardano_xpubs(
keypaths=[
[1852 + HARDENED, 1815 + HARDENED, HARDENED],
[1852 + HARDENED, 1815 + HARDENED, HARDENED + 1],
]
)
print("m/1852'/1815'/0' xpub: ", xpubs[0].hex())
print("m/1852'/1815'/1' xpub: ", xpubs[1].hex())
script_config = bitbox02.cardano.CardanoScriptConfig(
pkh_skh=bitbox02.cardano.CardanoScriptConfig.PkhSkh(
keypath_payment=[1852 + HARDENED, 1815 + HARDENED, HARDENED, 0, 0],
keypath_stake=[1852 + HARDENED, 1815 + HARDENED, HARDENED, 2, 0],
)
)
def get_address(display: bool) -> str:
return self._device.cardano_address(
bitbox02.cardano.CardanoAddressRequest(
network=bitbox02.cardano.CardanoMainnet,
display=display,
script_config=script_config,
)
)
def address() -> None:
print("m/1852'/1815'/0'/0/0 address: ", get_address(False))
get_address(True)
def sign() -> None:
response = self._device.cardano_sign_transaction(
transaction=bitbox02.cardano.CardanoSignTransactionRequest(
network=bitbox02.cardano.CardanoMainnet,
inputs=[
bitbox02.cardano.CardanoSignTransactionRequest.Input(
keypath=[2147485500, 2147485463, 2147483648, 0, 0],
prev_out_hash=bytes.fromhex(
"59864ee73ca5d91098a32b3ce9811bac1996dcbaefa6b6247dcaafb5779c2538"
),
prev_out_index=0,
)
],
outputs=[
bitbox02.cardano.CardanoSignTransactionRequest.Output(
encoded_address="addr1q9qfllpxg2vu4lq6rnpel4pvpp5xnv3kvvgtxk6k6wp4ff89xrhu8jnu3p33vnctc9eklee5dtykzyag5penc6dcmakqsqqgpt",
value=1000000,
),
bitbox02.cardano.CardanoSignTransactionRequest.Output(
encoded_address=get_address(False),
value=4829501,
script_config=script_config,
),
],
fee=170499,
ttl=41115811,
certificates=[],
validity_interval_start=41110811,
)
)
print(response)
def sign_zero_ttl() -> None:
response = self._device.cardano_sign_transaction(
transaction=bitbox02.cardano.CardanoSignTransactionRequest(
network=bitbox02.cardano.CardanoMainnet,
inputs=[
bitbox02.cardano.CardanoSignTransactionRequest.Input(
keypath=[2147485500, 2147485463, 2147483648, 0, 0],
prev_out_hash=bytes.fromhex(
"59864ee73ca5d91098a32b3ce9811bac1996dcbaefa6b6247dcaafb5779c2538"
),
prev_out_index=0,
)
],
outputs=[
bitbox02.cardano.CardanoSignTransactionRequest.Output(
encoded_address="addr1q9qfllpxg2vu4lq6rnpel4pvpp5xnv3kvvgtxk6k6wp4ff89xrhu8jnu3p33vnctc9eklee5dtykzyag5penc6dcmakqsqqgpt",
value=1000000,
),
bitbox02.cardano.CardanoSignTransactionRequest.Output(
encoded_address=get_address(False),
value=4829501,
script_config=script_config,
),
],
fee=170499,
ttl=0,
allow_zero_ttl=True,
certificates=[],
validity_interval_start=41110811,
)
)
print(response)
def sign_tokens() -> None:
response = self._device.cardano_sign_transaction(
transaction=bitbox02.cardano.CardanoSignTransactionRequest(
network=bitbox02.cardano.CardanoMainnet,
inputs=[
bitbox02.cardano.CardanoSignTransactionRequest.Input(
keypath=[2147485500, 2147485463, 2147483648, 0, 0],
prev_out_hash=bytes.fromhex(
"59864ee73ca5d91098a32b3ce9811bac1996dcbaefa6b6247dcaafb5779c2538"
),
prev_out_index=0,
)
],
outputs=[
bitbox02.cardano.CardanoSignTransactionRequest.Output(