2018-06-21 14:28:34 +00:00
|
|
|
# This file is part of the Trezor project.
|
2016-11-25 21:53:55 +00:00
|
|
|
#
|
2018-06-21 14:28:34 +00:00
|
|
|
# Copyright (C) 2012-2018 SatoshiLabs and contributors
|
2016-11-25 21:53:55 +00:00
|
|
|
#
|
|
|
|
# This library is free software: you can redistribute it and/or modify
|
2018-06-21 14:28:34 +00:00
|
|
|
# it under the terms of the GNU Lesser General Public License version 3
|
|
|
|
# as published by the Free Software Foundation.
|
2016-11-25 21:53:55 +00:00
|
|
|
#
|
|
|
|
# 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.
|
|
|
|
#
|
2018-06-21 14:28:34 +00:00
|
|
|
# You should have received a copy of the License along with this library.
|
|
|
|
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
|
2018-11-08 17:15:49 +00:00
|
|
|
|
2018-11-02 15:20:10 +00:00
|
|
|
from copy import deepcopy
|
2018-08-10 11:33:14 +00:00
|
|
|
|
|
|
|
from mnemonic import Mnemonic
|
2016-05-20 20:27:20 +00:00
|
|
|
|
2018-11-02 16:12:41 +00:00
|
|
|
from . import messages as proto, protobuf, tools
|
2018-09-13 16:47:19 +00:00
|
|
|
from .client import TrezorClient
|
2018-10-02 15:37:03 +00:00
|
|
|
from .tools import expect
|
2017-06-23 19:31:42 +00:00
|
|
|
|
2018-12-13 12:35:35 +00:00
|
|
|
EXPECTED_RESPONSES_CONTEXT_LINES = 3
|
|
|
|
|
2012-12-13 19:05:04 +00:00
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
class DebugLink:
|
2019-01-31 14:23:39 +00:00
|
|
|
def __init__(self, transport, auto_interact=True):
|
2012-12-03 15:36:03 +00:00
|
|
|
self.transport = transport
|
2019-01-31 14:23:39 +00:00
|
|
|
self.allow_interactions = auto_interact
|
2018-11-08 17:08:02 +00:00
|
|
|
|
|
|
|
def open(self):
|
trezorlib: transport/protocol reshuffle
This commit breaks session handling (which matters with Bridge) and
regresses Bridge to an older code state. Both of these issues will be
rectified in subsequent commits.
Explanation of this big API reshuffle follows:
* protocols are moved to trezorlib.transport, and to a single common file.
* there is a cleaner definition of Transport and Protocol API (see below)
* fully valid mypy type hinting
* session handle counters and open handle counters mostly went away. Transports
and Protocols are meant to be "raw" APIs; TrezorClient will implement
context-handler-based sessions, session tracking, etc.
I'm calling this a "reshuffle" because it involved very small number of
code changes. Most of it is moving things around where they sit better.
The API changes are as follows.
Transport is now a thing that can:
* open and close sessions
* read and write protobuf messages
* enumerate and find devices
Some transports (all except bridge) are technically bytes-based and need
a separate protocol implementation (because we have two existing protocols,
although only the first one is actually used). Hence a protocol superclass.
Protocol is a thing that *also* can:
* open and close sessions
* read and write protobuf messages
For that, it requires a `handle`.
Handle is a physical layer for a protocol. It can:
* open and close some sort of device connection
(this is distinct from session! Connection is a channel over which you can
send data. Session is a logical arrangement on top of that; you can have
multiple sessions on a single connection.)
* read and write 64-byte chunks of data
With that, we introduce ProtocolBasedTransport, which simply delegates
the appropriate Transport functionality to respective Protocol methods.
hid and webusb transports are ProtocolBasedTransport-s that provide separate
device handles. HidHandle and WebUsbHandle existed before, but the distinction
of functionality between a Transport and its Handle was unclear. Some methods
were moved and now the handles implement the Handle API, while the transports
provide the enumeration parts of the Transport API, as well as glue between
the respective Protocols and Handles.
udp transport is also a ProtocolBasedTransport, but it acts as its own handle.
(That might be changed. For now, I went with the pre-existing structure.)
In addition, session_begin/end is renamed to begin/end_session to keep
consistent verb_noun naming.
2018-11-08 14:24:28 +00:00
|
|
|
self.transport.begin_session()
|
2012-12-13 19:05:04 +00:00
|
|
|
|
2014-02-13 15:46:21 +00:00
|
|
|
def close(self):
|
trezorlib: transport/protocol reshuffle
This commit breaks session handling (which matters with Bridge) and
regresses Bridge to an older code state. Both of these issues will be
rectified in subsequent commits.
Explanation of this big API reshuffle follows:
* protocols are moved to trezorlib.transport, and to a single common file.
* there is a cleaner definition of Transport and Protocol API (see below)
* fully valid mypy type hinting
* session handle counters and open handle counters mostly went away. Transports
and Protocols are meant to be "raw" APIs; TrezorClient will implement
context-handler-based sessions, session tracking, etc.
I'm calling this a "reshuffle" because it involved very small number of
code changes. Most of it is moving things around where they sit better.
The API changes are as follows.
Transport is now a thing that can:
* open and close sessions
* read and write protobuf messages
* enumerate and find devices
Some transports (all except bridge) are technically bytes-based and need
a separate protocol implementation (because we have two existing protocols,
although only the first one is actually used). Hence a protocol superclass.
Protocol is a thing that *also* can:
* open and close sessions
* read and write protobuf messages
For that, it requires a `handle`.
Handle is a physical layer for a protocol. It can:
* open and close some sort of device connection
(this is distinct from session! Connection is a channel over which you can
send data. Session is a logical arrangement on top of that; you can have
multiple sessions on a single connection.)
* read and write 64-byte chunks of data
With that, we introduce ProtocolBasedTransport, which simply delegates
the appropriate Transport functionality to respective Protocol methods.
hid and webusb transports are ProtocolBasedTransport-s that provide separate
device handles. HidHandle and WebUsbHandle existed before, but the distinction
of functionality between a Transport and its Handle was unclear. Some methods
were moved and now the handles implement the Handle API, while the transports
provide the enumeration parts of the Transport API, as well as glue between
the respective Protocols and Handles.
udp transport is also a ProtocolBasedTransport, but it acts as its own handle.
(That might be changed. For now, I went with the pre-existing structure.)
In addition, session_begin/end is renamed to begin/end_session to keep
consistent verb_noun naming.
2018-11-08 14:24:28 +00:00
|
|
|
self.transport.end_session()
|
2016-01-12 23:17:38 +00:00
|
|
|
|
2014-02-25 18:31:31 +00:00
|
|
|
def _call(self, msg, nowait=False):
|
|
|
|
self.transport.write(msg)
|
|
|
|
if nowait:
|
2018-05-09 16:11:38 +00:00
|
|
|
return None
|
2017-08-24 12:29:27 +00:00
|
|
|
ret = self.transport.read()
|
2014-02-25 18:31:31 +00:00
|
|
|
return ret
|
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
def state(self):
|
|
|
|
return self._call(proto.DebugLinkGetState())
|
2014-02-06 22:34:13 +00:00
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
def read_pin(self):
|
|
|
|
state = self.state()
|
|
|
|
return state.pin, state.matrix
|
2014-02-06 22:34:13 +00:00
|
|
|
|
2013-09-01 01:34:36 +00:00
|
|
|
def read_pin_encoded(self):
|
2018-09-13 16:47:19 +00:00
|
|
|
return self.encode_pin(*self.read_pin())
|
2014-02-20 18:15:43 +00:00
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
def encode_pin(self, pin, matrix=None):
|
|
|
|
"""Transform correct PIN according to the displayed matrix."""
|
|
|
|
if matrix is None:
|
|
|
|
_, matrix = self.read_pin()
|
|
|
|
return "".join([str(matrix.index(p) + 1) for p in pin])
|
2016-01-12 23:17:38 +00:00
|
|
|
|
2014-02-06 22:34:13 +00:00
|
|
|
def read_layout(self):
|
2014-02-25 18:31:31 +00:00
|
|
|
obj = self._call(proto.DebugLinkGetState())
|
2014-02-06 22:34:13 +00:00
|
|
|
return obj.layout
|
|
|
|
|
2019-03-07 15:28:24 +00:00
|
|
|
def read_mnemonic_secret(self):
|
2014-02-25 18:31:31 +00:00
|
|
|
obj = self._call(proto.DebugLinkGetState())
|
2019-03-07 15:28:24 +00:00
|
|
|
return obj.mnemonic_secret
|
2014-02-06 22:34:13 +00:00
|
|
|
|
2014-03-07 16:25:55 +00:00
|
|
|
def read_recovery_word(self):
|
2014-02-25 18:31:31 +00:00
|
|
|
obj = self._call(proto.DebugLinkGetState())
|
2014-03-07 16:25:55 +00:00
|
|
|
return (obj.recovery_fake_word, obj.recovery_word_pos)
|
2014-02-20 18:15:43 +00:00
|
|
|
|
2014-03-07 16:25:55 +00:00
|
|
|
def read_reset_word(self):
|
2014-02-25 18:31:31 +00:00
|
|
|
obj = self._call(proto.DebugLinkGetState())
|
2014-03-07 16:25:55 +00:00
|
|
|
return obj.reset_word
|
|
|
|
|
2018-03-20 15:46:53 +00:00
|
|
|
def read_reset_word_pos(self):
|
|
|
|
obj = self._call(proto.DebugLinkGetState())
|
|
|
|
return obj.reset_word_pos
|
|
|
|
|
2014-03-07 16:25:55 +00:00
|
|
|
def read_reset_entropy(self):
|
|
|
|
obj = self._call(proto.DebugLinkGetState())
|
|
|
|
return obj.reset_entropy
|
2014-02-20 18:15:43 +00:00
|
|
|
|
2014-02-17 01:16:43 +00:00
|
|
|
def read_passphrase_protection(self):
|
2014-02-25 18:31:31 +00:00
|
|
|
obj = self._call(proto.DebugLinkGetState())
|
2014-02-17 01:16:43 +00:00
|
|
|
return obj.passphrase_protection
|
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
def input(self, word=None, button=None, swipe=None):
|
2019-01-31 14:23:39 +00:00
|
|
|
if not self.allow_interactions:
|
|
|
|
return
|
2018-09-13 16:47:19 +00:00
|
|
|
decision = proto.DebugLinkDecision()
|
|
|
|
if button is not None:
|
|
|
|
decision.yes_no = button
|
|
|
|
elif word is not None:
|
|
|
|
decision.input = word
|
|
|
|
elif swipe is not None:
|
|
|
|
decision.up_down = swipe
|
|
|
|
else:
|
|
|
|
raise ValueError("You need to provide input data.")
|
|
|
|
self._call(decision, nowait=True)
|
|
|
|
|
2012-12-03 15:36:03 +00:00
|
|
|
def press_button(self, yes_no):
|
2014-02-25 18:31:31 +00:00
|
|
|
self._call(proto.DebugLinkDecision(yes_no=yes_no), nowait=True)
|
2012-12-13 19:05:04 +00:00
|
|
|
|
2012-12-03 15:36:03 +00:00
|
|
|
def press_yes(self):
|
2018-09-13 16:47:19 +00:00
|
|
|
self.input(button=True)
|
2014-02-06 22:34:13 +00:00
|
|
|
|
2012-12-03 15:36:03 +00:00
|
|
|
def press_no(self):
|
2018-09-13 16:47:19 +00:00
|
|
|
self.input(button=False)
|
2018-03-20 15:46:53 +00:00
|
|
|
|
|
|
|
def swipe_up(self):
|
2018-09-13 16:47:19 +00:00
|
|
|
self.input(swipe=True)
|
2018-03-20 15:46:53 +00:00
|
|
|
|
|
|
|
def swipe_down(self):
|
2018-09-13 16:47:19 +00:00
|
|
|
self.input(swipe=False)
|
2018-03-20 15:46:53 +00:00
|
|
|
|
2013-10-11 01:51:45 +00:00
|
|
|
def stop(self):
|
2014-02-25 18:31:31 +00:00
|
|
|
self._call(proto.DebugLinkStop(), nowait=True)
|
2016-05-26 18:46:40 +00:00
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
@expect(proto.DebugLinkMemory, field="memory")
|
2016-05-26 18:46:40 +00:00
|
|
|
def memory_read(self, address, length):
|
2018-09-13 16:47:19 +00:00
|
|
|
return self._call(proto.DebugLinkMemoryRead(address=address, length=length))
|
2016-05-26 18:46:40 +00:00
|
|
|
|
|
|
|
def memory_write(self, address, memory, flash=False):
|
2018-08-13 16:21:24 +00:00
|
|
|
self._call(
|
|
|
|
proto.DebugLinkMemoryWrite(address=address, memory=memory, flash=flash),
|
|
|
|
nowait=True,
|
|
|
|
)
|
2016-05-26 18:46:40 +00:00
|
|
|
|
|
|
|
def flash_erase(self, sector):
|
2017-06-23 19:31:42 +00:00
|
|
|
self._call(proto.DebugLinkFlashErase(sector=sector), nowait=True)
|
2018-08-10 11:33:14 +00:00
|
|
|
|
|
|
|
|
2019-01-31 14:23:39 +00:00
|
|
|
class NullDebugLink(DebugLink):
|
|
|
|
def __init__(self):
|
|
|
|
super().__init__(None)
|
|
|
|
|
|
|
|
def open(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def _call(self, msg, nowait=False):
|
|
|
|
if not nowait:
|
|
|
|
if isinstance(msg, proto.DebugLinkGetState):
|
|
|
|
return proto.DebugLinkState()
|
|
|
|
else:
|
|
|
|
raise RuntimeError("unexpected call to a fake debuglink")
|
|
|
|
|
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
class DebugUI:
|
2018-10-02 15:18:13 +00:00
|
|
|
INPUT_FLOW_DONE = object()
|
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
def __init__(self, debuglink: DebugLink):
|
|
|
|
self.debuglink = debuglink
|
|
|
|
self.pin = None
|
|
|
|
self.passphrase = "sphinx of black quartz, judge my wov"
|
2018-10-02 15:18:13 +00:00
|
|
|
self.input_flow = None
|
2018-09-13 16:47:19 +00:00
|
|
|
|
2018-10-02 15:18:13 +00:00
|
|
|
def button_request(self, code):
|
|
|
|
if self.input_flow is None:
|
|
|
|
self.debuglink.press_yes()
|
|
|
|
elif self.input_flow is self.INPUT_FLOW_DONE:
|
|
|
|
raise AssertionError("input flow ended prematurely")
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
self.input_flow.send(code)
|
|
|
|
except StopIteration:
|
|
|
|
self.input_flow = self.INPUT_FLOW_DONE
|
2018-09-13 16:47:19 +00:00
|
|
|
|
2018-10-02 15:18:13 +00:00
|
|
|
def get_pin(self, code=None):
|
2018-09-13 16:47:19 +00:00
|
|
|
if self.pin:
|
|
|
|
return self.pin
|
|
|
|
else:
|
|
|
|
return self.debuglink.read_pin_encoded()
|
|
|
|
|
|
|
|
def get_passphrase(self):
|
|
|
|
return self.passphrase
|
|
|
|
|
|
|
|
|
|
|
|
class TrezorClientDebugLink(TrezorClient):
|
|
|
|
# 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.
|
|
|
|
|
2019-01-31 14:23:39 +00:00
|
|
|
def __init__(self, transport, auto_interact=True):
|
|
|
|
try:
|
|
|
|
debug_transport = transport.find_debug()
|
|
|
|
self.debug = DebugLink(debug_transport, auto_interact)
|
|
|
|
except Exception:
|
|
|
|
if not auto_interact:
|
|
|
|
self.debug = NullDebugLink()
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
self.ui = DebugUI(self.debug)
|
|
|
|
|
|
|
|
self.in_with_statement = 0
|
|
|
|
self.screenshot_id = 0
|
|
|
|
|
2018-11-02 15:20:10 +00:00
|
|
|
self.filters = {}
|
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
# Always press Yes and provide correct pin
|
|
|
|
self.setup_debuglink(True, True)
|
|
|
|
|
|
|
|
# Do not expect any specific response from device
|
|
|
|
self.expected_responses = None
|
2018-10-02 15:18:13 +00:00
|
|
|
self.current_response = None
|
2018-09-13 16:47:19 +00:00
|
|
|
|
|
|
|
# Use blank passphrase
|
|
|
|
self.set_passphrase("")
|
2018-10-02 15:18:13 +00:00
|
|
|
super().__init__(transport, ui=self.ui)
|
2018-09-13 16:47:19 +00:00
|
|
|
|
2018-11-08 17:08:02 +00:00
|
|
|
def open(self):
|
|
|
|
super().open()
|
|
|
|
self.debug.open()
|
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
def close(self):
|
2018-11-08 17:08:02 +00:00
|
|
|
self.debug.close()
|
2018-09-13 16:47:19 +00:00
|
|
|
super().close()
|
|
|
|
|
2018-11-02 15:20:10 +00:00
|
|
|
def set_filter(self, message_type, callback):
|
|
|
|
self.filters[message_type] = callback
|
|
|
|
|
|
|
|
def _filter_message(self, msg):
|
|
|
|
message_type = msg.__class__
|
|
|
|
callback = self.filters.get(message_type)
|
|
|
|
if callable(callback):
|
|
|
|
return callback(deepcopy(msg))
|
|
|
|
else:
|
|
|
|
return msg
|
2018-09-13 16:47:19 +00:00
|
|
|
|
2018-10-02 15:18:13 +00:00
|
|
|
def set_input_flow(self, input_flow):
|
2019-02-01 13:27:52 +00:00
|
|
|
if input_flow is None:
|
|
|
|
self.ui.input_flow = None
|
|
|
|
return
|
|
|
|
|
2018-10-02 15:18:13 +00:00
|
|
|
if callable(input_flow):
|
|
|
|
input_flow = input_flow()
|
|
|
|
if not hasattr(input_flow, "send"):
|
|
|
|
raise RuntimeError("input_flow should be a generator function")
|
|
|
|
self.ui.input_flow = input_flow
|
|
|
|
next(input_flow) # can't send before first yield
|
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
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 is not None:
|
|
|
|
# Another exception raised
|
|
|
|
return False
|
|
|
|
|
2018-10-03 12:00:24 +00:00
|
|
|
if self.expected_responses is None:
|
|
|
|
# no need to check anything else
|
|
|
|
return False
|
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
# return isinstance(value, TypeError)
|
|
|
|
# Evaluate missed responses in 'with' statement
|
2018-10-02 15:18:13 +00:00
|
|
|
if self.current_response < len(self.expected_responses):
|
|
|
|
self._raise_unexpected_response(None)
|
2018-09-13 16:47:19 +00:00
|
|
|
|
|
|
|
# Cleanup
|
|
|
|
self.expected_responses = None
|
2018-10-02 15:18:13 +00:00
|
|
|
self.current_response = None
|
2018-09-13 16:47:19 +00:00
|
|
|
return False
|
|
|
|
|
|
|
|
def set_expected_responses(self, expected):
|
|
|
|
if not self.in_with_statement:
|
|
|
|
raise RuntimeError("Must be called inside 'with' statement")
|
|
|
|
self.expected_responses = expected
|
2018-10-02 15:18:13 +00:00
|
|
|
self.current_response = 0
|
2018-09-13 16:47:19 +00:00
|
|
|
|
|
|
|
def setup_debuglink(self, button, pin_correct):
|
|
|
|
# self.button = button # True -> YES button, False -> NO button
|
|
|
|
if pin_correct:
|
|
|
|
self.ui.pin = None
|
|
|
|
else:
|
|
|
|
self.ui.pin = "444222"
|
|
|
|
|
|
|
|
def set_passphrase(self, passphrase):
|
|
|
|
self.ui.passphrase = Mnemonic.normalize_string(passphrase)
|
|
|
|
|
|
|
|
def set_mnemonic(self, mnemonic):
|
|
|
|
self.mnemonic = Mnemonic.normalize_string(mnemonic).split(" ")
|
|
|
|
|
2018-10-02 15:18:13 +00:00
|
|
|
def _raw_read(self):
|
2018-09-13 16:47:19 +00:00
|
|
|
__tracebackhide__ = True # for pytest # pylint: disable=W0612
|
|
|
|
|
|
|
|
# if SCREENSHOT and self.debug:
|
|
|
|
# from PIL import Image
|
|
|
|
|
|
|
|
# layout = self.debug.state().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
|
|
|
|
|
2018-10-02 15:18:13 +00:00
|
|
|
resp = super()._raw_read()
|
2018-11-02 15:20:10 +00:00
|
|
|
resp = self._filter_message(resp)
|
2018-09-13 16:47:19 +00:00
|
|
|
self._check_request(resp)
|
|
|
|
return resp
|
|
|
|
|
2018-11-02 15:20:10 +00:00
|
|
|
def _raw_write(self, msg):
|
|
|
|
return super()._raw_write(self._filter_message(msg))
|
|
|
|
|
2018-10-02 15:18:13 +00:00
|
|
|
def _raise_unexpected_response(self, msg):
|
2018-09-13 16:47:19 +00:00
|
|
|
__tracebackhide__ = True # for pytest # pylint: disable=W0612
|
|
|
|
|
2018-12-13 12:35:35 +00:00
|
|
|
start_at = max(self.current_response - EXPECTED_RESPONSES_CONTEXT_LINES, 0)
|
|
|
|
stop_at = min(
|
|
|
|
self.current_response + EXPECTED_RESPONSES_CONTEXT_LINES + 1,
|
|
|
|
len(self.expected_responses),
|
|
|
|
)
|
2018-10-02 15:18:13 +00:00
|
|
|
output = []
|
|
|
|
output.append("Expected responses:")
|
2018-12-13 12:35:35 +00:00
|
|
|
if start_at > 0:
|
|
|
|
output.append(" (...{} previous responses omitted)".format(start_at))
|
|
|
|
for i in range(start_at, stop_at):
|
|
|
|
exp = self.expected_responses[i]
|
2018-10-02 15:18:13 +00:00
|
|
|
prefix = " " if i != self.current_response else ">>> "
|
|
|
|
set_fields = {
|
|
|
|
key: value
|
|
|
|
for key, value in exp.__dict__.items()
|
|
|
|
if value is not None and value != []
|
|
|
|
}
|
|
|
|
oneline_str = ", ".join("{}={!r}".format(*i) for i in set_fields.items())
|
|
|
|
if len(oneline_str) < 60:
|
|
|
|
output.append(
|
|
|
|
"{}{}({})".format(prefix, exp.__class__.__name__, oneline_str)
|
2018-09-13 16:47:19 +00:00
|
|
|
)
|
2018-10-02 15:18:13 +00:00
|
|
|
else:
|
2018-12-13 12:35:35 +00:00
|
|
|
item = []
|
|
|
|
item.append("{}{}(".format(prefix, exp.__class__.__name__))
|
2018-10-02 15:18:13 +00:00
|
|
|
for key, value in set_fields.items():
|
2018-12-13 12:35:35 +00:00
|
|
|
item.append("{} {}={!r}".format(prefix, key, value))
|
|
|
|
item.append("{})".format(prefix))
|
|
|
|
output.append("\n".join(item))
|
|
|
|
if stop_at < len(self.expected_responses):
|
|
|
|
omitted = len(self.expected_responses) - stop_at
|
|
|
|
output.append(" (...{} following responses omitted)".format(omitted))
|
2018-10-02 15:18:13 +00:00
|
|
|
|
|
|
|
output.append("")
|
|
|
|
if msg is not None:
|
|
|
|
output.append("Actually received:")
|
2018-11-02 15:20:10 +00:00
|
|
|
output.append(protobuf.format_message(msg))
|
2018-10-02 15:18:13 +00:00
|
|
|
else:
|
|
|
|
output.append("This message was never received.")
|
|
|
|
raise AssertionError("\n".join(output))
|
2018-09-13 16:47:19 +00:00
|
|
|
|
2018-10-02 15:18:13 +00:00
|
|
|
def _check_request(self, msg):
|
|
|
|
__tracebackhide__ = True # for pytest # pylint: disable=W0612
|
|
|
|
if self.expected_responses is None:
|
|
|
|
return
|
|
|
|
|
|
|
|
if self.current_response >= len(self.expected_responses):
|
|
|
|
raise AssertionError(
|
2018-11-02 15:20:10 +00:00
|
|
|
"No more messages were expected, but we got:\n"
|
|
|
|
+ protobuf.format_message(msg)
|
2018-10-02 15:18:13 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
expected = self.expected_responses[self.current_response]
|
|
|
|
|
|
|
|
if msg.__class__ != expected.__class__:
|
|
|
|
self._raise_unexpected_response(msg)
|
|
|
|
|
|
|
|
for field, value in expected.__dict__.items():
|
|
|
|
if value is None or value == []:
|
|
|
|
continue
|
|
|
|
if getattr(msg, field) != value:
|
|
|
|
self._raise_unexpected_response(msg)
|
2018-09-13 16:47:19 +00:00
|
|
|
|
2018-10-02 15:18:13 +00:00
|
|
|
self.current_response += 1
|
2018-09-13 16:47:19 +00:00
|
|
|
|
|
|
|
def mnemonic_callback(self, _):
|
|
|
|
word, pos = self.debug.read_recovery_word()
|
|
|
|
if word != "":
|
|
|
|
return word
|
|
|
|
if pos != 0:
|
|
|
|
return self.mnemonic[pos - 1]
|
|
|
|
|
|
|
|
raise RuntimeError("Unexpected call")
|
|
|
|
|
|
|
|
|
2018-08-10 11:33:14 +00:00
|
|
|
@expect(proto.Success, field="message")
|
2018-08-13 16:21:24 +00:00
|
|
|
def load_device_by_mnemonic(
|
|
|
|
client,
|
|
|
|
mnemonic,
|
|
|
|
pin,
|
|
|
|
passphrase_protection,
|
|
|
|
label,
|
|
|
|
language="english",
|
|
|
|
skip_checksum=False,
|
|
|
|
expand=False,
|
|
|
|
):
|
2018-08-10 11:33:14 +00:00
|
|
|
# Convert mnemonic to UTF8 NKFD
|
|
|
|
mnemonic = Mnemonic.normalize_string(mnemonic)
|
|
|
|
|
|
|
|
# Convert mnemonic to ASCII stream
|
2018-09-06 14:21:15 +00:00
|
|
|
mnemonic = mnemonic.encode()
|
2018-08-10 11:33:14 +00:00
|
|
|
|
2018-08-13 16:21:24 +00:00
|
|
|
m = Mnemonic("english")
|
2018-08-10 11:33:14 +00:00
|
|
|
|
|
|
|
if expand:
|
|
|
|
mnemonic = m.expand(mnemonic)
|
|
|
|
|
|
|
|
if not skip_checksum and not m.check(mnemonic):
|
|
|
|
raise ValueError("Invalid mnemonic checksum")
|
|
|
|
|
|
|
|
if client.features.initialized:
|
2018-08-13 16:21:24 +00:00
|
|
|
raise RuntimeError(
|
2018-09-13 16:47:19 +00:00
|
|
|
"Device is initialized already. Call device.wipe() and try again."
|
2018-08-13 16:21:24 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
resp = client.call(
|
|
|
|
proto.LoadDevice(
|
|
|
|
mnemonic=mnemonic,
|
|
|
|
pin=pin,
|
|
|
|
passphrase_protection=passphrase_protection,
|
|
|
|
language=language,
|
|
|
|
label=label,
|
|
|
|
skip_checksum=skip_checksum,
|
|
|
|
)
|
|
|
|
)
|
2018-08-10 11:33:14 +00:00
|
|
|
client.init_device()
|
|
|
|
return resp
|
|
|
|
|
|
|
|
|
|
|
|
@expect(proto.Success, field="message")
|
|
|
|
def load_device_by_xprv(client, xprv, pin, passphrase_protection, label, language):
|
|
|
|
if client.features.initialized:
|
2018-08-13 16:21:24 +00:00
|
|
|
raise RuntimeError(
|
|
|
|
"Device is initialized already. Call wipe_device() and try again."
|
|
|
|
)
|
2018-08-10 11:33:14 +00:00
|
|
|
|
2018-08-13 16:21:24 +00:00
|
|
|
if xprv[0:4] not in ("xprv", "tprv"):
|
2018-08-10 11:33:14 +00:00
|
|
|
raise ValueError("Unknown type of xprv")
|
|
|
|
|
|
|
|
if not 100 < len(xprv) < 112: # yes this is correct in Python
|
|
|
|
raise ValueError("Invalid length of xprv")
|
|
|
|
|
|
|
|
node = proto.HDNodeType()
|
2018-09-12 22:44:08 +00:00
|
|
|
data = tools.b58decode(xprv, None).hex()
|
2018-08-10 11:33:14 +00:00
|
|
|
|
2018-09-12 22:44:08 +00:00
|
|
|
if data[90:92] != "00":
|
2018-08-10 11:33:14 +00:00
|
|
|
raise ValueError("Contain invalid private key")
|
|
|
|
|
2018-09-12 22:44:08 +00:00
|
|
|
checksum = (tools.btc_hash(bytes.fromhex(data[:156]))[:4]).hex()
|
2018-08-10 11:33:14 +00:00
|
|
|
if checksum != data[156:]:
|
|
|
|
raise ValueError("Checksum doesn't match")
|
|
|
|
|
|
|
|
# version 0488ade4
|
|
|
|
# depth 00
|
|
|
|
# fingerprint 00000000
|
|
|
|
# child_num 00000000
|
|
|
|
# chaincode 873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508
|
|
|
|
# privkey 00e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35
|
|
|
|
# checksum e77e9d71
|
|
|
|
|
|
|
|
node.depth = int(data[8:10], 16)
|
|
|
|
node.fingerprint = int(data[10:18], 16)
|
|
|
|
node.child_num = int(data[18:26], 16)
|
2018-09-12 22:44:08 +00:00
|
|
|
node.chain_code = bytes.fromhex(data[26:90])
|
|
|
|
node.private_key = bytes.fromhex(data[92:156]) # skip 0x00 indicating privkey
|
2018-08-10 11:33:14 +00:00
|
|
|
|
2018-08-13 16:21:24 +00:00
|
|
|
resp = client.call(
|
|
|
|
proto.LoadDevice(
|
|
|
|
node=node,
|
|
|
|
pin=pin,
|
|
|
|
passphrase_protection=passphrase_protection,
|
|
|
|
language=language,
|
|
|
|
label=label,
|
|
|
|
)
|
|
|
|
)
|
2018-08-10 11:33:14 +00:00
|
|
|
client.init_device()
|
|
|
|
return resp
|
|
|
|
|
|
|
|
|
|
|
|
@expect(proto.Success, field="message")
|
|
|
|
def self_test(client):
|
2018-08-10 13:18:34 +00:00
|
|
|
if client.features.bootloader_mode is not True:
|
2018-08-10 11:33:14 +00:00
|
|
|
raise RuntimeError("Device must be in bootloader mode")
|
|
|
|
|
2018-08-13 16:21:24 +00:00
|
|
|
return client.call(
|
|
|
|
proto.SelfTest(
|
|
|
|
payload=b"\x00\xFF\x55\xAA\x66\x99\x33\xCCABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\x00\xFF\x55\xAA\x66\x99\x33\xCC"
|
|
|
|
)
|
|
|
|
)
|