-
Notifications
You must be signed in to change notification settings - Fork 4
/
agent.py
1769 lines (1465 loc) · 57.2 KB
/
agent.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 python
# -*- coding: utf-8 -*-
# Author: Dusan Klinec, ph4r05, 2018
#
# Note pickling is used for message serialization.
# This is just for the prototyping & fast PoC, pickling wont be used in the production.
# Instead, protobuf messages will be defined and parsed to avoid malicious pickling.
#
import argparse
import asyncio
import binascii
import datetime
import json
import logging
import os
import re
import sys
import threading
import time
from monero_glue.agent import agent_lite, agent_misc
from monero_glue.agent.agent_lite import SignAuxData
from monero_glue.messages import DebugMoneroDiagRequest, Entropy, GetEntropy
from monero_glue.xmr import common, crypto, daemon_rpc, monero, wallet, wallet_rpc
from monero_glue.xmr.common import try_fnc
from monero_glue.xmr.enc import chacha, chacha_poly
from monero_glue.xmr.sub import addr as xmr_addr
from monero_poc.utils import cli, misc, trace_logger
from monero_poc.utils.misc import TrezorAddressMismatchError
from monero_poc.utils.trezor_server_proxy import TokenProxy
from monero_serialize import xmrboost, xmrserialize, xmrtypes
from trezorlib import debuglink, device
import coloredlogs
from cmd2 import Cmd
logger = logging.getLogger(__name__)
coloredlogs.CHROOT_FILES = []
coloredlogs.install(level=logging.WARNING, use_chroot=False)
class HostAgent(cli.BaseCli):
"""
Host agent wrapper
"""
prompt = "$> "
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.args = None
self.network_type = None
self.address = None
self.address_info = None # type: xmr_addr.AddrInfo
self.address_base_info = None # type: xmr_addr.AddrInfo
self.priv_view = None
self.pub_view = None
self.pub_spend = None
self.network_type = None
self.account_idx = 0 # major sub-address index
self.wallet_salt = None
self.wallet_password = b""
self.wallet_file = None
self.monero_bin = None
self.rpc_addr = "127.0.0.1:18081"
self.rpc_passwd = None
self.rpc_bind_port = 48084
self.rpc_running = False
self.rpc_ready = False
self.trace_logger = trace_logger.Tracelogger(logger)
self.loop = asyncio.get_event_loop()
self.worker_loop = asyncio.new_event_loop()
self.worker_thread = threading.Thread(
target=self.looper, args=(self.worker_loop,)
)
self.worker_thread.setDaemon(True)
self.worker_thread.start()
self.wallet_thread = None
self.terminating = False
self.trezor_proxy = None # type: TokenProxy
self.agent = None # type: agent_lite.Agent
self.token_debug = False
self.token_path = None
self.fresh_wallet = False
self.wallet_proxy = wallet_rpc.WalletRpc(
self, self.rpc_bind_port, self.rpc_passwd
)
self.daemon_rpc = daemon_rpc.DaemonRpc()
self.wallet_obj = wallet.Wallet(self.daemon_rpc)
def looper(self, loop):
"""
Main looper
:param loop:
:return:
"""
asyncio.set_event_loop(loop)
loop.run_forever()
def submit_coro(self, coro):
"""
Submits corroutine to the worker loop
:param fnc:
:param args:
:param kwargs:
:return:
"""
return asyncio.run_coroutine_threadsafe(coro, self.worker_loop)
def wait_coro(self, coro):
"""
Runs corouting, waits for result
:param fnc:
:param args:
:param kwargs:
:return:
"""
future = self.submit_coro(coro)
return future.result()
#
# CLI
#
def update_intro(self):
"""
Updates intro text for CLI header - adds version to it.
:return:
"""
self.intro = (
"-" * self.get_term_width()
+ "\n Monero Trezor agent\n"
+ "\n"
+ "-" * self.get_term_width()
)
def update_prompt(self):
"""
Prompt update
:return:
"""
flags = []
if not self.rpc_running:
flags.append("R!")
if not self.rpc_ready:
flags.append("Loading" if not self.fresh_wallet else "Syncing")
flags_str = "|".join(flags)
flags_suffix = "|" + flags_str if len(flags_str) > 0 else ""
self.prompt = "[wallet %s%s]: " % (
self.address[:6].decode("ascii") if self.address else "",
flags_suffix,
)
def token_cmd(self, coro):
try:
res = self.wait_coro(coro)
return res
except Exception as e:
print("Trezor error (e: %s)" % e)
self.trace_logger.log(e)
raise e
#
# Handlers
#
def check_rpc(self):
try_debug = None
if not self.args.debug_rpc:
try_debug = (
"Consider running with --debug-rpc flag to show RPC wallet "
"output for closer inspection and diagnosis"
)
if not self.rpc_running:
self.perror("Monero RPC wallet is not running.")
if try_debug:
self.poutput(try_debug)
return False
elif not self.rpc_ready:
self.perror("Monero RPC wallet is not yet ready, please wait a moment")
self.poutput(
"RPC wallet is not available during the blockchain scanning, it may take a while"
)
if try_debug:
self.poutput(try_debug)
return False
return True
def check_address(self):
pres = self.token_cmd(self.agent.get_address(account=self.account_idx))
if self.address != pres.address:
self.perror("Connected TREZOR address does not match wallet address")
raise TrezorAddressMismatchError()
def do_quit(self, line):
self.terminating = True
return super().do_quit(line)
do_q = do_quit
do_Q = do_quit
# def do_account(self, line):
# self.set_account(int(line))
def do_address(self, line):
print(self.address.decode("ascii"))
def do_ping(self, line):
pres = self.token_cmd(self.trezor_proxy.ping())
if pres:
print("OK %s" % pres)
def do_check_trezor(self, line):
self.check_address()
self.poutput("OK")
def do_state(self, line):
if not self.rpc_running:
self.perror("RPC wallet is not running")
else:
self.poutput("RPC wallet: running")
if self.rpc_ready:
self.poutput("RPC wallet: ready")
elif self.fresh_wallet:
self.poutput("RPC wallet: synchronising")
else:
self.poutput("RPC wallet: starting")
def do_get_watch_only(self, line):
pres = self.token_cmd(self.agent.get_watch_only())
print("View key: %s" % binascii.hexlify(pres.watch_key).decode("utf8"))
print("Address: %s" % pres.address.decode("utf8"))
def do_get_address(self, line):
pres = self.token_cmd(self.agent.get_address(account=self.account_idx))
print("Address: %s" % pres.address.decode("utf8"))
def do_balance(self, line):
if not self.check_rpc():
return
res = self.wallet_proxy.balance()
print("Balance: %.5f" % wallet.conv_disp_amount(res["result"]["balance"]))
print(
"Unlocked Balance: %.5f"
% wallet.conv_disp_amount(res["result"]["unlocked_balance"])
)
def do_height(self, line):
if not self.check_rpc():
return
res = self.wallet_proxy.height()
print("Height: %s" % res["result"]["height"])
def do_get_transfers(self, line):
if not self.check_rpc():
return
res = self.wallet_proxy.get_transfers({"pool": True, "in": True, "out": True})
print(json.dumps(res, indent=2))
def do_rescan_bc(self, line):
if not self.check_rpc():
return
res = self.wallet_proxy.rescan_bc()
print(json.dumps(res, indent=2))
def do_key_image_sync(self, line):
if not self.check_rpc():
return
self.check_address()
self.wait_coro(self.key_image_sync(line))
def do_refresh(self, line):
if not self.check_rpc():
return
res = self.wallet_proxy.refresh()
print(json.dumps(res, indent=2))
def do_transfer(self, line):
if not self.check_rpc():
return
self.check_address()
if len(line) == 0:
print(
"Usage: transfer [<priority>] [<ring_size>] <address> <amount> [<payment_id>]"
)
parts = [x for x in line.split(" ") if len(x.strip()) > 0]
res = misc.parse_transfer_cmd(parts)
return self.transfer_cmd(res)
def do_sweep_dust(self, line):
if not self.check_rpc():
return
res = self.wallet_proxy.sweep_dust({"do_not_relay": True})
if "result" not in res:
logger.error("Sweep dust error: %s" % res)
raise ValueError("Could not transfer")
result = res["result"]
unsigned = binascii.unhexlify(result["unsigned_txset"])
self.wait_coro(self.sign_unsigned(unsigned))
def do_sweep_all(self, line):
if not self.check_rpc():
return
if len(line) == 0:
self.poutput(
"sweep_all [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> [<payment_id>]"
)
return
params = misc.parse_sweep_all(line)
self.sweep_cmd(params, is_all=True)
def do_sweep_below(self, line):
if not self.check_rpc():
return
if len(line) == 0:
self.poutput(
"sweep_below <amount_threshold> [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> [<payment_id>]"
)
return
params = misc.parse_sweep_below(line)
self.sweep_cmd(params, is_below=True)
def do_sweep_single(self, line):
if not self.check_rpc():
return
if len(line) == 0:
self.poutput(
"sweep_single [<priority>] [<ring_size>] <key_image> <address> [<payment_id>]"
)
return
params = misc.parse_sweep_below(line)
self.sweep_cmd(params, is_single=True)
def do_sign(self, line):
if not self.check_rpc():
return
self.check_address()
self.wait_coro(self.sign_wrap(line))
def do_init(self, line):
mnemonic12 = "alcohol woman abuse must during monitor noble actual mixed trade anger aisle"
mnemonic24 = "permit universe parent weapon amused modify essay borrow tobacco budget walnut lunch consider gallery ride amazing frog forget treat market chapter velvet useless topple"
init_mode = 0 if len(line) == 0 else int(line)
mnemonic = mnemonic12 if len(line) == 0 or int(line) == 0 else mnemonic24
print(self.trezor_proxy.client)
device.wipe(self.trezor_proxy.client)
debuglink.load_device_by_mnemonic(
client=self.trezor_proxy.client,
mnemonic=mnemonic,
pin="1234" if init_mode >= 2 else "",
passphrase_protection=init_mode >= 3,
label="ph4test",
language="english",
)
def do_get_entropy(self, line):
parts = line.split(" ")
size = int(parts[0])
path = parts[1]
self.wait_coro(self.get_entropy(size, path))
def do_tdeb(self, line):
is_deb = bool(int(line))
print("Token debug set to: %s" % is_deb)
self.token_debug = is_deb
def do_switch(self, line):
line = line.strip()
path = "bridge:web01"
if line == "udp":
path = "udp:127.0.0.1:21324"
elif ":" in line:
path = line
elif len(line) == 0:
path = self.choose_trezor()
if "bridge" in path:
self.token_debug = False
print("Switching to device: %s" % path)
self.token_path = path
self.wait_coro(self.connect(path))
def do_reconnect(self, line):
self.wait_coro(self.connect(self.token_path))
def do_enumerate(self, line):
from monero_glue.trezor import manager as tmanager
r = tmanager.Trezor.enumerate()
for x in r:
print(x)
def do_diag(self, line):
m = re.match(r"^\s*(\d+)(?:(\s+\d+)(?:(\s+\d+)([\s\d]+))?)?\s*$", line.strip())
if m is None:
print("Usage: diag INS [p1 [p2 [ints...]]")
return
diag_code = int(m.group(1))
p1 = int(m.group(2)) if m.group(2) else None
p2 = int(m.group(3)) if m.group(3) else None
ints = [int(x) for x in re.sub(r"\s{2,}", " ", m.group(4).strip()).split(" ")] if m.group(4) else None
print("Diagnosis: %d p1: %s p2: %s params: %s" % (diag_code, p1, p2, ints))
msg = DebugMoneroDiagRequest(ins=diag_code, p1=p1, p2=p2, pd=ints)
try:
resp = self.wait_coro(self.trezor_proxy.call(msg))
print(resp)
except Exception as e:
self.trace_logger.log(e)
logger.warning(e)
complete_sign = Cmd.path_complete
#
# Logic
#
def set_network_type(self, ntype):
self.network_type = ntype
self.agent.network_type = ntype
async def is_connected(self):
"""
Returns True if Trezor is connected
:return:
"""
try:
await self.trezor_proxy.ping()
return True
except Exception as e:
return False
async def load_watchonly(self):
"""
Loads watch-only credentials from connected Trezor
:return:
"""
if not await self.is_connected():
logger.error("Trezor is not connected")
raise agent_misc.TrezorNotRunning("Could not load watch-only credentials")
try:
print(
"Loading watch-only credentials from Trezor. Please, confirm the request on Trezor."
)
self.set_network_type(
monero.NetworkTypes.TESTNET
if self.args.testnet
else monero.NetworkTypes.MAINNET
)
res = await self.agent.get_watch_only() # type: messages.MoneroWatchKey
self.priv_view = crypto.decodeint(res.watch_key)
self.set_address(res.address)
await self.open_with_keys(self.priv_view, self.address)
except Exception as e:
if not self.args:
raise ValueError(e)
else:
logger.warning("Loading watch-only keys failed (but init is not required), %s" % (e,))
async def get_entropy(self, size, path):
"""
Loads entropy from the device, writes to the path
:param size:
:param path:
:return:
"""
logger.info("Loading entropy of %s B to %s" % (size, path))
with open(path, "wb+") as fh:
csize = 0
while csize < size:
req = GetEntropy(size=1024 * 10)
res = await self.trezor_proxy.call_in_session(req) # type: Entropy
csize += len(res.entropy)
logger.debug(
" .. loaded %s / %s (%s %%)" % (csize, size, 100.0 * csize / size)
)
fh.write(res.entropy)
logger.info("Entropy loading done")
def load_params(self):
"""
Args
:return:
"""
if self.args.rpc_addr:
self.rpc_addr = self.args.rpc_addr
if self.args.watch_wallet:
self.wallet_file = self.args.watch_wallet
if self.args.monero_bin:
self.monero_bin = self.args.monero_bin
def choose_trezor(self):
from monero_glue.trezor import manager as tmanager
r = tmanager.Trezor.enumerate()
noptions = len(r)
if noptions == 0:
self.perror("No TREZOR device found")
raise EnvironmentError("No usable device")
elif noptions == 1:
self.poutput("Detected TREZOR: %s" % r[0])
return str(r[0])
choices = [(i, str(r[i])) for i in range(noptions)]
res = self.select(choices, "Please select from connected devices: ")
return str(r[res])
def monkey_patch_trezorlib(self):
logger.info(
"Monkey-patching trezorlib with the current messages versions fromt trezor-common"
)
try:
import trezorlib
from monero_glue import protobuf
from monero_glue import messages
from trezorlib import protobuf as tprotobuf
tprotobuf.UVarintType = protobuf.UVarintType
tprotobuf.SVarintType = protobuf.SVarintType
tprotobuf.BoolType = protobuf.BoolType
tprotobuf.BytesType = protobuf.BytesType
tprotobuf.UnicodeType = protobuf.UnicodeType
tprotobuf.MessageType = protobuf.MessageType
trezorlib.messages = messages
from trezorlib import mapping
trezorlib.mapping.map_type_to_class = {}
trezorlib.mapping.map_class_to_type = {}
trezorlib.mapping.build_map()
except Exception as e:
logger.error("Monkey patching error: %s" % e)
async def connect(self, path=None):
"""
Connects to the trezor
:return:
"""
if not self.args.poc or (self.args.trezor_path or path):
if self.args.patch_client:
self.monkey_patch_trezorlib()
from monero_glue.trezor import manager as tmanager
t_path = path if path else self.args.trezor_path
if t_path is None or len(t_path) == 0:
self.token_path = self.choose_trezor()
t_path = self.token_path
self.trezor_proxy = tmanager.Trezor(path=t_path, debug=self.token_debug)
else:
self.trezor_proxy = TokenProxy()
ntype = self.agent.network_type if self.agent else self.network_type
self.agent = agent_lite.Agent(
self.trezor_proxy, network_type=ntype
)
async def open_account(self):
"""
Opens the watch only account
:return:
"""
creds_passed = self.args.view_key is not None and self.args.address is not None
account_file_set = self.args.account_file is not None
account_file_ex = (
os.path.exists(self.args.account_file) if account_file_set else False
)
if creds_passed:
await self.open_account_passed()
elif account_file_ex:
await self.open_account_file(self.args.account_file)
else:
self.load_params()
await self.check_params(True)
await self.load_watchonly()
self.load_params()
if account_file_set and not account_file_ex:
await self.check_params(True)
self.wallet_password = await self.prompt_password(True)
# Create watch only wallet file for monero-wallet-rpc
await self.ensure_watch_only()
# Write acquired data to the account file
if account_file_set and not account_file_ex:
await self.save_account(self.args.account_file)
if self.pub_spend:
print(
"Public spend key: %s"
% binascii.hexlify(crypto.encodepoint(self.pub_spend)).decode("ascii")
)
print(
"Public view key : %s"
% binascii.hexlify(crypto.encodepoint(self.pub_view)).decode("ascii")
)
if self.address:
print("Address: %s" % self.address.decode("utf8"))
self.update_intro()
self.update_prompt()
async def check_params(self, new_wallet=False):
"""
All params correctly entered?
:return:
"""
if not new_wallet:
return
if self.args.sign is not None:
return
if self.wallet_file is None:
logger.error(
"--watch-wallet file is not set. Please specify path where to create the monero watch wallet"
)
sys.exit(1)
if self.monero_bin is None:
logger.error(
"--monero-bin is not set. Please specify path to the monero binaries"
)
sys.exit(1)
async def prompt_password(self, new_wallet=False):
"""
Prompts password for a new wallet
:param new_wallet:
:return:
"""
if new_wallet:
passwd = self.ask_password(
"Creating a new wallet. Please, enter the password: ", True
)
else:
passwd = self.ask_password("Please, enter the wallet password: ", False)
return passwd.encode("utf8")
async def save_account(self, file):
"""
Stores account data
:param file:
:return:
"""
if self.wallet_salt is None:
self.wallet_salt = crypto.random_bytes(32)
# Wallet view key encryption
wallet_enc_key = misc.wallet_enc_key(self.wallet_salt, self.wallet_password)
ciphertext = chacha_poly.encrypt_pack(
wallet_enc_key, crypto.encodeint(self.priv_view)
)
with open(file, "w") as fh:
data = {
"view_key_enc": binascii.hexlify(ciphertext).decode("ascii"),
"address": self.address.decode("ascii"),
"network_type": self.network_type,
"wallet_salt": binascii.hexlify(self.wallet_salt).decode("ascii"),
"rpc_addr": self.rpc_addr,
"wallet_file": self.wallet_file,
"monero_bin": self.monero_bin,
}
json.dump(data, fh, indent=2)
async def check_existing_wallet_file(self, key_file):
"""
Checks existing wallet file correctness
:param key_file:
:return:
"""
wl = await wallet.load_keys_file(key_file, self.wallet_password)
addr = wl["key_data"]["m_keys"]["m_account_address"]
spend_pub = addr["m_spend_public_key"]
view_pub = addr["m_view_public_key"]
match = spend_pub == crypto.encodepoint(
self.pub_spend
) and view_pub == crypto.encodepoint(self.pub_view)
net_ver = monero.net_version(self.network_type, False)
addr = monero.encode_addr(net_ver, spend_pub, view_pub)
return addr, match
async def wallet_restore_param(self):
self.poutput(
"Creating a new wallet file, please enter the blockchain height to start a restore of the wallet."
)
self.poutput(
" - Restore height should be a little less than your first incoming transaction to the wallet."
)
self.poutput(' - If the wallet was never used before, enter "-"')
self.poutput(
' - If you are not sure enter "0" to start from the beginning (may take few minutes)'
)
self.poutput(" - You may enter also a date in the format YYYY-MM-DD\n")
height = 0
sure_stage = False
while True:
if sure_stage:
if (
self.ask_proceed_quit(
"The height: %s. Is it correct? (y/n) " % height
)
== self.PROCEED_YES
):
break
height = misc.py_raw_input("Restore height: ").strip().lower()
if height == "-":
height = await self.wallet_obj.get_height()
sure_stage = True
continue
elif len(height) == 0:
height = 0
sure_stage = True
continue
m = re.match(r"^(\d{4})-(\d{1,2})-(\d{1,2})$", height)
if m:
year, month, day = int(m.group(1)), int(m.group(2)), int(m.group(3))
try:
height = await self.wallet_obj.get_blockchain_height_by_date(
year, month, day
)
sure_stage = True
continue
except Exception as e:
logger.warning("Could not resolve date to the height: %s" % e)
self.trace_logger.log(e)
r = self.ask_proceed_quit(
"Could not resolve date to height. Do you want to try again? (y/n) "
)
if r == self.PROCEED_YES:
continue
else:
return 0
else:
try:
height = int(height)
sure_stage = True
continue
except Exception as e:
self.poutput("Invalid format")
sure_stage = False
continue
return height
async def ensure_watch_only(self):
"""
Ensures watch only wallet for monero exists
:return:
"""
if self.wallet_file is None:
return
key_file = "%s.keys" % self.wallet_file
match, addr = False, None
if self.pub_view and os.path.exists(key_file):
logger.debug("Watch only wallet key file exists: %s" % key_file)
try:
addr, match = await self.check_existing_wallet_file(key_file)
except Exception as e:
logger.error("Wallet key file processing exception: %s" % e)
if not match:
logger.error("Key file address is not correct: %s" % addr)
if not self.args.no_init:
print("Please, move the file so Agent can create correct key file")
sys.exit(2)
return
if not addr and self.args.no_init:
logger.info("Device not initialized, skipping wallet setup")
return
if not self.args.no_init and not self.pub_view:
raise ValueError("Wallet key not loaded")
self.fresh_wallet = True
account_keys = xmrtypes.AccountKeys()
key_data = wallet.WalletKeyData()
restore_height = await self.wallet_restore_param()
self.poutput("Wallet restore height: %s" % restore_height)
wallet_data = wallet.WalletKeyFile()
wallet_data.key_data = key_data
wallet_data.watch_only = 1
wallet_data.testnet = self.network_type == monero.NetworkTypes.TESTNET
wallet_data.refresh_height = restore_height
key_data.m_creation_timestamp = int(time.time())
key_data.m_keys = account_keys
account_keys.m_account_address = xmrtypes.AccountPublicAddress(
m_spend_public_key=crypto.encodepoint(self.pub_spend),
m_view_public_key=crypto.encodepoint(self.pub_view),
)
account_keys.m_spend_secret_key = crypto.encodeint(crypto.sc_0())
account_keys.m_view_secret_key = crypto.encodeint(self.priv_view)
await wallet.save_keys_file(key_file, self.wallet_password, wallet_data)
logger.debug("Watch-only wallet keys generated: %s" % key_file)
async def open_account_passed(self):
"""
Loads passed credentials
:return:
"""
priv_view = self.args.view_key.encode("ascii")
self.priv_view = crypto.b16_to_scalar(priv_view)
self.set_network_type(
monero.NetworkTypes.TESTNET
if self.args.testnet
else monero.NetworkTypes.MAINNET
)
self.set_address(self.args.address.encode("ascii"))
self.wallet_file = self.args.watch_wallet
self.monero_bin = self.args.monero_bin
await self.open_with_keys(self.priv_view, self.address)
async def open_account_file(self, file):
"""
Opens account file
:param file:
:return:
"""
with open(file) as fh:
js = json.load(fh)
# Wallet key encryption
self.wallet_password = await self.prompt_password()
self.wallet_salt = common.defvalkey(js, "wallet_salt")
if self.wallet_salt is None:
self.wallet_salt = crypto.random_bytes(32)
else:
self.wallet_salt = binascii.unhexlify(self.wallet_salt)
# Wallet view key dec.
if "view_key" in js:
self.priv_view = crypto.b16_to_scalar(js["view_key"].encode("utf8"))
elif "view_key_enc" in js:
wallet_enc_key = misc.wallet_enc_key(self.wallet_salt, self.wallet_password)
plain = chacha_poly.decrypt_pack(
wallet_enc_key, binascii.unhexlify(js["view_key_enc"])
)
self.priv_view = crypto.decodeint(plain)
self.wallet_file = js["wallet_file"]
self.monero_bin = js["monero_bin"]
self.set_network_type(js["network_type"])
self.set_address(js["address"].encode("utf8"))
self.rpc_addr = js["rpc_addr"]
await self.open_with_keys(self.priv_view, self.address)
async def open_with_keys(self, view_key, address):
"""
Processess view key private + address
:param view_key:
:param address:
:return:
"""
self.pub_view = crypto.scalarmult_base(view_key)
addr_info = monero.decode_addr(address)
self.pub_spend = crypto.decodepoint(addr_info.spend_key)
if not crypto.point_eq(self.pub_view, crypto.decodepoint(addr_info.view_key)):
raise ValueError(
"Computed view public key does not match the one from address"
)
def set_address(self, address):
self.address = address
self.address_info = monero.decode_addr(self.address)
self.address_base_info = monero.decode_addr(self.address)
self.recompute_address()
def recompute_address(self):
D, C = monero.generate_sub_address_keys(
self.priv_view,
crypto.decodepoint(self.address_base_info.spend_key),
self.account_idx,
0,
)
self.address_info.recompute_sub(
crypto.encodepoint(D), crypto.encodepoint(C), self.account_idx
)
self.address = self.address_info.addr
self.update_prompt()
def set_account(self, new_accound_idx):
self.account_idx = new_accound_idx
self.recompute_address()
def wallet_rpc_main(self, *args, **kwargs):
"""
Wallet RPC thread
:return:
"""
rpc_cmd = os.path.join(self.monero_bin, "monero-wallet-rpc")
if not os.path.exists(rpc_cmd):
logger.error("Wallet rpc binary not found: %s" % rpc_cmd)
sys.exit(1)
self.rpc_passwd = misc.gen_simple_passwd(16)
self.wallet_proxy.set_creds(["trezor", self.rpc_passwd])
args = [
"--daemon-address %s" % misc.escape_shell(self.rpc_addr),
"--wallet-file %s" % misc.escape_shell(self.wallet_file),
"--prompt-for-password",
"--rpc-login=trezor",
"--rpc-bind-port %s" % int(self.rpc_bind_port),
]
if self.args.testnet or self.network_type == monero.NetworkTypes.TESTNET:
args.append("--testnet")
if self.args.debug_rpc:
logger.debug("RPC credentials: trezor:%s" % self.rpc_passwd)
def preexec_function():
os.setpgrp()
cmd = "%s %s" % (rpc_cmd, " ".join(args))
feeder = misc.Feeder()
p = misc.run(
cmd,
input=feeder,
async_=True,
stdout=misc.Capture(timeout=0.1, buffer_size=1),
stderr=misc.Capture(timeout=0.1, buffer_size=1),
cwd=os.getcwd(),
env=None,
shell=True,
preexec_fn=preexec_function,
)
ret_code = 1
out_acc, err_acc = [], []
out_cur, err_cur = [""], [""]
logline_pattern = re.compile(r"^([^\s]+)\s+([^\s]+)\s+\[(.+?)\]\s+([^\s]+?)\s+")
passwd_set = False
def log_parse(line):
m = logline_pattern.match(line)