2018-06-21 14:28:34 +00:00
|
|
|
# This file is part of the Trezor project.
|
2016-11-25 21:53:55 +00:00
|
|
|
#
|
2019-05-29 16:44:09 +00:00
|
|
|
# Copyright (C) 2012-2019 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
|
|
|
|
2020-04-24 10:23:53 +00:00
|
|
|
import logging
|
2020-09-15 11:06:41 +00:00
|
|
|
import textwrap
|
2019-10-18 11:31:57 +00:00
|
|
|
from collections import namedtuple
|
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
|
|
|
|
2020-04-24 10:28:14 +00:00
|
|
|
from . import mapping, messages, protobuf
|
2018-09-13 16:47:19 +00:00
|
|
|
from .client import TrezorClient
|
2020-07-28 12:40:54 +00:00
|
|
|
from .exceptions import TrezorFailure
|
2020-04-24 10:23:53 +00:00
|
|
|
from .log import DUMP_BYTES
|
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
|
|
|
|
|
2019-10-18 11:31:57 +00:00
|
|
|
LayoutLines = namedtuple("LayoutLines", "lines text")
|
|
|
|
|
2020-04-24 10:23:53 +00:00
|
|
|
LOG = logging.getLogger(__name__)
|
|
|
|
|
2019-10-18 11:31:57 +00:00
|
|
|
|
|
|
|
def layout_lines(lines):
|
|
|
|
return LayoutLines(lines, " ".join(lines))
|
|
|
|
|
|
|
|
|
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):
|
2020-04-24 10:23:53 +00:00
|
|
|
LOG.debug(
|
|
|
|
"sending message: {}".format(msg.__class__.__name__),
|
|
|
|
extra={"protobuf": msg},
|
|
|
|
)
|
2020-03-05 16:38:31 +00:00
|
|
|
msg_type, msg_bytes = mapping.encode(msg)
|
2020-04-24 10:23:53 +00:00
|
|
|
LOG.log(
|
|
|
|
DUMP_BYTES,
|
|
|
|
"encoded as type {} ({} bytes): {}".format(
|
|
|
|
msg_type, len(msg_bytes), msg_bytes.hex()
|
|
|
|
),
|
|
|
|
)
|
2020-03-05 16:38:31 +00:00
|
|
|
self.transport.write(msg_type, msg_bytes)
|
2014-02-25 18:31:31 +00:00
|
|
|
if nowait:
|
2018-05-09 16:11:38 +00:00
|
|
|
return None
|
2020-04-24 10:23:53 +00:00
|
|
|
|
2020-03-05 16:38:31 +00:00
|
|
|
ret_type, ret_bytes = self.transport.read()
|
2020-04-24 10:23:53 +00:00
|
|
|
LOG.log(
|
|
|
|
DUMP_BYTES,
|
|
|
|
"received type {} ({} bytes): {}".format(
|
|
|
|
msg_type, len(msg_bytes), msg_bytes.hex()
|
|
|
|
),
|
|
|
|
)
|
|
|
|
msg = mapping.decode(ret_type, ret_bytes)
|
|
|
|
LOG.debug(
|
|
|
|
"received message: {}".format(msg.__class__.__name__),
|
|
|
|
extra={"protobuf": msg},
|
|
|
|
)
|
|
|
|
return msg
|
2014-02-25 18:31:31 +00:00
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
def state(self):
|
2020-04-24 10:28:14 +00:00
|
|
|
return self._call(messages.DebugLinkGetState())
|
2014-02-06 22:34:13 +00:00
|
|
|
|
2019-10-18 11:31:57 +00:00
|
|
|
def read_layout(self):
|
|
|
|
return layout_lines(self.state().layout_lines)
|
|
|
|
|
2019-10-16 15:38:48 +00:00
|
|
|
def wait_layout(self):
|
2020-04-24 10:28:14 +00:00
|
|
|
obj = self._call(messages.DebugLinkGetState(wait_layout=True))
|
2020-07-28 12:40:54 +00:00
|
|
|
if isinstance(obj, messages.Failure):
|
|
|
|
raise TrezorFailure(obj)
|
2019-10-18 11:31:57 +00:00
|
|
|
return layout_lines(obj.layout_lines)
|
2019-10-16 15:38:48 +00:00
|
|
|
|
2020-05-22 13:38:40 +00:00
|
|
|
def watch_layout(self, watch: bool) -> None:
|
|
|
|
"""Enable or disable watching layouts.
|
|
|
|
If disabled, wait_layout will not work.
|
|
|
|
|
|
|
|
The message is missing on T1. Use `TrezorClientDebugLink.watch_layout` for
|
|
|
|
cross-version compatibility.
|
|
|
|
"""
|
|
|
|
self._call(messages.DebugLinkWatchLayout(watch=watch))
|
|
|
|
|
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:
|
2020-04-24 10:16:17 +00:00
|
|
|
matrix = self.state().matrix
|
2020-04-27 10:42:37 +00:00
|
|
|
if matrix is None:
|
|
|
|
# we are on trezor-core
|
|
|
|
return pin
|
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
return "".join([str(matrix.index(p) + 1) for p in pin])
|
2016-01-12 23:17:38 +00:00
|
|
|
|
2014-03-07 16:25:55 +00:00
|
|
|
def read_recovery_word(self):
|
2020-04-24 10:16:17 +00:00
|
|
|
state = self.state()
|
|
|
|
return (state.recovery_fake_word, state.recovery_word_pos)
|
2014-02-20 18:15:43 +00:00
|
|
|
|
2014-03-07 16:25:55 +00:00
|
|
|
def read_reset_word(self):
|
2020-04-24 10:28:14 +00:00
|
|
|
state = self._call(messages.DebugLinkGetState(wait_word_list=True))
|
2020-04-24 10:16:17 +00:00
|
|
|
return state.reset_word
|
2014-03-07 16:25:55 +00:00
|
|
|
|
2018-03-20 15:46:53 +00:00
|
|
|
def read_reset_word_pos(self):
|
2020-04-24 10:28:14 +00:00
|
|
|
state = self._call(messages.DebugLinkGetState(wait_word_pos=True))
|
2020-04-24 10:16:17 +00:00
|
|
|
return state.reset_word_pos
|
2014-02-17 01:16:43 +00:00
|
|
|
|
2019-09-27 13:38:15 +00:00
|
|
|
def input(self, word=None, button=None, swipe=None, x=None, y=None, wait=False):
|
2019-01-31 14:23:39 +00:00
|
|
|
if not self.allow_interactions:
|
|
|
|
return
|
2018-09-13 16:47:19 +00:00
|
|
|
|
2019-09-27 13:38:15 +00:00
|
|
|
args = sum(a is not None for a in (word, button, swipe, x))
|
2019-07-26 15:37:26 +00:00
|
|
|
if args != 1:
|
|
|
|
raise ValueError("Invalid input - must use one of word, button, swipe")
|
|
|
|
|
2020-04-24 10:28:14 +00:00
|
|
|
decision = messages.DebugLinkDecision(
|
2019-09-27 13:38:15 +00:00
|
|
|
yes_no=button, swipe=swipe, input=word, x=x, y=y, wait=wait
|
|
|
|
)
|
|
|
|
ret = self._call(decision, nowait=not wait)
|
|
|
|
if ret is not None:
|
2019-10-18 11:31:57 +00:00
|
|
|
return layout_lines(ret.lines)
|
2019-09-27 13:38:15 +00:00
|
|
|
|
|
|
|
def click(self, click, wait=False):
|
|
|
|
x, y = click
|
|
|
|
return self.input(x=x, y=y, wait=wait)
|
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):
|
2020-04-24 10:28:14 +00:00
|
|
|
self.input(swipe=messages.DebugSwipeDirection.UP)
|
2018-03-20 15:46:53 +00:00
|
|
|
|
|
|
|
def swipe_down(self):
|
2020-04-24 10:28:14 +00:00
|
|
|
self.input(swipe=messages.DebugSwipeDirection.DOWN)
|
2019-10-04 15:27:41 +00:00
|
|
|
|
|
|
|
def swipe_right(self):
|
2020-04-24 10:28:14 +00:00
|
|
|
self.input(swipe=messages.DebugSwipeDirection.RIGHT)
|
2019-10-04 15:27:41 +00:00
|
|
|
|
|
|
|
def swipe_left(self):
|
2020-04-24 10:28:14 +00:00
|
|
|
self.input(swipe=messages.DebugSwipeDirection.LEFT)
|
2018-03-20 15:46:53 +00:00
|
|
|
|
2013-10-11 01:51:45 +00:00
|
|
|
def stop(self):
|
2020-04-24 10:28:14 +00:00
|
|
|
self._call(messages.DebugLinkStop(), nowait=True)
|
2016-05-26 18:46:40 +00:00
|
|
|
|
2019-12-09 16:01:04 +00:00
|
|
|
def reseed(self, value):
|
2020-04-24 10:28:14 +00:00
|
|
|
self._call(messages.DebugLinkReseedRandom(value=value))
|
2019-12-09 16:01:04 +00:00
|
|
|
|
|
|
|
def start_recording(self, directory):
|
2020-04-24 10:28:14 +00:00
|
|
|
self._call(messages.DebugLinkRecordScreen(target_directory=directory))
|
2019-12-09 16:01:04 +00:00
|
|
|
|
|
|
|
def stop_recording(self):
|
2020-04-24 10:28:14 +00:00
|
|
|
self._call(messages.DebugLinkRecordScreen(target_directory=None))
|
2019-12-09 16:01:04 +00:00
|
|
|
|
2020-04-24 10:28:14 +00:00
|
|
|
@expect(messages.DebugLinkMemory, field="memory")
|
2016-05-26 18:46:40 +00:00
|
|
|
def memory_read(self, address, length):
|
2020-04-24 10:28:14 +00:00
|
|
|
return self._call(messages.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(
|
2020-04-24 10:28:14 +00:00
|
|
|
messages.DebugLinkMemoryWrite(address=address, memory=memory, flash=flash),
|
2018-08-13 16:21:24 +00:00
|
|
|
nowait=True,
|
|
|
|
)
|
2016-05-26 18:46:40 +00:00
|
|
|
|
|
|
|
def flash_erase(self, sector):
|
2020-04-24 10:28:14 +00:00
|
|
|
self._call(messages.DebugLinkFlashErase(sector=sector), nowait=True)
|
2018-08-10 11:33:14 +00:00
|
|
|
|
2020-04-24 10:28:14 +00:00
|
|
|
@expect(messages.Success)
|
2020-02-17 16:35:46 +00:00
|
|
|
def erase_sd_card(self, format=True):
|
2020-04-24 10:28:14 +00:00
|
|
|
return self._call(messages.DebugLinkEraseSdCard(format=format))
|
2020-02-17 16:35:46 +00:00
|
|
|
|
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:
|
2020-04-24 10:28:14 +00:00
|
|
|
if isinstance(msg, messages.DebugLinkGetState):
|
|
|
|
return messages.DebugLinkState()
|
2019-01-31 14:23:39 +00:00
|
|
|
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
|
2020-02-12 14:38:18 +00:00
|
|
|
self.clear()
|
|
|
|
|
|
|
|
def clear(self):
|
|
|
|
self.pins = None
|
|
|
|
self.passphrase = ""
|
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:
|
2020-05-25 13:44:41 +00:00
|
|
|
if code == messages.ButtonRequestType.PinEntry:
|
2020-04-27 10:42:37 +00:00
|
|
|
self.debuglink.input(self.get_pin())
|
|
|
|
else:
|
|
|
|
self.debuglink.press_yes()
|
2018-10-02 15:18:13 +00:00
|
|
|
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):
|
2020-02-12 14:38:18 +00:00
|
|
|
if self.pins is None:
|
2020-04-27 14:37:07 +00:00
|
|
|
raise RuntimeError("PIN requested but no sequence was configured")
|
2020-02-12 14:38:18 +00:00
|
|
|
|
2020-04-27 10:42:37 +00:00
|
|
|
try:
|
|
|
|
return self.debuglink.encode_pin(next(self.pins))
|
|
|
|
except StopIteration:
|
2020-02-08 10:21:37 +00:00
|
|
|
raise AssertionError("PIN sequence ended prematurely")
|
2018-09-13 16:47:19 +00:00
|
|
|
|
2020-01-29 14:46:23 +00:00
|
|
|
def get_passphrase(self, available_on_device):
|
2018-09-13 16:47:19 +00:00
|
|
|
return self.passphrase
|
|
|
|
|
|
|
|
|
2020-09-15 11:06:41 +00:00
|
|
|
class MessageFilter:
|
|
|
|
def __init__(self, message_type, **fields):
|
|
|
|
self.message_type = message_type
|
|
|
|
self.fields = {}
|
|
|
|
self.update_fields(**fields)
|
|
|
|
|
|
|
|
def update_fields(self, **fields):
|
|
|
|
for name, value in fields.items():
|
|
|
|
try:
|
|
|
|
self.fields[name] = self.from_message_or_type(value)
|
|
|
|
except TypeError:
|
|
|
|
self.fields[name] = value
|
|
|
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_message_or_type(cls, message_or_type):
|
|
|
|
if isinstance(message_or_type, cls):
|
|
|
|
return message_or_type
|
|
|
|
if isinstance(message_or_type, protobuf.MessageType):
|
|
|
|
return cls.from_message(message_or_type)
|
|
|
|
if isinstance(message_or_type, type) and issubclass(
|
|
|
|
message_or_type, protobuf.MessageType
|
|
|
|
):
|
|
|
|
return cls(message_or_type)
|
|
|
|
raise TypeError("Invalid kind of expected response")
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_message(cls, message):
|
|
|
|
fields = {}
|
|
|
|
for field in message.keys():
|
|
|
|
value = getattr(message, field)
|
|
|
|
if value in (None, []):
|
|
|
|
continue
|
|
|
|
fields[field] = value
|
|
|
|
return cls(type(message), **fields)
|
|
|
|
|
|
|
|
def match(self, message):
|
|
|
|
if type(message) != self.message_type:
|
|
|
|
return False
|
|
|
|
|
|
|
|
for field, expected_value in self.fields.items():
|
|
|
|
actual_value = getattr(message, field, None)
|
|
|
|
if isinstance(expected_value, MessageFilter):
|
|
|
|
if not expected_value.match(actual_value):
|
|
|
|
return False
|
|
|
|
elif expected_value != actual_value:
|
|
|
|
return False
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
def format(self, maxwidth=80):
|
|
|
|
fields = []
|
|
|
|
for fname, ftype, _ in self.message_type.get_fields().values():
|
|
|
|
if fname not in self.fields:
|
|
|
|
continue
|
|
|
|
value = self.fields[fname]
|
|
|
|
if isinstance(ftype, protobuf.EnumType) and isinstance(value, int):
|
|
|
|
field_str = ftype.to_str(value)
|
|
|
|
elif isinstance(value, MessageFilter):
|
|
|
|
field_str = value.format(maxwidth - 4)
|
|
|
|
elif isinstance(value, protobuf.MessageType):
|
|
|
|
field_str = protobuf.format_message(value)
|
|
|
|
else:
|
|
|
|
field_str = repr(value)
|
|
|
|
field_str = textwrap.indent(field_str, " ").lstrip()
|
|
|
|
fields.append((fname, field_str))
|
|
|
|
|
|
|
|
pairs = ["{}={}".format(k, v) for k, v in fields]
|
|
|
|
oneline_str = ", ".join(pairs)
|
|
|
|
if len(oneline_str) < maxwidth:
|
|
|
|
return "{}({})".format(self.message_type.__name__, oneline_str)
|
|
|
|
else:
|
|
|
|
item = []
|
|
|
|
item.append("{}(".format(self.message_type.__name__))
|
|
|
|
for pair in pairs:
|
|
|
|
item.append(" {}".format(pair))
|
|
|
|
item.append(")")
|
|
|
|
return "\n".join(item)
|
|
|
|
|
|
|
|
|
|
|
|
class MessageFilterGenerator:
|
|
|
|
def __getattr__(self, key):
|
|
|
|
message_type = getattr(messages, key)
|
|
|
|
return MessageFilter(message_type).update_fields
|
|
|
|
|
|
|
|
|
|
|
|
message_filters = MessageFilterGenerator()
|
|
|
|
|
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
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)
|
2019-07-24 15:55:06 +00:00
|
|
|
# try to open debuglink, see if it works
|
|
|
|
self.debug.open()
|
|
|
|
self.debug.close()
|
2019-01-31 14:23:39 +00:00
|
|
|
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
|
|
|
# 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
|
|
|
|
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()
|
2020-03-23 14:53:51 +00:00
|
|
|
if self.session_counter == 1:
|
|
|
|
self.debug.open()
|
2018-11-08 17:08:02 +00:00
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
def close(self):
|
2020-03-23 14:53:51 +00:00
|
|
|
if self.session_counter == 1:
|
|
|
|
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):
|
2020-02-12 14:38:18 +00:00
|
|
|
"""Configure a filter function for a specified message type.
|
|
|
|
|
|
|
|
The `callback` must be a function that accepts a protobuf message, and returns
|
|
|
|
a (possibly modified) protobuf message of the same type. Whenever a message
|
|
|
|
is sent or received that matches `message_type`, `callback` is invoked on the
|
|
|
|
message and its result is substituted for the original.
|
|
|
|
|
|
|
|
Useful for test scenarios with an active malicious actor on the wire.
|
|
|
|
"""
|
2018-11-02 15:20:10 +00:00
|
|
|
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):
|
2020-02-12 14:38:18 +00:00
|
|
|
"""Configure a sequence of input events for the current with-block.
|
|
|
|
|
|
|
|
The `input_flow` must be a generator function. A `yield` statement in the
|
|
|
|
input flow function waits for a ButtonRequest from the device, and returns
|
|
|
|
its code.
|
|
|
|
|
|
|
|
Example usage:
|
|
|
|
|
|
|
|
>>> def input_flow():
|
|
|
|
>>> # wait for first button prompt
|
|
|
|
>>> code = yield
|
|
|
|
>>> assert code == ButtonRequestType.Other
|
|
|
|
>>> # press No
|
|
|
|
>>> client.debug.press_no()
|
|
|
|
>>>
|
|
|
|
>>> # wait for second button prompt
|
|
|
|
>>> yield
|
|
|
|
>>> # press Yes
|
|
|
|
>>> client.debug.press_yes()
|
|
|
|
>>>
|
|
|
|
>>> with client:
|
|
|
|
>>> client.set_input_flow(input_flow)
|
|
|
|
>>> some_call(client)
|
|
|
|
"""
|
2019-09-18 14:13:11 +00:00
|
|
|
if not self.in_with_statement:
|
|
|
|
raise RuntimeError("Must be called inside 'with' statement")
|
|
|
|
|
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
|
2020-05-25 13:44:41 +00:00
|
|
|
input_flow.send(None) # start the generator
|
2018-10-02 15:18:13 +00:00
|
|
|
|
2020-07-28 12:40:54 +00:00
|
|
|
def watch_layout(self, watch: bool = True) -> None:
|
2020-05-22 13:38:40 +00:00
|
|
|
"""Enable or disable watching layout changes.
|
|
|
|
|
|
|
|
Since trezor-core v2.3.2, it is necessary to call `watch_layout()` before
|
|
|
|
using `debug.wait_layout()`, otherwise layout changes are not reported.
|
|
|
|
"""
|
|
|
|
if self.version >= (2, 3, 2):
|
|
|
|
# version check is necessary because otherwise we cannot reliably detect
|
|
|
|
# whether and where to wait for reply:
|
|
|
|
# - T1 reports unknown debuglink messages on the wirelink
|
|
|
|
# - TT < 2.3.0 does not reply to unknown debuglink messages due to a bug
|
|
|
|
self.debug.watch_layout(watch)
|
|
|
|
|
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
|
|
|
|
|
2019-09-18 14:13:11 +00:00
|
|
|
# Clear input flow.
|
2020-02-11 10:29:47 +00:00
|
|
|
try:
|
|
|
|
if _type is not None:
|
|
|
|
# Another exception raised
|
|
|
|
return False
|
|
|
|
|
|
|
|
if self.expected_responses is None:
|
|
|
|
# no need to check anything else
|
|
|
|
return False
|
|
|
|
|
|
|
|
# Evaluate missed responses in 'with' statement
|
|
|
|
if self.current_response < len(self.expected_responses):
|
|
|
|
self._raise_unexpected_response(None)
|
|
|
|
|
|
|
|
finally:
|
|
|
|
# Cleanup
|
|
|
|
self.expected_responses = None
|
|
|
|
self.current_response = None
|
2020-02-12 14:38:18 +00:00
|
|
|
self.ui.clear()
|
2020-05-22 13:38:40 +00:00
|
|
|
self.watch_layout(False)
|
2019-09-18 14:13:11 +00:00
|
|
|
|
2018-09-13 16:47:19 +00:00
|
|
|
return False
|
|
|
|
|
|
|
|
def set_expected_responses(self, expected):
|
2020-02-12 14:38:18 +00:00
|
|
|
"""Set a sequence of expected responses to client calls.
|
|
|
|
|
|
|
|
Within a given with-block, the list of received responses from device must
|
|
|
|
match the list of expected responses, otherwise an AssertionError is raised.
|
|
|
|
|
|
|
|
If an expected response is given a field value other than None, that field value
|
|
|
|
must exactly match the received field value. If a given field is None
|
|
|
|
(or unspecified) in the expected response, the received field value is not
|
|
|
|
checked.
|
2020-04-24 10:58:17 +00:00
|
|
|
|
|
|
|
Each expected response can also be a tuple (bool, message). In that case, the
|
|
|
|
expected response is only evaluated if the first field is True.
|
|
|
|
This is useful for differentiating sequences between Trezor models:
|
|
|
|
|
|
|
|
>>> trezor_one = client.features.model == "1"
|
|
|
|
>>> client.set_expected_responses([
|
|
|
|
>>> messages.ButtonRequest(code=ConfirmOutput),
|
|
|
|
>>> (trezor_one, messages.ButtonRequest(code=ConfirmOutput)),
|
|
|
|
>>> messages.Success(),
|
|
|
|
>>> ])
|
2020-02-12 14:38:18 +00:00
|
|
|
"""
|
2018-09-13 16:47:19 +00:00
|
|
|
if not self.in_with_statement:
|
|
|
|
raise RuntimeError("Must be called inside 'with' statement")
|
2020-04-24 10:58:17 +00:00
|
|
|
|
|
|
|
# make sure all items are (bool, message) tuples
|
2020-09-15 11:06:41 +00:00
|
|
|
expected_with_validity = (
|
2020-04-24 10:58:17 +00:00
|
|
|
e if isinstance(e, tuple) else (True, e) for e in expected
|
2020-09-15 11:06:41 +00:00
|
|
|
)
|
2020-04-24 10:58:17 +00:00
|
|
|
|
|
|
|
# only apply those items that are (True, message)
|
|
|
|
self.expected_responses = [
|
2020-09-15 11:06:41 +00:00
|
|
|
MessageFilter.from_message_or_type(expected)
|
|
|
|
for valid, expected in expected_with_validity
|
|
|
|
if valid
|
2020-04-24 10:58:17 +00:00
|
|
|
]
|
|
|
|
|
2018-10-02 15:18:13 +00:00
|
|
|
self.current_response = 0
|
2018-09-13 16:47:19 +00:00
|
|
|
|
2020-02-12 14:38:18 +00:00
|
|
|
def use_pin_sequence(self, pins):
|
|
|
|
"""Respond to PIN prompts from device with the provided PINs.
|
|
|
|
The sequence must be at least as long as the expected number of PIN prompts.
|
|
|
|
"""
|
2020-04-27 10:42:37 +00:00
|
|
|
self.ui.pins = iter(pins)
|
2020-02-12 14:38:18 +00:00
|
|
|
|
|
|
|
def use_passphrase(self, passphrase):
|
|
|
|
"""Respond to passphrase prompts from device with the provided passphrase."""
|
2018-09-13 16:47:19 +00:00
|
|
|
self.ui.passphrase = Mnemonic.normalize_string(passphrase)
|
|
|
|
|
2020-02-12 14:38:18 +00:00
|
|
|
def use_mnemonic(self, mnemonic):
|
|
|
|
"""Use the provided mnemonic to respond to device.
|
|
|
|
Only applies to T1, where device prompts the host for mnemonic words."""
|
2018-09-13 16:47:19 +00:00
|
|
|
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
|
|
|
|
|
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 ">>> "
|
2020-09-15 11:06:41 +00:00
|
|
|
output.append(textwrap.indent(exp.format(), prefix))
|
2018-12-13 12:35:35 +00:00
|
|
|
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:")
|
2020-09-15 11:06:41 +00:00
|
|
|
output.append(textwrap.indent(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]
|
|
|
|
|
2020-09-15 11:06:41 +00:00
|
|
|
if not expected.match(msg):
|
2018-10-02 15:18:13 +00:00
|
|
|
self._raise_unexpected_response(msg)
|
|
|
|
|
|
|
|
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")
|
|
|
|
|
|
|
|
|
2020-04-24 10:28:14 +00:00
|
|
|
@expect(messages.Success, field="message")
|
2019-11-13 11:47:51 +00:00
|
|
|
def load_device(
|
2018-08-13 16:21:24 +00:00
|
|
|
client,
|
|
|
|
mnemonic,
|
|
|
|
pin,
|
|
|
|
passphrase_protection,
|
|
|
|
label,
|
2019-12-07 11:11:51 +00:00
|
|
|
language="en-US",
|
2018-08-13 16:21:24 +00:00
|
|
|
skip_checksum=False,
|
2019-11-13 11:47:51 +00:00
|
|
|
needs_backup=False,
|
|
|
|
no_backup=False,
|
2018-08-13 16:21:24 +00:00
|
|
|
):
|
2019-07-24 13:36:33 +00:00
|
|
|
if not isinstance(mnemonic, (list, tuple)):
|
|
|
|
mnemonic = [mnemonic]
|
2018-08-10 11:33:14 +00:00
|
|
|
|
2019-07-24 13:36:33 +00:00
|
|
|
mnemonics = [Mnemonic.normalize_string(m) for m in mnemonic]
|
2018-08-10 11:33:14 +00:00
|
|
|
|
|
|
|
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(
|
2020-04-24 10:28:14 +00:00
|
|
|
messages.LoadDevice(
|
2019-07-24 13:36:33 +00:00
|
|
|
mnemonics=mnemonics,
|
2018-08-13 16:21:24 +00:00
|
|
|
pin=pin,
|
|
|
|
passphrase_protection=passphrase_protection,
|
|
|
|
language=language,
|
|
|
|
label=label,
|
|
|
|
skip_checksum=skip_checksum,
|
2019-11-13 11:47:51 +00:00
|
|
|
needs_backup=needs_backup,
|
|
|
|
no_backup=no_backup,
|
2018-08-13 16:21:24 +00:00
|
|
|
)
|
|
|
|
)
|
2018-08-10 11:33:14 +00:00
|
|
|
client.init_device()
|
|
|
|
return resp
|
|
|
|
|
|
|
|
|
2019-11-13 11:47:51 +00:00
|
|
|
# keep the old name for compatibility
|
|
|
|
load_device_by_mnemonic = load_device
|
|
|
|
|
|
|
|
|
2020-04-24 10:28:14 +00:00
|
|
|
@expect(messages.Success, field="message")
|
2018-08-10 11:33:14 +00:00
|
|
|
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(
|
2020-04-24 10:28:14 +00:00
|
|
|
messages.SelfTest(
|
2018-08-13 16:21:24 +00:00
|
|
|
payload=b"\x00\xFF\x55\xAA\x66\x99\x33\xCCABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\x00\xFF\x55\xAA\x66\x99\x33\xCC"
|
|
|
|
)
|
|
|
|
)
|
2020-02-05 14:43:19 +00:00
|
|
|
|
|
|
|
|
2020-04-24 10:28:14 +00:00
|
|
|
@expect(messages.Success, field="message")
|
2020-02-05 14:43:19 +00:00
|
|
|
def show_text(client, header_text, body_text, icon=None, icon_color=None):
|
|
|
|
body_text = [
|
2020-04-24 10:28:14 +00:00
|
|
|
messages.DebugLinkShowTextItem(style=style, content=content)
|
2020-02-05 14:43:19 +00:00
|
|
|
for style, content in body_text
|
|
|
|
]
|
2020-04-24 10:28:14 +00:00
|
|
|
msg = messages.DebugLinkShowText(
|
2020-02-05 14:43:19 +00:00
|
|
|
header_text=header_text,
|
|
|
|
body_text=body_text,
|
|
|
|
header_icon=icon,
|
|
|
|
icon_color=icon_color,
|
|
|
|
)
|
|
|
|
return client.call(msg)
|