You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
trezor-firmware/python/src/trezorlib/transport/__init__.py

173 lines
5.0 KiB

# This file is part of the Trezor project.
#
# Copyright (C) 2012-2022 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# 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 License along with this library.
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
import logging
feat(python): add full type information WIP - typing the trezorctl apps typing functions trezorlib/cli addressing most of mypy issue for trezorlib apps and _internal folder fixing broken device tests by changing asserts in debuglink.py addressing most of mypy issues in trezorlib/cli folder adding types to some untyped functions, mypy section in setup.cfg typing what can be typed, some mypy fixes, resolving circular import issues importing type objects in "if TYPE_CHECKING:" branch fixing CI by removing assert in emulator, better ignore comments CI assert fix, style fixes, new config options fixup! CI assert fix, style fixes, new config options type fixes after rebasing on master fixing python3.6 and 3.7 unittests by importing Literal from typing_extensions couple mypy and style fixes fixes and improvements from code review silencing all but one mypy issues trial of typing the tools.expect function fixup! trial of typing the tools.expect function @expect and @session decorators correctly type-checked Optional args in CLI where relevant, not using general list/tuple/dict where possible python/Makefile commands, adding them into CI, ignoring last mypy issue documenting overload for expect decorator, two mypy fixes coming from that black style fix improved typing of decorators, pyright config file addressing or ignoring pyright errors, replacing mypy in CI by pyright fixing incomplete assert causing device tests to fail pyright issue that showed in CI but not locally, printing pyright version in CI fixup! pyright issue that showed in CI but not locally, printing pyright version in CI unifying type:ignore statements for pyright usage resolving PIL.Image issues, pyrightconfig not excluding anything replacing couple asserts with TypeGuard on safe_issubclass better error handling of usb1 import for webusb better error handling of hid import small typing details found out by strict pyright mode improvements from code review chore(python): changing List to Sequence for protobuf messages small code changes to reflect the protobuf change to Sequence importing TypedDict from typing_extensions to support 3.6 and 3.7 simplify _format_access_list function fixup! simplify _format_access_list function typing tools folder typing helper-scripts folder some click typing enforcing all functions to have typed arguments reverting the changed argument name in tools replacing TransportType with Transport making PinMatrixRequest.type protobuf attribute required reverting the protobuf change, making argument into get_pin Optional small fixes in asserts solving the session decorator type issues fixup! solving the session decorator type issues improvements from code review fixing new pyright errors introduced after version increase changing -> Iterable to -> Sequence in enumerate_devices, change in wait_for_devices style change in debuglink.py chore(python): adding type annotation to Sequences in messages.py better "self and cls" types on Transport fixup! better "self and cls" types on Transport fixing some easy things from strict pyright run
3 years ago
from typing import (
TYPE_CHECKING,
Iterable,
List,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
)
from ..exceptions import TrezorException
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.
6 years ago
feat(python): add full type information WIP - typing the trezorctl apps typing functions trezorlib/cli addressing most of mypy issue for trezorlib apps and _internal folder fixing broken device tests by changing asserts in debuglink.py addressing most of mypy issues in trezorlib/cli folder adding types to some untyped functions, mypy section in setup.cfg typing what can be typed, some mypy fixes, resolving circular import issues importing type objects in "if TYPE_CHECKING:" branch fixing CI by removing assert in emulator, better ignore comments CI assert fix, style fixes, new config options fixup! CI assert fix, style fixes, new config options type fixes after rebasing on master fixing python3.6 and 3.7 unittests by importing Literal from typing_extensions couple mypy and style fixes fixes and improvements from code review silencing all but one mypy issues trial of typing the tools.expect function fixup! trial of typing the tools.expect function @expect and @session decorators correctly type-checked Optional args in CLI where relevant, not using general list/tuple/dict where possible python/Makefile commands, adding them into CI, ignoring last mypy issue documenting overload for expect decorator, two mypy fixes coming from that black style fix improved typing of decorators, pyright config file addressing or ignoring pyright errors, replacing mypy in CI by pyright fixing incomplete assert causing device tests to fail pyright issue that showed in CI but not locally, printing pyright version in CI fixup! pyright issue that showed in CI but not locally, printing pyright version in CI unifying type:ignore statements for pyright usage resolving PIL.Image issues, pyrightconfig not excluding anything replacing couple asserts with TypeGuard on safe_issubclass better error handling of usb1 import for webusb better error handling of hid import small typing details found out by strict pyright mode improvements from code review chore(python): changing List to Sequence for protobuf messages small code changes to reflect the protobuf change to Sequence importing TypedDict from typing_extensions to support 3.6 and 3.7 simplify _format_access_list function fixup! simplify _format_access_list function typing tools folder typing helper-scripts folder some click typing enforcing all functions to have typed arguments reverting the changed argument name in tools replacing TransportType with Transport making PinMatrixRequest.type protobuf attribute required reverting the protobuf change, making argument into get_pin Optional small fixes in asserts solving the session decorator type issues fixup! solving the session decorator type issues improvements from code review fixing new pyright errors introduced after version increase changing -> Iterable to -> Sequence in enumerate_devices, change in wait_for_devices style change in debuglink.py chore(python): adding type annotation to Sequences in messages.py better "self and cls" types on Transport fixup! better "self and cls" types on Transport fixing some easy things from strict pyright run
3 years ago
if TYPE_CHECKING:
from ..models import TrezorModel
feat(python): add full type information WIP - typing the trezorctl apps typing functions trezorlib/cli addressing most of mypy issue for trezorlib apps and _internal folder fixing broken device tests by changing asserts in debuglink.py addressing most of mypy issues in trezorlib/cli folder adding types to some untyped functions, mypy section in setup.cfg typing what can be typed, some mypy fixes, resolving circular import issues importing type objects in "if TYPE_CHECKING:" branch fixing CI by removing assert in emulator, better ignore comments CI assert fix, style fixes, new config options fixup! CI assert fix, style fixes, new config options type fixes after rebasing on master fixing python3.6 and 3.7 unittests by importing Literal from typing_extensions couple mypy and style fixes fixes and improvements from code review silencing all but one mypy issues trial of typing the tools.expect function fixup! trial of typing the tools.expect function @expect and @session decorators correctly type-checked Optional args in CLI where relevant, not using general list/tuple/dict where possible python/Makefile commands, adding them into CI, ignoring last mypy issue documenting overload for expect decorator, two mypy fixes coming from that black style fix improved typing of decorators, pyright config file addressing or ignoring pyright errors, replacing mypy in CI by pyright fixing incomplete assert causing device tests to fail pyright issue that showed in CI but not locally, printing pyright version in CI fixup! pyright issue that showed in CI but not locally, printing pyright version in CI unifying type:ignore statements for pyright usage resolving PIL.Image issues, pyrightconfig not excluding anything replacing couple asserts with TypeGuard on safe_issubclass better error handling of usb1 import for webusb better error handling of hid import small typing details found out by strict pyright mode improvements from code review chore(python): changing List to Sequence for protobuf messages small code changes to reflect the protobuf change to Sequence importing TypedDict from typing_extensions to support 3.6 and 3.7 simplify _format_access_list function fixup! simplify _format_access_list function typing tools folder typing helper-scripts folder some click typing enforcing all functions to have typed arguments reverting the changed argument name in tools replacing TransportType with Transport making PinMatrixRequest.type protobuf attribute required reverting the protobuf change, making argument into get_pin Optional small fixes in asserts solving the session decorator type issues fixup! solving the session decorator type issues improvements from code review fixing new pyright errors introduced after version increase changing -> Iterable to -> Sequence in enumerate_devices, change in wait_for_devices style change in debuglink.py chore(python): adding type annotation to Sequences in messages.py better "self and cls" types on Transport fixup! better "self and cls" types on Transport fixing some easy things from strict pyright run
3 years ago
T = TypeVar("T", bound="Transport")
LOG = logging.getLogger(__name__)
UDEV_RULES_STR = """
Do you have udev rules installed?
https://github.com/trezor/trezor-common/blob/master/udev/51-trezor.rules
""".strip()
MessagePayload = Tuple[int, bytes]
class TransportException(TrezorException):
pass
class DeviceIsBusy(TransportException):
pass
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.
6 years ago
class Transport:
"""Raw connection to a Trezor device.
Transport subclass represents a kind of communication link: Trezor Bridge, WebUSB
or USB-HID connection, or UDP socket of listening emulator(s).
It can also enumerate devices available over this communication link, and return
them as instances.
Transport instance is a thing that:
- can be identified and requested by a string URI-like path
- can open and close sessions, which enclose related operations
- can read and write protobuf messages
You need to implement a new Transport subclass if you invent a new way to connect
a Trezor device to a computer.
"""
feat(python): add full type information WIP - typing the trezorctl apps typing functions trezorlib/cli addressing most of mypy issue for trezorlib apps and _internal folder fixing broken device tests by changing asserts in debuglink.py addressing most of mypy issues in trezorlib/cli folder adding types to some untyped functions, mypy section in setup.cfg typing what can be typed, some mypy fixes, resolving circular import issues importing type objects in "if TYPE_CHECKING:" branch fixing CI by removing assert in emulator, better ignore comments CI assert fix, style fixes, new config options fixup! CI assert fix, style fixes, new config options type fixes after rebasing on master fixing python3.6 and 3.7 unittests by importing Literal from typing_extensions couple mypy and style fixes fixes and improvements from code review silencing all but one mypy issues trial of typing the tools.expect function fixup! trial of typing the tools.expect function @expect and @session decorators correctly type-checked Optional args in CLI where relevant, not using general list/tuple/dict where possible python/Makefile commands, adding them into CI, ignoring last mypy issue documenting overload for expect decorator, two mypy fixes coming from that black style fix improved typing of decorators, pyright config file addressing or ignoring pyright errors, replacing mypy in CI by pyright fixing incomplete assert causing device tests to fail pyright issue that showed in CI but not locally, printing pyright version in CI fixup! pyright issue that showed in CI but not locally, printing pyright version in CI unifying type:ignore statements for pyright usage resolving PIL.Image issues, pyrightconfig not excluding anything replacing couple asserts with TypeGuard on safe_issubclass better error handling of usb1 import for webusb better error handling of hid import small typing details found out by strict pyright mode improvements from code review chore(python): changing List to Sequence for protobuf messages small code changes to reflect the protobuf change to Sequence importing TypedDict from typing_extensions to support 3.6 and 3.7 simplify _format_access_list function fixup! simplify _format_access_list function typing tools folder typing helper-scripts folder some click typing enforcing all functions to have typed arguments reverting the changed argument name in tools replacing TransportType with Transport making PinMatrixRequest.type protobuf attribute required reverting the protobuf change, making argument into get_pin Optional small fixes in asserts solving the session decorator type issues fixup! solving the session decorator type issues improvements from code review fixing new pyright errors introduced after version increase changing -> Iterable to -> Sequence in enumerate_devices, change in wait_for_devices style change in debuglink.py chore(python): adding type annotation to Sequences in messages.py better "self and cls" types on Transport fixup! better "self and cls" types on Transport fixing some easy things from strict pyright run
3 years ago
PATH_PREFIX: str
ENABLED = False
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.
6 years ago
def __str__(self) -> str:
return self.get_path()
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.
6 years ago
def get_path(self) -> str:
raise NotImplementedError
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.
6 years ago
def begin_session(self) -> None:
raise NotImplementedError
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.
6 years ago
def end_session(self) -> None:
raise NotImplementedError
8 years ago
def read(self) -> MessagePayload:
raise NotImplementedError
8 years ago
def write(self, message_type: int, message_data: bytes) -> None:
7 years ago
raise NotImplementedError
feat(python): add full type information WIP - typing the trezorctl apps typing functions trezorlib/cli addressing most of mypy issue for trezorlib apps and _internal folder fixing broken device tests by changing asserts in debuglink.py addressing most of mypy issues in trezorlib/cli folder adding types to some untyped functions, mypy section in setup.cfg typing what can be typed, some mypy fixes, resolving circular import issues importing type objects in "if TYPE_CHECKING:" branch fixing CI by removing assert in emulator, better ignore comments CI assert fix, style fixes, new config options fixup! CI assert fix, style fixes, new config options type fixes after rebasing on master fixing python3.6 and 3.7 unittests by importing Literal from typing_extensions couple mypy and style fixes fixes and improvements from code review silencing all but one mypy issues trial of typing the tools.expect function fixup! trial of typing the tools.expect function @expect and @session decorators correctly type-checked Optional args in CLI where relevant, not using general list/tuple/dict where possible python/Makefile commands, adding them into CI, ignoring last mypy issue documenting overload for expect decorator, two mypy fixes coming from that black style fix improved typing of decorators, pyright config file addressing or ignoring pyright errors, replacing mypy in CI by pyright fixing incomplete assert causing device tests to fail pyright issue that showed in CI but not locally, printing pyright version in CI fixup! pyright issue that showed in CI but not locally, printing pyright version in CI unifying type:ignore statements for pyright usage resolving PIL.Image issues, pyrightconfig not excluding anything replacing couple asserts with TypeGuard on safe_issubclass better error handling of usb1 import for webusb better error handling of hid import small typing details found out by strict pyright mode improvements from code review chore(python): changing List to Sequence for protobuf messages small code changes to reflect the protobuf change to Sequence importing TypedDict from typing_extensions to support 3.6 and 3.7 simplify _format_access_list function fixup! simplify _format_access_list function typing tools folder typing helper-scripts folder some click typing enforcing all functions to have typed arguments reverting the changed argument name in tools replacing TransportType with Transport making PinMatrixRequest.type protobuf attribute required reverting the protobuf change, making argument into get_pin Optional small fixes in asserts solving the session decorator type issues fixup! solving the session decorator type issues improvements from code review fixing new pyright errors introduced after version increase changing -> Iterable to -> Sequence in enumerate_devices, change in wait_for_devices style change in debuglink.py chore(python): adding type annotation to Sequences in messages.py better "self and cls" types on Transport fixup! better "self and cls" types on Transport fixing some easy things from strict pyright run
3 years ago
def find_debug(self: "T") -> "T":
raise NotImplementedError
@classmethod
def enumerate(
cls: Type["T"], models: Optional[Iterable["TrezorModel"]] = None
) -> Iterable["T"]:
raise NotImplementedError
@classmethod
feat(python): add full type information WIP - typing the trezorctl apps typing functions trezorlib/cli addressing most of mypy issue for trezorlib apps and _internal folder fixing broken device tests by changing asserts in debuglink.py addressing most of mypy issues in trezorlib/cli folder adding types to some untyped functions, mypy section in setup.cfg typing what can be typed, some mypy fixes, resolving circular import issues importing type objects in "if TYPE_CHECKING:" branch fixing CI by removing assert in emulator, better ignore comments CI assert fix, style fixes, new config options fixup! CI assert fix, style fixes, new config options type fixes after rebasing on master fixing python3.6 and 3.7 unittests by importing Literal from typing_extensions couple mypy and style fixes fixes and improvements from code review silencing all but one mypy issues trial of typing the tools.expect function fixup! trial of typing the tools.expect function @expect and @session decorators correctly type-checked Optional args in CLI where relevant, not using general list/tuple/dict where possible python/Makefile commands, adding them into CI, ignoring last mypy issue documenting overload for expect decorator, two mypy fixes coming from that black style fix improved typing of decorators, pyright config file addressing or ignoring pyright errors, replacing mypy in CI by pyright fixing incomplete assert causing device tests to fail pyright issue that showed in CI but not locally, printing pyright version in CI fixup! pyright issue that showed in CI but not locally, printing pyright version in CI unifying type:ignore statements for pyright usage resolving PIL.Image issues, pyrightconfig not excluding anything replacing couple asserts with TypeGuard on safe_issubclass better error handling of usb1 import for webusb better error handling of hid import small typing details found out by strict pyright mode improvements from code review chore(python): changing List to Sequence for protobuf messages small code changes to reflect the protobuf change to Sequence importing TypedDict from typing_extensions to support 3.6 and 3.7 simplify _format_access_list function fixup! simplify _format_access_list function typing tools folder typing helper-scripts folder some click typing enforcing all functions to have typed arguments reverting the changed argument name in tools replacing TransportType with Transport making PinMatrixRequest.type protobuf attribute required reverting the protobuf change, making argument into get_pin Optional small fixes in asserts solving the session decorator type issues fixup! solving the session decorator type issues improvements from code review fixing new pyright errors introduced after version increase changing -> Iterable to -> Sequence in enumerate_devices, change in wait_for_devices style change in debuglink.py chore(python): adding type annotation to Sequences in messages.py better "self and cls" types on Transport fixup! better "self and cls" types on Transport fixing some easy things from strict pyright run
3 years ago
def find_by_path(cls: Type["T"], path: str, prefix_search: bool = False) -> "T":
for device in cls.enumerate():
if (
path is None
or device.get_path() == path
or (prefix_search and device.get_path().startswith(path))
):
return device
raise TransportException(f"{cls.PATH_PREFIX} device not found: {path}")
feat(python): add full type information WIP - typing the trezorctl apps typing functions trezorlib/cli addressing most of mypy issue for trezorlib apps and _internal folder fixing broken device tests by changing asserts in debuglink.py addressing most of mypy issues in trezorlib/cli folder adding types to some untyped functions, mypy section in setup.cfg typing what can be typed, some mypy fixes, resolving circular import issues importing type objects in "if TYPE_CHECKING:" branch fixing CI by removing assert in emulator, better ignore comments CI assert fix, style fixes, new config options fixup! CI assert fix, style fixes, new config options type fixes after rebasing on master fixing python3.6 and 3.7 unittests by importing Literal from typing_extensions couple mypy and style fixes fixes and improvements from code review silencing all but one mypy issues trial of typing the tools.expect function fixup! trial of typing the tools.expect function @expect and @session decorators correctly type-checked Optional args in CLI where relevant, not using general list/tuple/dict where possible python/Makefile commands, adding them into CI, ignoring last mypy issue documenting overload for expect decorator, two mypy fixes coming from that black style fix improved typing of decorators, pyright config file addressing or ignoring pyright errors, replacing mypy in CI by pyright fixing incomplete assert causing device tests to fail pyright issue that showed in CI but not locally, printing pyright version in CI fixup! pyright issue that showed in CI but not locally, printing pyright version in CI unifying type:ignore statements for pyright usage resolving PIL.Image issues, pyrightconfig not excluding anything replacing couple asserts with TypeGuard on safe_issubclass better error handling of usb1 import for webusb better error handling of hid import small typing details found out by strict pyright mode improvements from code review chore(python): changing List to Sequence for protobuf messages small code changes to reflect the protobuf change to Sequence importing TypedDict from typing_extensions to support 3.6 and 3.7 simplify _format_access_list function fixup! simplify _format_access_list function typing tools folder typing helper-scripts folder some click typing enforcing all functions to have typed arguments reverting the changed argument name in tools replacing TransportType with Transport making PinMatrixRequest.type protobuf attribute required reverting the protobuf change, making argument into get_pin Optional small fixes in asserts solving the session decorator type issues fixup! solving the session decorator type issues improvements from code review fixing new pyright errors introduced after version increase changing -> Iterable to -> Sequence in enumerate_devices, change in wait_for_devices style change in debuglink.py chore(python): adding type annotation to Sequences in messages.py better "self and cls" types on Transport fixup! better "self and cls" types on Transport fixing some easy things from strict pyright run
3 years ago
def all_transports() -> Iterable[Type["Transport"]]:
from .bridge import BridgeTransport
from .hid import HidTransport
from .udp import UdpTransport
from .webusb import WebUsbTransport
feat(python): add full type information WIP - typing the trezorctl apps typing functions trezorlib/cli addressing most of mypy issue for trezorlib apps and _internal folder fixing broken device tests by changing asserts in debuglink.py addressing most of mypy issues in trezorlib/cli folder adding types to some untyped functions, mypy section in setup.cfg typing what can be typed, some mypy fixes, resolving circular import issues importing type objects in "if TYPE_CHECKING:" branch fixing CI by removing assert in emulator, better ignore comments CI assert fix, style fixes, new config options fixup! CI assert fix, style fixes, new config options type fixes after rebasing on master fixing python3.6 and 3.7 unittests by importing Literal from typing_extensions couple mypy and style fixes fixes and improvements from code review silencing all but one mypy issues trial of typing the tools.expect function fixup! trial of typing the tools.expect function @expect and @session decorators correctly type-checked Optional args in CLI where relevant, not using general list/tuple/dict where possible python/Makefile commands, adding them into CI, ignoring last mypy issue documenting overload for expect decorator, two mypy fixes coming from that black style fix improved typing of decorators, pyright config file addressing or ignoring pyright errors, replacing mypy in CI by pyright fixing incomplete assert causing device tests to fail pyright issue that showed in CI but not locally, printing pyright version in CI fixup! pyright issue that showed in CI but not locally, printing pyright version in CI unifying type:ignore statements for pyright usage resolving PIL.Image issues, pyrightconfig not excluding anything replacing couple asserts with TypeGuard on safe_issubclass better error handling of usb1 import for webusb better error handling of hid import small typing details found out by strict pyright mode improvements from code review chore(python): changing List to Sequence for protobuf messages small code changes to reflect the protobuf change to Sequence importing TypedDict from typing_extensions to support 3.6 and 3.7 simplify _format_access_list function fixup! simplify _format_access_list function typing tools folder typing helper-scripts folder some click typing enforcing all functions to have typed arguments reverting the changed argument name in tools replacing TransportType with Transport making PinMatrixRequest.type protobuf attribute required reverting the protobuf change, making argument into get_pin Optional small fixes in asserts solving the session decorator type issues fixup! solving the session decorator type issues improvements from code review fixing new pyright errors introduced after version increase changing -> Iterable to -> Sequence in enumerate_devices, change in wait_for_devices style change in debuglink.py chore(python): adding type annotation to Sequences in messages.py better "self and cls" types on Transport fixup! better "self and cls" types on Transport fixing some easy things from strict pyright run
3 years ago
transports: Tuple[Type["Transport"], ...] = (
BridgeTransport,
HidTransport,
UdpTransport,
WebUsbTransport,
)
feat(python): add full type information WIP - typing the trezorctl apps typing functions trezorlib/cli addressing most of mypy issue for trezorlib apps and _internal folder fixing broken device tests by changing asserts in debuglink.py addressing most of mypy issues in trezorlib/cli folder adding types to some untyped functions, mypy section in setup.cfg typing what can be typed, some mypy fixes, resolving circular import issues importing type objects in "if TYPE_CHECKING:" branch fixing CI by removing assert in emulator, better ignore comments CI assert fix, style fixes, new config options fixup! CI assert fix, style fixes, new config options type fixes after rebasing on master fixing python3.6 and 3.7 unittests by importing Literal from typing_extensions couple mypy and style fixes fixes and improvements from code review silencing all but one mypy issues trial of typing the tools.expect function fixup! trial of typing the tools.expect function @expect and @session decorators correctly type-checked Optional args in CLI where relevant, not using general list/tuple/dict where possible python/Makefile commands, adding them into CI, ignoring last mypy issue documenting overload for expect decorator, two mypy fixes coming from that black style fix improved typing of decorators, pyright config file addressing or ignoring pyright errors, replacing mypy in CI by pyright fixing incomplete assert causing device tests to fail pyright issue that showed in CI but not locally, printing pyright version in CI fixup! pyright issue that showed in CI but not locally, printing pyright version in CI unifying type:ignore statements for pyright usage resolving PIL.Image issues, pyrightconfig not excluding anything replacing couple asserts with TypeGuard on safe_issubclass better error handling of usb1 import for webusb better error handling of hid import small typing details found out by strict pyright mode improvements from code review chore(python): changing List to Sequence for protobuf messages small code changes to reflect the protobuf change to Sequence importing TypedDict from typing_extensions to support 3.6 and 3.7 simplify _format_access_list function fixup! simplify _format_access_list function typing tools folder typing helper-scripts folder some click typing enforcing all functions to have typed arguments reverting the changed argument name in tools replacing TransportType with Transport making PinMatrixRequest.type protobuf attribute required reverting the protobuf change, making argument into get_pin Optional small fixes in asserts solving the session decorator type issues fixup! solving the session decorator type issues improvements from code review fixing new pyright errors introduced after version increase changing -> Iterable to -> Sequence in enumerate_devices, change in wait_for_devices style change in debuglink.py chore(python): adding type annotation to Sequences in messages.py better "self and cls" types on Transport fixup! better "self and cls" types on Transport fixing some easy things from strict pyright run
3 years ago
return set(t for t in transports if t.ENABLED)
def enumerate_devices(
models: Optional[Iterable["TrezorModel"]] = None,
) -> Sequence["Transport"]:
feat(python): add full type information WIP - typing the trezorctl apps typing functions trezorlib/cli addressing most of mypy issue for trezorlib apps and _internal folder fixing broken device tests by changing asserts in debuglink.py addressing most of mypy issues in trezorlib/cli folder adding types to some untyped functions, mypy section in setup.cfg typing what can be typed, some mypy fixes, resolving circular import issues importing type objects in "if TYPE_CHECKING:" branch fixing CI by removing assert in emulator, better ignore comments CI assert fix, style fixes, new config options fixup! CI assert fix, style fixes, new config options type fixes after rebasing on master fixing python3.6 and 3.7 unittests by importing Literal from typing_extensions couple mypy and style fixes fixes and improvements from code review silencing all but one mypy issues trial of typing the tools.expect function fixup! trial of typing the tools.expect function @expect and @session decorators correctly type-checked Optional args in CLI where relevant, not using general list/tuple/dict where possible python/Makefile commands, adding them into CI, ignoring last mypy issue documenting overload for expect decorator, two mypy fixes coming from that black style fix improved typing of decorators, pyright config file addressing or ignoring pyright errors, replacing mypy in CI by pyright fixing incomplete assert causing device tests to fail pyright issue that showed in CI but not locally, printing pyright version in CI fixup! pyright issue that showed in CI but not locally, printing pyright version in CI unifying type:ignore statements for pyright usage resolving PIL.Image issues, pyrightconfig not excluding anything replacing couple asserts with TypeGuard on safe_issubclass better error handling of usb1 import for webusb better error handling of hid import small typing details found out by strict pyright mode improvements from code review chore(python): changing List to Sequence for protobuf messages small code changes to reflect the protobuf change to Sequence importing TypedDict from typing_extensions to support 3.6 and 3.7 simplify _format_access_list function fixup! simplify _format_access_list function typing tools folder typing helper-scripts folder some click typing enforcing all functions to have typed arguments reverting the changed argument name in tools replacing TransportType with Transport making PinMatrixRequest.type protobuf attribute required reverting the protobuf change, making argument into get_pin Optional small fixes in asserts solving the session decorator type issues fixup! solving the session decorator type issues improvements from code review fixing new pyright errors introduced after version increase changing -> Iterable to -> Sequence in enumerate_devices, change in wait_for_devices style change in debuglink.py chore(python): adding type annotation to Sequences in messages.py better "self and cls" types on Transport fixup! better "self and cls" types on Transport fixing some easy things from strict pyright run
3 years ago
devices: List["Transport"] = []
for transport in all_transports():
name = transport.__name__
try:
found = list(transport.enumerate(models))
LOG.info(f"Enumerating {name}: found {len(found)} devices")
devices.extend(found)
except NotImplementedError:
LOG.error(f"{name} does not implement device enumeration")
except Exception as e:
excname = e.__class__.__name__
LOG.error(f"Failed to enumerate {name}. {excname}: {e}")
return devices
feat(python): add full type information WIP - typing the trezorctl apps typing functions trezorlib/cli addressing most of mypy issue for trezorlib apps and _internal folder fixing broken device tests by changing asserts in debuglink.py addressing most of mypy issues in trezorlib/cli folder adding types to some untyped functions, mypy section in setup.cfg typing what can be typed, some mypy fixes, resolving circular import issues importing type objects in "if TYPE_CHECKING:" branch fixing CI by removing assert in emulator, better ignore comments CI assert fix, style fixes, new config options fixup! CI assert fix, style fixes, new config options type fixes after rebasing on master fixing python3.6 and 3.7 unittests by importing Literal from typing_extensions couple mypy and style fixes fixes and improvements from code review silencing all but one mypy issues trial of typing the tools.expect function fixup! trial of typing the tools.expect function @expect and @session decorators correctly type-checked Optional args in CLI where relevant, not using general list/tuple/dict where possible python/Makefile commands, adding them into CI, ignoring last mypy issue documenting overload for expect decorator, two mypy fixes coming from that black style fix improved typing of decorators, pyright config file addressing or ignoring pyright errors, replacing mypy in CI by pyright fixing incomplete assert causing device tests to fail pyright issue that showed in CI but not locally, printing pyright version in CI fixup! pyright issue that showed in CI but not locally, printing pyright version in CI unifying type:ignore statements for pyright usage resolving PIL.Image issues, pyrightconfig not excluding anything replacing couple asserts with TypeGuard on safe_issubclass better error handling of usb1 import for webusb better error handling of hid import small typing details found out by strict pyright mode improvements from code review chore(python): changing List to Sequence for protobuf messages small code changes to reflect the protobuf change to Sequence importing TypedDict from typing_extensions to support 3.6 and 3.7 simplify _format_access_list function fixup! simplify _format_access_list function typing tools folder typing helper-scripts folder some click typing enforcing all functions to have typed arguments reverting the changed argument name in tools replacing TransportType with Transport making PinMatrixRequest.type protobuf attribute required reverting the protobuf change, making argument into get_pin Optional small fixes in asserts solving the session decorator type issues fixup! solving the session decorator type issues improvements from code review fixing new pyright errors introduced after version increase changing -> Iterable to -> Sequence in enumerate_devices, change in wait_for_devices style change in debuglink.py chore(python): adding type annotation to Sequences in messages.py better "self and cls" types on Transport fixup! better "self and cls" types on Transport fixing some easy things from strict pyright run
3 years ago
def get_transport(
path: Optional[str] = None, prefix_search: bool = False
) -> "Transport":
if path is None:
try:
return next(iter(enumerate_devices()))
except StopIteration:
raise TransportException("No Trezor device found") from None
# Find whether B is prefix of A (transport name is part of the path)
# or A is prefix of B (path is a prefix, or a name, of transport).
# This naively expects that no two transports have a common prefix.
def match_prefix(a: str, b: str) -> bool:
return a.startswith(b) or b.startswith(a)
LOG.info(
"looking for device by {}: {}".format(
"prefix" if prefix_search else "full path", path
)
)
transports = [t for t in all_transports() if match_prefix(path, t.PATH_PREFIX)]
if transports:
return transports[0].find_by_path(path, prefix_search=prefix_search)
raise TransportException(f"Could not find device by path: {path}")