-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathclient.py
More file actions
1571 lines (1301 loc) · 56.3 KB
/
client.py
File metadata and controls
1571 lines (1301 loc) · 56.3 KB
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
# This file is part of the TREZOR project.
#
# Copyright (C) 2012-2016 Marek Palatinus <slush@satoshilabs.com>
# Copyright (C) 2012-2016 Pavol Rusnak <stick@satoshilabs.com>
# Copyright (C) 2016 Jochen Hoenicke <hoenicke@gmail.com>
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library. If not, see <http://www.gnu.org/licenses/>.
#
# The script has been modified for KeepKey Device.
from __future__ import print_function, absolute_import
import os
import sys
import time
import binascii
import hashlib
import unicodedata
import json
import getpass
import copy
from mnemonic import Mnemonic
from . import tools
from . import mapping
from . import messages_pb2 as proto
from . import messages_ethereum_pb2 as eth_proto
from . import messages_eos_pb2 as eos_proto
from . import messages_nano_pb2 as nano_proto
from . import messages_cosmos_pb2 as cosmos_proto
from . import messages_osmosis_pb2 as osmosis_proto
from . import messages_ripple_pb2 as ripple_proto
from . import messages_tendermint_pb2 as tendermint_proto
from . import messages_thorchain_pb2 as thorchain_proto
from . import messages_mayachain_pb2 as mayachain_proto
from . import types_pb2 as types
from . import eos
from . import nano
from .debuglink import DebugLink
# try:
# from PIL import Image
# SCREENSHOT = True
# except:
# SCREENSHOT = False
SCREENSHOT = False
DEFAULT_CURVE = 'secp256k1'
# monkeypatching: text formatting of protobuf messages
tools.monkeypatch_google_protobuf_text_format()
def get_buttonrequest_value(code):
# Converts integer code to its string representation of ButtonRequestType
return [ k for k, v in types.ButtonRequestType.items() if v == code][0]
def pprint(msg):
msg_class = msg.__class__.__name__
msg_size = msg.ByteSize()
"""
msg_ser = msg.SerializeToString()
msg_id = mapping.get_type(msg)
msg_json = json.dumps(protobuf_json.pb2json(msg))
"""
if isinstance(msg, proto.FirmwareUpload):
return "<%s> (%d bytes):\n" % (msg_class, msg_size)
else:
return "<%s> (%d bytes):\n%s" % (msg_class, msg_size, msg)
def log(msg):
sys.stderr.write(msg + '\n')
sys.stderr.flush()
def log_cr(msg):
sys.stdout.write('\r' + msg)
sys.stdout.flush()
def format_mnemonic(word_pos, character_pos):
return "WORD %d: %s" % (word_pos, character_pos * '*')
def getch():
try:
import termios
except ImportError:
# Non-POSIX. Return msvcrt's (Windows') getch.
import msvcrt
return msvcrt.getch()
# POSIX system. Create and return a getch that manipulates the tty.
import sys, tty
def _getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
return _getch()
class CallException(Exception):
def __init__(self, code, message):
super(CallException, self).__init__()
self.args = [code, message]
class PinException(CallException):
pass
class field(object):
# Decorator extracts single value from
# protobuf object. If the field is not
# present, raises an exception.
def __init__(self, field):
self.field = field
def __call__(self, f):
def wrapped_f(*args, **kwargs):
ret = f(*args, **kwargs)
ret.HasField(self.field)
return getattr(ret, self.field)
return wrapped_f
class expect(object):
# Decorator checks if the method
# returned one of expected protobuf messages
# or raises an exception
def __init__(self, *expected):
self.expected = expected
def __call__(self, f):
def wrapped_f(*args, **kwargs):
ret = f(*args, **kwargs)
if not isinstance(ret, self.expected):
raise Exception("Got %s, expected %s" % (ret.__class__, self.expected))
return ret
return wrapped_f
def session(f):
# Decorator wraps a BaseClient method
# with session activation / deactivation
def wrapped_f(*args, **kwargs):
client = args[0]
try:
client.transport.session_begin()
return f(*args, **kwargs)
finally:
client.transport.session_end()
return wrapped_f
def normalize_nfc(txt):
if sys.version_info[0] < 3:
if isinstance(txt, unicode):
return unicodedata.normalize('NFC', txt)
if isinstance(txt, str):
return unicodedata.normalize('NFC', txt.decode('utf-8'))
else:
if isinstance(txt, bytes):
return unicodedata.normalize('NFC', txt.decode('utf-8'))
if isinstance(txt, str):
return unicodedata.normalize('NFC', txt)
raise Exception('unicode/str or bytes/str expected')
class BaseClient(object):
# Implements very basic layer of sending raw protobuf
# messages to device and getting its response back.
def __init__(self, transport, **kwargs):
self.transport = transport
self.verbose = False
super(BaseClient, self).__init__() # *args, **kwargs)
def cancel(self):
self.transport.write(proto.Cancel())
@session
def call_raw(self, msg):
self.transport.write(msg)
return self.transport.read_blocking()
@session
def call_bridge(self, msg):
self.transport.bridgeWrite(msg)
return
@session
def call_bridge_read(self):
return self.transport.bridge_read_blocking()
@session
def call(self, msg):
resp = self.call_raw(msg)
handler_name = "callback_%s" % resp.__class__.__name__
handler = getattr(self, handler_name, None)
if handler != None:
msg = handler(resp)
if msg == None:
raise Exception("Callback %s must return protobuf message, not None" % handler)
resp = self.call(msg)
return resp
def callback_Failure(self, msg):
if msg.code in (types.Failure_PinInvalid,
types.Failure_PinCancelled, types.Failure_PinExpected):
raise PinException(msg.code, msg.message)
raise CallException(msg.code, msg.message)
def close(self):
self.transport.close()
class DebugWireMixin(object):
def call_raw(self, msg):
log("SENDING " + pprint(msg))
resp = super(DebugWireMixin, self).call_raw(msg)
log("RECEIVED " + pprint(resp))
return resp
class TextUIMixin(object):
# This class demonstrates easy test-based UI
# integration between the device and wallet.
# You can implement similar functionality
# by implementing your own GuiMixin with
# graphical widgets for every type of these callbacks.
def __init__(self, *args, **kwargs):
super(TextUIMixin, self).__init__(*args, **kwargs)
self.character_request_first_pass = True
def callback_ButtonRequest(self, msg):
# log("Sending ButtonAck for %s " % get_buttonrequest_value(msg.code))
return proto.ButtonAck()
def callback_RecoveryMatrix(self, msg):
if self.recovery_matrix_first_pass:
self.recovery_matrix_first_pass = False
log("Use the numeric keypad to describe positions. For the word list use only left and right keys. The layout is:")
log(" 7 8 9 7 | 9")
log(" 4 5 6 4 | 6")
log(" 1 2 3 1 | 3")
while True:
character = getch()
if character in ('\x03', '\x04'):
return proto.Cancel()
if character in ('\x08', '\x7f'):
return proto.WordAck(word='\x08')
# ignore middle column if only 6 keys requested.
if (msg.type == types.WordRequestType_Matrix6 and
character in ('2', '5', '8')):
continue
if (ord(character) >= ord('1') and ord(character) <= ord('9')):
return proto.WordAck(word=character)
def callback_PinMatrixRequest(self, msg):
if msg.type == 1:
desc = 'current PIN'
elif msg.type == 2:
desc = 'new PIN'
elif msg.type == 3:
desc = 'new PIN again'
else:
desc = 'PIN'
log("Use the numeric keypad to describe number positions. The layout is:")
log(" 7 8 9")
log(" 4 5 6")
log(" 1 2 3")
log("Please enter %s: " % desc)
pin = getpass.getpass('')
return proto.PinMatrixAck(pin=pin)
def callback_PassphraseRequest(self, msg):
log("Passphrase required: ")
passphrase = getpass.getpass('')
log("Confirm your Passphrase: ")
if passphrase == getpass.getpass(''):
passphrase = normalize_nfc(passphrase)
return proto.PassphraseAck(passphrase=passphrase)
else:
log("Passphrase did not match! ")
exit()
def callback_CharacterRequest(self, msg):
if self.character_request_first_pass:
self.character_request_first_pass = False
log("Use recovery cipher on device to input mnemonic. Words are autocompleted at 3 or 4 characters.")
log("(use spacebar to progress to next word after match, use backspace to correct bad character or word entries)")
# format mnemonic for console
formatted_console = format_mnemonic(msg.word_pos + 1, msg.character_pos)
# clear the runway before we display formatted mnemonic
log_cr(' ' * 14)
log_cr(formatted_console)
while True:
character = getch().lower()
# capture escape
if character in ('\x03', '\x04'):
return proto.Cancel()
character_ascii = ord(character)
if character_ascii >= 97 and character_ascii <= 122 \
and msg.character_pos != 4:
# capture characters a-z
return proto.CharacterAck(character=character)
elif character_ascii == 32 and msg.word_pos < 23 \
and msg.character_pos >= 3:
# capture spaces
return proto.CharacterAck(character=' ')
elif character_ascii == 8 or character_ascii == 127 \
and (msg.word_pos > 0 or msg.character_pos > 0):
# capture backspaces
return proto.CharacterAck(delete=True)
elif character_ascii == 13 and msg.word_pos in (11, 17, 23):
# capture returns
log("")
return proto.CharacterAck(done=True)
class DebugLinkMixin(object):
# This class implements automatic responses
# and other functionality for unit tests
# for various callbacks, created in order
# to automatically pass unit tests.
#
# This mixing should be used only for purposes
# of unit testing, because it will fail to work
# without special DebugLink interface provided
# by the device.
def __init__(self, *args, **kwargs):
super(DebugLinkMixin, self).__init__(*args, **kwargs)
self.debug = None
self.in_with_statement = 0
self.button_wait = 0
self.screenshot_id = 0
# Always press Yes and provide correct pin
self.setup_debuglink(True, True)
self.auto_button = True
# Do not expect any specific response from device
self.expected_responses = None
# Use blank passphrase
self.set_passphrase('')
def close(self):
super(DebugLinkMixin, self).close()
if self.debug:
self.debug.close()
def set_debuglink(self, debug_transport):
self.debug = DebugLink(debug_transport)
def set_buttonwait(self, secs):
self.button_wait = secs
def __enter__(self):
# For usage in with/expected_responses
self.in_with_statement += 1
return self
def __exit__(self, _type, value, traceback):
self.in_with_statement -= 1
if _type != None:
# Another exception raised
return False
# return isinstance(value, TypeError)
# Evaluate missed responses in 'with' statement
if self.expected_responses != None and len(self.expected_responses):
raise Exception("Some of expected responses didn't come from device: %s" % \
[ pprint(x) for x in self.expected_responses ])
# Cleanup
self.expected_responses = None
return False
def set_expected_responses(self, expected):
if not self.in_with_statement:
raise Exception("Must be called inside 'with' statement")
self.expected_responses = expected
def setup_debuglink(self, button, pin_correct):
self.button = button # True -> YES button, False -> NO button
self.pin_correct = pin_correct
def set_passphrase(self, passphrase):
self.passphrase = normalize_nfc(passphrase)
def set_mnemonic(self, mnemonic):
self.mnemonic = normalize_nfc(mnemonic).split(' ')
def call_raw(self, msg):
if SCREENSHOT and self.debug:
layout = self.debug.read_layout()
im = Image.new("RGB", (128, 64))
pix = im.load()
for x in range(128):
for y in range(64):
rx, ry = 127 - x, 63 - y
if (ord(layout[rx + (ry / 8) * 128]) & (1 << (ry % 8))) > 0:
pix[x, y] = (255, 255, 255)
im.save('scr%05d.png' % self.screenshot_id)
self.screenshot_id += 1
resp = super(DebugLinkMixin, self).call_raw(msg)
self._check_request(resp)
return resp
def _check_request(self, msg):
if self.expected_responses != None:
try:
expected = self.expected_responses.pop(0)
except IndexError:
raise CallException(types.Failure_Other,
"Got %s, but no message has been expected" % pprint(msg))
if msg.__class__ != expected.__class__:
raise CallException(types.Failure_Other,
"Expected %s, got %s" % (pprint(expected), pprint(msg)))
fields = expected.ListFields() # only filled (including extensions)
for field, value in fields:
if not msg.HasField(field.name) or getattr(msg, field.name) != value:
raise CallException(types.Failure_Other,
"Expected %s, got %s" % (pprint(expected), pprint(msg)))
def callback_ButtonRequest(self, msg):
if self.verbose:
log("ButtonRequest code: " + get_buttonrequest_value(msg.code))
if self.auto_button:
if self.verbose:
log("Pressing button " + str(self.button))
if self.button_wait:
if self.verbose:
log("Waiting %d seconds " % self.button_wait)
time.sleep(self.button_wait)
self.debug.press_button(self.button)
return proto.ButtonAck()
def callback_PinMatrixRequest(self, msg):
if self.pin_correct:
pin = self.debug.read_pin_encoded()
else:
pin = '444222'
return proto.PinMatrixAck(pin=pin)
def callback_PassphraseRequest(self, msg):
if self.verbose:
log("Provided passphrase: '%s'" % self.passphrase)
return proto.PassphraseAck(passphrase=self.passphrase)
class ProtocolMixin(object):
PRIME_DERIVATION_FLAG = 0x80000000
VENDORS = ('keepkey.com',)
def __init__(self, *args, **kwargs):
super(ProtocolMixin, self).__init__(*args, **kwargs)
self.init_device()
self.tx_api = None
def set_tx_api(self, tx_api):
self.tx_api = tx_api
def get_tx_api(self):
return self.tx_api
def init_device(self):
self.features = expect(proto.Features)(self.call)(proto.Initialize())
if str(self.features.vendor) not in self.VENDORS:
raise Exception("Unsupported device")
def _get_local_entropy(self):
return os.urandom(32)
def _convert_prime(self, n):
# Convert minus signs to uint32 with flag
return [ int(abs(x) | self.PRIME_DERIVATION_FLAG) if x < 0 else x for x in n ]
@staticmethod
def expand_path(n):
# Convert string of bip32 path to list of uint32 integers with prime flags
# 0/-1/1' -> [0, 0x80000001, 0x80000001]
if not n:
return []
n = n.split('/')
# m/a/b/c => a/b/c
if n[0] == 'm':
n = n[1:]
# coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c
# https://github.com/satoshilabs/slips/blob/master/slip-0044.md
coins = {
"Bitcoin": 0,
"Testnet": 1,
"Litecoin": 2,
"Dogecoin": 3,
"Dash": 5,
"Namecoin": 7,
"Digibyte": 20,
"Bitsend": 91,
"Groestlcoin": 17,
"Zcash": 133,
"BitcoinCash": 145,
"Bitcore": 160,
"Megacoin": 217,
"Bitcloud": 218,
"Axe": 4242,
}
if n[0] in coins:
n = ["44'", "%d'" % coins[n[0]] ] + n[1:]
path = []
for x in n:
prime = False
if x.endswith("'"):
x = x.replace('\'', '')
prime = True
if x.startswith('-'):
prime = True
x = abs(int(x))
if prime:
x |= ProtocolMixin.PRIME_DERIVATION_FLAG
path.append(x)
return path
@expect(proto.PublicKey)
def get_public_node(self, n, ecdsa_curve_name=DEFAULT_CURVE, show_display=False, coin_name=None, script_type=types.SPENDADDRESS):
n = self._convert_prime(n)
if not ecdsa_curve_name:
ecdsa_curve_name=DEFAULT_CURVE
return self.call(proto.GetPublicKey(address_n=n, ecdsa_curve_name=ecdsa_curve_name, show_display=show_display, coin_name=coin_name, script_type=script_type))
@field('address')
@expect(proto.Address)
def get_address(self, coin_name, n, show_display=False, multisig=None, script_type=types.SPENDADDRESS):
n = self._convert_prime(n)
if multisig:
return self.call(proto.GetAddress(address_n=n, coin_name=coin_name, show_display=show_display, multisig=multisig, script_type=script_type))
else:
return self.call(proto.GetAddress(address_n=n, coin_name=coin_name, show_display=show_display, script_type=script_type))
@field('address')
@expect(eth_proto.EthereumAddress)
def ethereum_get_address(self, n, show_display=False, multisig=None):
n = self._convert_prime(n)
return self.call(eth_proto.EthereumGetAddress(address_n=n, show_display=show_display))
@expect(eth_proto.EthereumTypedDataSignature)
def ethereum_sign_typed_data_hash(self, n, ds_hash, m_hash=None):
n = self._convert_prime(n)
msg = eth_proto.EthereumSignTypedHash(
address_n=n,
domain_separator_hash=ds_hash
)
if m_hash:
msg.message_hash = m_hash
response = self.call(msg)
return response
@expect(eth_proto.EthereumTypedDataSignature)
def e712_types_values(self, n, types_prop, ptype_prop, value_prop, typevals):
msg = eth_proto.Ethereum712TypesValues(
address_n = self._convert_prime(n),
eip712types = types_prop,
eip712primetype = ptype_prop,
eip712data = value_prop,
eip712typevals = typevals
)
response = self.call(msg)
return response
@expect(eth_proto.EthereumMessageSignature)
def ethereum_sign_message(self, n, message):
n = self._convert_prime(n)
msg = eth_proto.EthereumSignMessage(
address_n=n,
message=message
)
response = self.call(msg)
return response
def ethereum_verify_message(self, addr, signature, message):
msg = eth_proto.EthereumVerifyMessage(
address=addr,
signature=signature,
message=message
)
response = self.call(msg)
return response
@session
def ethereum_sign_tx(self, n, nonce, gas_limit, value, gas_price=None, max_fee_per_gas=None, max_priority_fee_per_gas=None, to=None, to_n=None, address_type=None, data=None, chain_id=None):
from keepkeylib.tools import int_to_big_endian
if gas_price is None and max_fee_per_gas is None:
raise Exception("Either gas_price or max_fee_per_gas must be provided")
n = self._convert_prime(n)
if address_type == types.TRANSFER: #Ethereum transfer transaction
msg = eth_proto.EthereumSignTx(
address_n=n,
nonce=int_to_big_endian(nonce),
gas_price=int_to_big_endian(gas_price) if gas_price else None,
gas_limit=int_to_big_endian(gas_limit),
max_fee_per_gas=int_to_big_endian(max_fee_per_gas) if max_fee_per_gas else None ,
max_priority_fee_per_gas=int_to_big_endian(max_priority_fee_per_gas) if max_priority_fee_per_gas else None,
value=int_to_big_endian(value),
to_address_n=to_n,
address_type=address_type,
type=2 if max_fee_per_gas else None
)
else:
msg = eth_proto.EthereumSignTx(
address_n=n,
nonce=int_to_big_endian(nonce),
gas_price=int_to_big_endian(gas_price) if gas_price else None,
gas_limit=int_to_big_endian(gas_limit),
max_fee_per_gas=int_to_big_endian(max_fee_per_gas) if max_fee_per_gas else None,
max_priority_fee_per_gas=int_to_big_endian(max_priority_fee_per_gas) if max_priority_fee_per_gas else None,
value=int_to_big_endian(value),
type=2 if max_fee_per_gas else None
)
if to:
msg.to = to
if data:
msg.data_length = len(data)
data, chunk = data[1024:], data[:1024]
msg.data_initial_chunk = chunk
if chain_id:
msg.chain_id = chain_id
response = self.call(msg)
while response.HasField('data_length'):
data_length = response.data_length
data, chunk = data[data_length:], data[:data_length]
response = self.call(eth_proto.EthereumTxAck(data_chunk=chunk))
if address_type:
return response.signature_v, response.signature_r, response.signature_s, response.hash, response.signature_der
else:
return response.signature_v, response.signature_r, response.signature_s
@expect(eos_proto.EosPublicKey)
def eos_get_public_key(self, address_n, show_display=True, legacy=True):
msg = eos_proto.EosGetPublicKey(
address_n=address_n,
show_display=show_display,
kind = eos_proto.EOS if legacy else eos_proto.EOS_K1
)
return self.call(msg)
@session
def eos_sign_tx_raw(self, msg, actions):
response = self.call(msg)
for common, action in actions:
if isinstance(action, eos_proto.EosActionTransfer):
msg = eos_proto.EosTxActionAck(common=common, transfer=action)
elif isinstance(action, eos_proto.EosActionDelegate):
msg = eos_proto.EosTxActionAck(common=common, delegate=action)
elif isinstance(action, eos_proto.EosActionUndelegate):
msg = eos_proto.EosTxActionAck(common=common, undelegate=action)
elif isinstance(action, eos_proto.EosActionRefund):
msg = eos_proto.EosTxActionAck(common=common, refund=action)
elif isinstance(action, eos_proto.EosActionBuyRam):
msg = eos_proto.EosTxActionAck(common=common, buy_ram=action)
elif isinstance(action, eos_proto.EosActionBuyRamBytes):
msg = eos_proto.EosTxActionAck(common=common, buy_ram_bytes=action)
elif isinstance(action, eos_proto.EosActionSellRam):
msg = eos_proto.EosTxActionAck(common=common, sell_ram=action)
elif isinstance(action, eos_proto.EosActionVoteProducer):
msg = eos_proto.EosTxActionAck(common=common, vote_producer=action)
elif isinstance(action, eos_proto.EosActionUpdateAuth):
msg = eos_proto.EosTxActionAck(common=common, update_auth=action)
elif isinstance(action, eos_proto.EosActionDeleteAuth):
msg = eos_proto.EosTxActionAck(common=common, delete_auth=action)
elif isinstance(action, eos_proto.EosActionUnlinkAuth):
msg = eos_proto.EosTxActionAck(common=common, unlink_auth=action)
elif isinstance(action, eos_proto.EosActionLinkAuth):
msg = eos_proto.EosTxActionAck(common=common, link_auth=action)
elif isinstance(action, eos_proto.EosActionNewAccount):
msg = eos_proto.EosTxActionAck(common=common, new_account=action)
elif isinstance(action, eos_proto.EosActionUnknown):
msg = eos_proto.EosTxActionAck(common=common, unknown=action)
else:
raise Exception("Unknown EOS Action")
response = self.call(msg)
if not isinstance(response, eos_proto.EosSignedTx):
raise Exception("Unexpected EOS signing response")
return response
@session
def eos_sign_tx(self, n, transaction):
tx = eos.parse_transaction_json(copy.deepcopy(transaction))
header = eos_proto.EosTxHeader(
expiration=tx.expiration,
ref_block_num=tx.ref_block_num,
ref_block_prefix=tx.ref_block_prefix,
max_net_usage_words=tx.net_usage_words,
max_cpu_usage_ms=tx.max_cpu_usage_ms,
delay_sec=tx.delay_sec)
msg = eos_proto.EosSignTx(
address_n=n,
chain_id=tx.chain_id,
header=header,
num_actions=tx.num_actions)
response = self.call(msg)
try:
while isinstance(response, eos_proto.EosTxActionRequest):
a = eos.parse_action(tx.actions.pop(0))
if isinstance(a, list):
while len(a) and isinstance(response, eos_proto.EosTxActionRequest):
response = self.call(a.pop(0))
else:
response = self.call(a)
except IndexError:
# pop from empty list
raise Exception("Unexpected EOS signing response")
if not isinstance(response, eos_proto.EosSignedTx):
raise Exception("Unexpected EOS signing response")
return response
@expect(nano_proto.NanoAddress)
def nano_get_address(self, coin_name, address_n, show_display=False):
msg = nano_proto.NanoGetAddress(
coin_name=coin_name,
address_n=address_n,
show_display=show_display)
return self.call(msg)
@expect(nano_proto.NanoSignedTx)
def nano_sign_tx(
self, coin_name, address_n,
grandparent_hash=None,
parent_link=None,
parent_representative=None,
parent_balance=None,
link_hash=None,
link_recipient=None,
link_recipient_n=None,
representative=None,
balance=None,
):
parent_block = None
if (grandparent_hash is not None or
parent_link is not None or
parent_representative is not None or
parent_balance is not None):
parent_block = nano_proto.NanoSignTx.ParentBlock(
parent_hash=grandparent_hash,
link=parent_link,
representative=parent_representative,
balance=nano.encode_balance(parent_balance),
)
msg = nano_proto.NanoSignTx(
coin_name=coin_name,
address_n=address_n,
parent_block=parent_block,
link_hash=link_hash,
link_recipient=link_recipient,
link_recipient_n=link_recipient_n,
representative=representative,
balance=nano.encode_balance(balance),
)
return self.call(msg)
@field('address')
@expect(osmosis_proto.OsmosisAddress)
def osmosis_get_address(self, address_n, show_display=False):
return self.call(
osmosis_proto.OsmosisGetAddress(address_n=address_n, show_display=show_display)
)
@session
def osmosis_sign_tx(
self,
address_n,
account_number,
chain_id,
fee,
gas,
msgs,
memo,
sequence,
):
resp = self.call(osmosis_proto.OsmosisSignTx(
address_n=address_n,
account_number=account_number,
chain_id=chain_id,
fee_amount=fee,
gas=gas,
memo=memo,
sequence=sequence,
msg_count=len(msgs)
))
for msg in msgs:
if not isinstance(resp, osmosis_proto.OsmosisMsgRequest):
raise CallException(
"Osmosis.ExpectedMsgRequest",
"Message request expected but not received.",
)
if msg['type'] == "osmosis-sdk/MsgSend":
if len(msg['value']['amount']) != 1:
raise CallException("Osmosis.MsgSend", "Multiple amounts per msg not supported")
denom = msg['value']['amount'][0]['denom']
if denom != 'uatom':
raise CallException("Osmosis.MsgSend", "Unsupported denomination: " + denom)
resp = self.call(osmosis_proto.OsmosisMsgAck(
send=osmosis_proto.OsmosisMsgSend(
from_address=msg['value']['from_address'],
to_address=msg['value']['to_address'],
amount=int(msg['value']['amount'][0]['amount']),
address_type=types.SPEND,
)
))
else:
raise CallException(
"Osmosis.UnknownMsg",
"Osmosis message %s is not yet supported" % (msg['type'],)
)
if not isinstance(resp, osmosis_proto.OsmosisSignedTx):
raise CallException(
"Osmosis.UnexpectedEndOfOperations",
"Reached end of operations without a signature.",
)
return resp
@field('address')
@expect(cosmos_proto.CosmosAddress)
def cosmos_get_address(self, address_n, show_display=False):
return self.call(
cosmos_proto.CosmosGetAddress(address_n=address_n, show_display=show_display)
)
@session
def cosmos_sign_tx(
self,
address_n,
account_number,
chain_id,
fee,
gas,
msgs,
memo,
sequence,
):
resp = self.call(cosmos_proto.CosmosSignTx(
address_n=address_n,
account_number=account_number,
chain_id=chain_id,
fee_amount=fee,
gas=gas,
memo=memo,
sequence=sequence,
msg_count=len(msgs)
))
for msg in msgs:
if not isinstance(resp, cosmos_proto.CosmosMsgRequest):
raise CallException(
"Cosmos.ExpectedMsgRequest",
"Message request expected but not received.",
)
if msg['type'] == "cosmos-sdk/MsgSend":
if len(msg['value']['amount']) != 1:
raise CallException("Cosmos.MsgSend", "Multiple amounts per msg not supported")
denom = msg['value']['amount'][0]['denom']
if denom != 'uatom':
raise CallException("Cosmos.MsgSend", "Unsupported denomination: " + denom)
resp = self.call(cosmos_proto.CosmosMsgAck(
send=cosmos_proto.CosmosMsgSend(
from_address=msg['value']['from_address'],
to_address=msg['value']['to_address'],
amount=int(msg['value']['amount'][0]['amount']),
address_type=types.SPEND,
)
))
else:
raise CallException(
"Cosmos.UnknownMsg",
"Cosmos message %s is not yet supported" % (msg['type'],)
)
if not isinstance(resp, cosmos_proto.CosmosSignedTx):
raise CallException(
"Cosmos.UnexpectedEndOfOperations",
"Reached end of operations without a signature.",
)
return resp
@field('address')
@expect(thorchain_proto.ThorchainAddress)
def thorchain_get_address(self, address_n, show_display=False, testnet=False):
return self.call(
thorchain_proto.ThorchainGetAddress(address_n=address_n, show_display=show_display, testnet=testnet)
)
@session
def thorchain_sign_tx(
self,
address_n,
account_number,
chain_id,
fee,
gas,
msgs,
memo,
sequence,
testnet=None
):
resp = self.call(thorchain_proto.ThorchainSignTx(
address_n=address_n,
account_number=account_number,
chain_id=chain_id,
fee_amount=fee,
gas=gas,
memo=memo,
sequence=sequence,
msg_count=len(msgs),
testnet=testnet
))
for msg in msgs:
if not isinstance(resp, thorchain_proto.ThorchainMsgRequest):