2018-06-21 14:28:34 +00:00
# This file is part of the Trezor project.
2017-12-12 15:40:11 +00:00
#
2021-11-26 14:50:43 +00:00
# Copyright (C) 2012-2022 SatoshiLabs and contributors
2017-12-12 15:40:11 +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.
2017-12-12 15:40:11 +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>.
2017-12-12 15:40:11 +00:00
2019-08-22 14:44:23 +00:00
"""
Extremely minimal streaming codec for a subset of protobuf .
Supports uint32 , bytes , string , embedded message and repeated fields .
2017-12-12 15:40:11 +00:00
2019-08-22 14:44:23 +00:00
For de - serializing ( loading ) protobuf types , object with ` Reader ` interface is required .
For serializing ( dumping ) protobuf types , object with ` Writer ` interface is required .
"""
2017-12-12 15:40:11 +00:00
2019-08-02 17:06:01 +00:00
import logging
2020-10-08 10:03:29 +00:00
import warnings
2021-11-22 10:51:08 +00:00
from dataclasses import dataclass
2021-06-01 09:29:20 +00:00
from enum import IntEnum
2017-12-12 15:40:11 +00:00
from io import BytesIO
2020-10-08 09:28:11 +00:00
from itertools import zip_longest
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
2021-11-03 22:12:53 +00:00
from typing import Any , Dict , List , Optional , Tuple , Type , TypeVar , Union
2019-08-22 14:44:23 +00:00
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
2021-11-03 22:12:53 +00:00
from typing_extensions import Protocol , TypeGuard
2019-08-22 14:44:23 +00:00
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
2021-11-03 22:12:53 +00:00
T = TypeVar ( " T " , bound = type )
2019-08-22 14:44:23 +00:00
MT = TypeVar ( " MT " , bound = " MessageType " )
class Reader ( Protocol ) :
2021-12-08 09:00:47 +00:00
def readinto ( self , __buf : bytearray ) - > int :
2019-08-22 14:44:23 +00:00
"""
Reads exactly ` len ( buffer ) ` bytes into ` buffer ` . Returns number of bytes read ,
or 0 if it cannot read that much .
"""
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
2021-11-03 22:12:53 +00:00
. . .
2019-08-22 14:44:23 +00:00
class Writer ( Protocol ) :
2021-12-08 09:00:47 +00:00
def write ( self , __buf : bytes ) - > int :
2019-08-22 14:44:23 +00:00
"""
Writes all bytes from ` buffer ` , or raises ` EOFError `
"""
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
2021-11-03 22:12:53 +00:00
. . .
2019-08-22 14:44:23 +00:00
2017-12-12 15:40:11 +00:00
_UVARINT_BUFFER = bytearray ( 1 )
2019-08-02 17:06:01 +00:00
LOG = logging . getLogger ( __name__ )
2017-12-12 15:40:11 +00:00
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
2021-11-03 22:12:53 +00:00
def safe_issubclass ( value : Any , cls : Union [ T , Tuple [ T , . . . ] ] ) - > TypeGuard [ T ] :
2021-06-01 09:29:20 +00:00
return isinstance ( value , type ) and issubclass ( value , cls )
2019-08-22 14:44:23 +00:00
def load_uvarint ( reader : Reader ) - > int :
2017-12-12 15:40:11 +00:00
buffer = _UVARINT_BUFFER
result = 0
shift = 0
byte = 0x80
2019-08-22 14:44:23 +00:00
bytes_read = 0
2017-12-12 15:40:11 +00:00
while byte & 0x80 :
if reader . readinto ( buffer ) == 0 :
2019-08-22 14:44:23 +00:00
if bytes_read > 0 :
raise IOError ( " Interrupted UVarint " )
else :
raise EOFError
bytes_read + = 1
2017-12-12 15:40:11 +00:00
byte = buffer [ 0 ]
result + = ( byte & 0x7F ) << shift
shift + = 7
return result
2019-08-22 14:44:23 +00:00
def dump_uvarint ( writer : Writer , n : int ) - > None :
2018-04-11 09:15:38 +00:00
if n < 0 :
raise ValueError ( " Cannot dump signed value, convert it to unsigned first. " )
2017-12-12 15:40:11 +00:00
buffer = _UVARINT_BUFFER
2019-08-22 14:44:23 +00:00
shifted = 1
2017-12-12 15:40:11 +00:00
while shifted :
shifted = n >> 7
buffer [ 0 ] = ( n & 0x7F ) | ( 0x80 if shifted else 0x00 )
writer . write ( buffer )
n = shifted
2018-04-11 09:15:38 +00:00
# protobuf interleaved signed encoding:
# https://developers.google.com/protocol-buffers/docs/encoding#structure
# the idea is to save the sign in LSbit instead of twos-complement.
# so counting up, you go: 0, -1, 1, -2, 2, ... (as the first bit changes, sign flips)
#
# To achieve this with a twos-complement number:
# 1. shift left by 1, leaving LSbit free
2018-05-07 12:09:56 +00:00
# 2. if the number is negative, do bitwise negation.
2018-04-11 09:15:38 +00:00
# This keeps positive number the same, and converts negative from twos-complement
2018-05-07 12:09:56 +00:00
# to the appropriate value, while setting the sign bit.
2018-04-11 09:15:38 +00:00
#
# The original algorithm makes use of the fact that arithmetic (signed) shift
2018-05-07 12:09:56 +00:00
# keeps the sign bits, so for a n-bit number, (x >> n) gets us "all sign bits".
# Then you can take "number XOR all-sign-bits", which is XOR 0 (identity) for positive
# and XOR 1 (bitwise negation) for negative. Cute and efficient.
2018-04-11 09:15:38 +00:00
#
2018-05-07 12:09:56 +00:00
# But this is harder in Python because we don't natively know the bit size of the number.
# So we have to branch on whether the number is negative.
2017-12-12 15:40:11 +00:00
2018-08-13 16:21:24 +00:00
2019-08-22 14:44:23 +00:00
def sint_to_uint ( sint : int ) - > int :
2018-04-11 09:15:38 +00:00
res = sint << 1
if sint < 0 :
res = ~ res
return res
2017-12-12 15:40:11 +00:00
2018-04-11 09:15:38 +00:00
2019-08-22 14:44:23 +00:00
def uint_to_sint ( uint : int ) - > int :
2018-04-11 09:15:38 +00:00
sign = uint & 1
res = uint >> 1
if sign :
res = ~ res
return res
2021-06-01 09:29:20 +00:00
WIRE_TYPE_INT = 0
WIRE_TYPE_LENGTH = 2
2017-12-12 15:40:11 +00:00
2021-06-01 09:29:20 +00:00
WIRE_TYPES = {
" uint32 " : WIRE_TYPE_INT ,
" uint64 " : WIRE_TYPE_INT ,
" sint32 " : WIRE_TYPE_INT ,
" sint64 " : WIRE_TYPE_INT ,
" bool " : WIRE_TYPE_INT ,
" bytes " : WIRE_TYPE_LENGTH ,
" string " : WIRE_TYPE_LENGTH ,
}
2017-12-12 15:40:11 +00:00
2021-06-01 09:29:20 +00:00
REQUIRED_FIELD_PLACEHOLDER = object ( )
2018-01-30 14:04:24 +00:00
2021-11-22 10:51:08 +00:00
@dataclass
2021-06-01 09:29:20 +00:00
class Field :
name : str
2021-07-21 11:28:52 +00:00
type : str
2021-11-22 10:51:08 +00:00
repeated : bool = False
required : bool = False
default : object = None
2017-12-12 15:40:11 +00:00
2021-06-01 09:29:20 +00:00
@property
def wire_type ( self ) - > int :
if self . type in WIRE_TYPES :
return WIRE_TYPES [ self . type ]
2017-12-12 15:40:11 +00:00
2021-07-21 11:28:52 +00:00
field_type_object = get_field_type_object ( self )
if safe_issubclass ( field_type_object , MessageType ) :
2021-06-01 09:29:20 +00:00
return WIRE_TYPE_LENGTH
2019-08-02 17:06:01 +00:00
2021-07-21 11:28:52 +00:00
if safe_issubclass ( field_type_object , IntEnum ) :
2021-06-01 09:29:20 +00:00
return WIRE_TYPE_INT
2019-08-02 17:06:01 +00:00
2021-06-01 09:29:20 +00:00
raise ValueError ( f " Unrecognized type for field { self . name } " )
2019-08-02 17:06:01 +00:00
2021-06-01 09:29:20 +00:00
def value_fits ( self , value : int ) - > bool :
if self . type == " uint32 " :
2022-06-21 13:31:47 +00:00
return 0 < = value < 2 * * 32
2021-06-01 09:29:20 +00:00
if self . type == " uint64 " :
2022-06-21 13:31:47 +00:00
return 0 < = value < 2 * * 64
2021-06-01 09:29:20 +00:00
if self . type == " sint32 " :
2022-06-21 13:31:47 +00:00
return - ( 2 * * 31 ) < = value < 2 * * 31
2021-06-01 09:29:20 +00:00
if self . type == " sint64 " :
2022-06-21 13:31:47 +00:00
return - ( 2 * * 63 ) < = value < 2 * * 63
2019-08-02 17:06:01 +00:00
2021-06-01 09:29:20 +00:00
raise ValueError ( f " Cannot check range bounds for { self . type } " )
2017-12-12 15:40:11 +00:00
2020-10-08 09:28:11 +00:00
class _MessageTypeMeta ( type ) :
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
2021-11-03 22:12:53 +00:00
def __init__ ( cls , name : str , bases : tuple , d : dict ) - > None :
2022-03-01 12:55:58 +00:00
super ( ) . __init__ ( name , bases , d ) # type: ignore [Expected 1 positional argument]
2020-10-08 09:28:11 +00:00
if name != " MessageType " :
2022-03-01 12:55:58 +00:00
cls . __init__ = MessageType . __init__ # type: ignore ["__init__" is obscured by a declaration of the same name;;Cannot assign member "__init__" for type "_MessageTypeMeta"]
2020-10-08 09:28:11 +00:00
class MessageType ( metaclass = _MessageTypeMeta ) :
2021-06-01 09:29:20 +00:00
MESSAGE_WIRE_TYPE : Optional [ int ] = None
2020-10-08 09:28:11 +00:00
2021-06-01 09:29:20 +00:00
FIELDS : Dict [ int , Field ] = { }
2017-12-12 15:40:11 +00:00
2019-11-14 14:36:33 +00:00
@classmethod
2021-06-01 09:29:20 +00:00
def get_field ( cls , name : str ) - > Optional [ Field ] :
return next ( ( f for f in cls . FIELDS . values ( ) if f . name == name ) , None )
2019-11-14 14:36:33 +00:00
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
2021-11-03 22:12:53 +00:00
def __init__ ( self , * args : Any , * * kwargs : Any ) - > None :
2020-10-08 09:28:11 +00:00
if args :
warnings . warn (
" Positional arguments for MessageType are deprecated " ,
DeprecationWarning ,
stacklevel = 2 ,
)
# process fields one by one
2021-06-01 09:29:20 +00:00
MISSING = object ( )
for field , val in zip_longest ( self . FIELDS . values ( ) , args , fillvalue = MISSING ) :
if field is MISSING :
2020-10-08 09:28:11 +00:00
raise TypeError ( " too many positional arguments " )
2021-06-01 09:29:20 +00:00
if field . name in kwargs and val is not MISSING :
2020-10-08 09:28:11 +00:00
# both *args and **kwargs specify the same thing
2021-06-01 09:29:20 +00:00
raise TypeError ( f " got multiple values for argument ' { field . name } ' " )
elif field . name in kwargs :
2020-10-08 09:28:11 +00:00
# set in kwargs but not in args
2021-06-01 09:29:20 +00:00
setattr ( self , field . name , kwargs [ field . name ] )
elif val is not MISSING :
2020-10-08 09:28:11 +00:00
# set in args but not in kwargs
2021-06-01 09:29:20 +00:00
setattr ( self , field . name , val )
2020-10-08 09:28:11 +00:00
else :
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
2021-11-03 22:12:53 +00:00
default : Any
2020-10-08 09:28:11 +00:00
# not set at all, pick a default
2021-06-01 09:29:20 +00:00
if field . repeated :
default = [ ]
elif field . required :
2020-10-08 09:28:11 +00:00
warnings . warn (
2021-06-01 09:29:20 +00:00
f " Value of required field ' { field . name } ' must be provided in constructor " ,
2020-10-08 09:28:11 +00:00
DeprecationWarning ,
stacklevel = 2 ,
)
2021-06-01 09:29:20 +00:00
default = REQUIRED_FIELD_PLACEHOLDER
else :
default = field . default
setattr ( self , field . name , default )
2017-12-12 15:40:11 +00:00
2019-08-22 14:44:23 +00:00
def __eq__ ( self , rhs : Any ) - > bool :
2018-08-13 16:21:24 +00:00
return self . __class__ is rhs . __class__ and self . __dict__ == rhs . __dict__
2017-12-12 15:40:11 +00:00
2019-08-22 14:44:23 +00:00
def __repr__ ( self ) - > str :
2018-01-07 17:07:13 +00:00
d = { }
for key , value in self . __dict__ . items ( ) :
if value is None or value == [ ] :
continue
d [ key ] = value
2021-09-27 10:13:51 +00:00
return f " < { self . __class__ . __name__ } : { d } > "
2017-12-12 15:40:11 +00:00
2019-08-22 14:44:23 +00:00
def ByteSize ( self ) - > int :
2017-12-12 15:40:11 +00:00
data = BytesIO ( )
dump_message ( data , self )
return len ( data . getvalue ( ) )
class LimitedReader :
2019-08-22 14:44:23 +00:00
def __init__ ( self , reader : Reader , limit : int ) - > None :
2017-12-12 15:40:11 +00:00
self . reader = reader
self . limit = limit
2019-08-22 14:44:23 +00:00
def readinto ( self , buf : bytearray ) - > int :
2017-12-12 15:40:11 +00:00
if self . limit < len ( buf ) :
2019-08-22 14:44:23 +00:00
return 0
2017-12-12 15:40:11 +00:00
else :
nread = self . reader . readinto ( buf )
self . limit - = nread
return nread
class CountingWriter :
2019-08-22 14:44:23 +00:00
def __init__ ( self ) - > None :
2017-12-12 15:40:11 +00:00
self . size = 0
2019-08-22 14:44:23 +00:00
def write ( self , buf : bytes ) - > int :
2017-12-12 15:40:11 +00:00
nwritten = len ( buf )
self . size + = nwritten
return nwritten
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
2021-11-03 22:12:53 +00:00
def get_field_type_object (
field : Field ,
) - > Optional [ Union [ Type [ MessageType ] , Type [ IntEnum ] ] ] :
2021-07-21 11:28:52 +00:00
from . import messages
field_type_object = getattr ( messages , field . type , None )
if not safe_issubclass ( field_type_object , ( IntEnum , MessageType ) ) :
return None
return field_type_object
2021-06-01 09:29:20 +00:00
def decode_packed_array_field ( field : Field , reader : Reader ) - > List [ Any ] :
assert field . repeated , " Not decoding packed array into non-repeated field "
2019-08-22 14:44:23 +00:00
length = load_uvarint ( reader )
packed_reader = LimitedReader ( reader , length )
values = [ ]
try :
while True :
2021-06-01 09:29:20 +00:00
values . append ( decode_varint_field ( field , packed_reader ) )
2019-08-22 14:44:23 +00:00
except EOFError :
pass
return values
2021-06-01 09:29:20 +00:00
def decode_varint_field ( field : Field , reader : Reader ) - > Union [ int , bool , IntEnum ] :
assert field . wire_type == WIRE_TYPE_INT , f " Field { field . name } is not varint-encoded "
2019-08-22 14:44:23 +00:00
value = load_uvarint ( reader )
2021-07-21 11:28:52 +00:00
field_type_object = get_field_type_object ( field )
if safe_issubclass ( field_type_object , IntEnum ) :
2021-06-01 09:29:20 +00:00
try :
2021-07-21 11:28:52 +00:00
return field_type_object ( value )
2021-06-01 09:29:20 +00:00
except ValueError as e :
# treat enum errors as warnings
LOG . info ( f " On field { field . name } : { e } " )
return value
if field . type . startswith ( " uint " ) :
if not field . value_fits ( value ) :
LOG . info (
f " On field { field . name } : value { value } out of range for { field . type } "
)
return value
if field . type . startswith ( " sint " ) :
value = uint_to_sint ( value )
if not field . value_fits ( value ) :
LOG . info (
f " On field { field . name } : value { value } out of range for { field . type } "
)
2019-08-22 14:44:23 +00:00
return value
2021-06-01 09:29:20 +00:00
if field . type == " bool " :
2019-08-22 14:44:23 +00:00
return bool ( value )
2021-06-01 09:29:20 +00:00
raise TypeError # not a varint field or unknown type
2019-08-22 14:44:23 +00:00
def decode_length_delimited_field (
2021-06-01 09:29:20 +00:00
field : Field , reader : Reader
2019-08-22 14:44:23 +00:00
) - > Union [ bytes , str , MessageType ] :
value = load_uvarint ( reader )
2021-06-01 09:29:20 +00:00
if field . type == " bytes " :
2019-08-22 14:44:23 +00:00
buf = bytearray ( value )
reader . readinto ( buf )
return bytes ( buf )
2021-06-01 09:29:20 +00:00
if field . type == " string " :
2019-08-22 14:44:23 +00:00
buf = bytearray ( value )
reader . readinto ( buf )
return buf . decode ( )
2021-07-21 11:28:52 +00:00
field_type_object = get_field_type_object ( field )
if safe_issubclass ( field_type_object , MessageType ) :
return load_message ( LimitedReader ( reader , value ) , field_type_object )
2021-06-01 09:29:20 +00:00
raise TypeError # field type is unknown
2019-08-22 14:44:23 +00:00
2020-09-14 10:47:06 +00:00
2021-06-01 09:29:20 +00:00
def load_message ( reader : Reader , msg_type : Type [ MT ] ) - > MT :
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
2021-11-03 22:12:53 +00:00
msg_dict : Dict [ str , Any ] = { }
2020-09-14 10:47:06 +00:00
# pre-seed the dict
2021-06-01 09:29:20 +00:00
for field in msg_type . FIELDS . values ( ) :
if field . repeated :
msg_dict [ field . name ] = [ ]
elif not field . required :
msg_dict [ field . name ] = field . default
2017-12-12 15:40:11 +00:00
while True :
try :
fkey = load_uvarint ( reader )
except EOFError :
break # no more fields to load
ftag = fkey >> 3
wtype = fkey & 7
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
2021-11-03 22:12:53 +00:00
if ftag not in msg_type . FIELDS : # unknown field, skip it
2021-06-01 09:29:20 +00:00
if wtype == WIRE_TYPE_INT :
2017-12-12 15:40:11 +00:00
load_uvarint ( reader )
2021-06-01 09:29:20 +00:00
elif wtype == WIRE_TYPE_LENGTH :
2017-12-12 15:40:11 +00:00
ivalue = load_uvarint ( reader )
reader . readinto ( bytearray ( ivalue ) )
else :
raise ValueError
continue
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
2021-11-03 22:12:53 +00:00
field = msg_type . FIELDS [ ftag ]
2021-06-01 09:29:20 +00:00
if (
wtype == WIRE_TYPE_LENGTH
and field . wire_type == WIRE_TYPE_INT
and field . repeated
) :
2019-08-22 14:44:23 +00:00
# packed array
2021-06-01 09:29:20 +00:00
fvalues = decode_packed_array_field ( field , reader )
2019-08-22 14:44:23 +00:00
2021-06-01 09:29:20 +00:00
elif wtype != field . wire_type :
raise ValueError ( f " Field { field . name } received value does not match schema " )
2017-12-12 15:40:11 +00:00
2021-06-01 09:29:20 +00:00
elif wtype == WIRE_TYPE_LENGTH :
fvalues = [ decode_length_delimited_field ( field , reader ) ]
2019-08-22 14:44:23 +00:00
2021-06-01 09:29:20 +00:00
elif wtype == WIRE_TYPE_INT :
fvalues = [ decode_varint_field ( field , reader ) ]
2019-08-22 14:44:23 +00:00
2017-12-12 15:40:11 +00:00
else :
2019-08-22 14:44:23 +00:00
raise TypeError # unknown wire type
2017-12-12 15:40:11 +00:00
2021-06-01 09:29:20 +00:00
if field . repeated :
msg_dict [ field . name ] . extend ( fvalues )
2019-08-22 14:44:23 +00:00
elif len ( fvalues ) != 1 :
raise ValueError ( " Unexpected multiple values in non-repeating field " )
else :
2021-06-01 09:29:20 +00:00
msg_dict [ field . name ] = fvalues [ 0 ]
2017-12-12 15:40:11 +00:00
2021-06-01 09:29:20 +00:00
for field in msg_type . FIELDS . values ( ) :
if field . required and field . name not in msg_dict :
raise ValueError ( f " Did not receive value for field { field . name } " )
2020-09-14 10:47:06 +00:00
return msg_type ( * * msg_dict )
2017-12-12 15:40:11 +00:00
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
2021-11-03 22:12:53 +00:00
def dump_message ( writer : Writer , msg : " MessageType " ) - > None :
2017-12-12 15:40:11 +00:00
repvalue = [ 0 ]
mtype = msg . __class__
2021-06-01 09:29:20 +00:00
for ftag , field in mtype . FIELDS . items ( ) :
fvalue = getattr ( msg , field . name , None )
if fvalue is REQUIRED_FIELD_PLACEHOLDER :
raise ValueError ( f " Required value of field { field . name } was not provided " )
2017-12-12 15:40:11 +00:00
if fvalue is None :
2021-06-01 09:29:20 +00:00
# not sending empty values
2017-12-12 15:40:11 +00:00
continue
2021-06-01 09:29:20 +00:00
fkey = ( ftag << 3 ) | field . wire_type
2017-12-12 15:40:11 +00:00
2021-06-01 09:29:20 +00:00
if not field . repeated :
2017-12-12 15:40:11 +00:00
repvalue [ 0 ] = fvalue
fvalue = repvalue
for svalue in fvalue :
dump_uvarint ( writer , fkey )
2021-07-21 11:28:52 +00:00
field_type_object = get_field_type_object ( field )
if safe_issubclass ( field_type_object , MessageType ) :
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
2021-11-03 22:12:53 +00:00
if not isinstance ( svalue , field_type_object ) :
raise ValueError (
f " Value { svalue } in field { field . name } is not { field_type_object . __name__ } "
)
2021-06-01 09:29:20 +00:00
counter = CountingWriter ( )
dump_message ( counter , svalue )
dump_uvarint ( writer , counter . size )
dump_message ( writer , svalue )
2021-07-21 11:28:52 +00:00
elif safe_issubclass ( field_type_object , IntEnum ) :
if svalue not in field_type_object . __members__ . values ( ) :
2021-06-01 09:29:20 +00:00
raise ValueError (
2021-07-21 11:28:52 +00:00
f " Value { svalue } in field { field . name } unknown for { field . type } "
2021-06-01 09:29:20 +00:00
)
dump_uvarint ( writer , svalue )
elif field . type . startswith ( " uint " ) :
if not field . value_fits ( svalue ) :
raise ValueError (
f " Value { svalue } in field { field . name } does not fit into { field . type } "
)
2017-12-12 15:40:11 +00:00
dump_uvarint ( writer , svalue )
2021-06-01 09:29:20 +00:00
elif field . type . startswith ( " sint " ) :
if not field . value_fits ( svalue ) :
raise ValueError (
f " Value { svalue } in field { field . name } does not fit into { field . type } "
)
2018-04-11 09:15:38 +00:00
dump_uvarint ( writer , sint_to_uint ( svalue ) )
2018-01-30 14:04:24 +00:00
2021-06-01 09:29:20 +00:00
elif field . type == " bool " :
2017-12-12 15:40:11 +00:00
dump_uvarint ( writer , int ( svalue ) )
2021-06-01 09:29:20 +00:00
elif field . type == " bytes " :
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
2021-11-03 22:12:53 +00:00
assert isinstance ( svalue , ( bytes , bytearray ) )
2017-12-12 15:40:11 +00:00
dump_uvarint ( writer , len ( svalue ) )
writer . write ( svalue )
2021-06-01 09:29:20 +00:00
elif field . type == " string " :
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
2021-11-03 22:12:53 +00:00
assert isinstance ( svalue , str )
2019-08-29 11:56:09 +00:00
svalue_bytes = svalue . encode ( )
dump_uvarint ( writer , len ( svalue_bytes ) )
writer . write ( svalue_bytes )
2017-12-12 15:40:11 +00:00
else :
raise TypeError
2018-04-20 13:52:47 +00:00
2018-08-13 16:21:24 +00:00
def format_message (
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
2021-11-03 22:12:53 +00:00
pb : " MessageType " ,
2018-08-13 16:21:24 +00:00
indent : int = 0 ,
sep : str = " " * 4 ,
truncate_after : Optional [ int ] = 256 ,
truncate_to : Optional [ int ] = 64 ,
) - > str :
2019-08-22 14:44:23 +00:00
def mostly_printable ( bytes : bytes ) - > bool :
2018-05-09 16:01:51 +00:00
if not bytes :
return True
2018-10-01 12:01:33 +00:00
printable = sum ( 1 for byte in bytes if 0x20 < = byte < = 0x7E )
2018-05-09 16:01:51 +00:00
return printable / len ( bytes ) > 0.8
2019-08-02 17:06:01 +00:00
def pformat ( name : str , value : Any , indent : int ) - > str :
2018-04-20 13:52:47 +00:00
level = sep * indent
leadin = sep * ( indent + 1 )
2019-08-02 17:06:01 +00:00
2018-04-20 13:52:47 +00:00
if isinstance ( value , MessageType ) :
return format_message ( value , indent , sep )
2019-08-02 17:06:01 +00:00
2018-04-20 13:52:47 +00:00
if isinstance ( value , list ) :
2018-05-09 16:01:51 +00:00
# short list of simple values
2021-06-01 09:29:20 +00:00
if not value or all ( isinstance ( x , int ) for x in value ) :
2018-05-09 16:01:51 +00:00
return repr ( value )
# long list, one line per entry
2018-08-13 16:21:24 +00:00
lines = [ " [ " , level + " ] " ]
2019-08-02 17:06:01 +00:00
lines [ 1 : 1 ] = [ leadin + pformat ( name , x , indent + 1 ) + " , " for x in value ]
2018-08-13 16:21:24 +00:00
return " \n " . join ( lines )
2019-08-02 17:06:01 +00:00
2018-04-20 13:52:47 +00:00
if isinstance ( value , dict ) :
2018-08-13 16:21:24 +00:00
lines = [ " { " ]
2018-04-20 13:52:47 +00:00
for key , val in sorted ( value . items ( ) ) :
if val is None or val == [ ] :
continue
2019-08-02 17:06:01 +00:00
lines . append ( leadin + key + " : " + pformat ( key , val , indent + 1 ) + " , " )
2018-08-13 16:21:24 +00:00
lines . append ( level + " } " )
return " \n " . join ( lines )
2019-08-02 17:06:01 +00:00
2018-05-09 16:01:51 +00:00
if isinstance ( value , ( bytes , bytearray ) ) :
length = len ( value )
2018-08-13 16:21:24 +00:00
suffix = " "
2018-05-09 16:01:51 +00:00
if truncate_after and length > truncate_after :
2018-08-13 16:21:24 +00:00
suffix = " ... "
value = value [ : truncate_to or 0 ]
2018-05-09 16:01:51 +00:00
if mostly_printable ( value ) :
output = repr ( value )
else :
2018-09-12 22:44:08 +00:00
output = " 0x " + value . hex ( )
2021-09-27 10:13:51 +00:00
return f " { length } bytes { output } { suffix } "
2018-04-20 13:52:47 +00:00
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
2021-11-03 22:12:53 +00:00
field = pb . get_field ( name )
if field is not None :
if isinstance ( value , int ) and safe_issubclass ( field . type , IntEnum ) :
try :
return f " { field . type ( value ) . name } ( { value } ) "
except ValueError :
return str ( value )
2019-08-02 17:06:01 +00:00
2018-04-20 13:52:47 +00:00
return repr ( value )
2022-02-18 14:44:18 +00:00
try :
byte_size = str ( pb . ByteSize ( ) ) + " bytes "
except Exception :
byte_size = " encoding failed "
return " {name} ( {size} ) {content} " . format (
2018-04-23 10:58:30 +00:00
name = pb . __class__ . __name__ ,
2022-02-18 14:44:18 +00:00
size = byte_size ,
2019-08-02 17:06:01 +00:00
content = pformat ( " " , pb . __dict__ , indent ) ,
2018-04-23 10:58:30 +00:00
)
2018-08-21 13:58:26 +00:00
2021-06-01 09:29:20 +00:00
def value_to_proto ( field : Field , value : Any ) - > Any :
2021-07-21 11:28:52 +00:00
field_type_object = get_field_type_object ( field )
if safe_issubclass ( field_type_object , MessageType ) :
2018-08-21 13:58:26 +00:00
raise TypeError ( " value_to_proto only converts simple values " )
2021-07-21 11:28:52 +00:00
if safe_issubclass ( field_type_object , IntEnum ) :
2019-08-02 17:06:01 +00:00
if isinstance ( value , str ) :
2021-07-21 11:28:52 +00:00
return field_type_object . __members__ [ value ]
2019-05-06 11:26:23 +00:00
else :
2021-06-01 09:29:20 +00:00
try :
2021-07-21 11:28:52 +00:00
return field_type_object ( value )
2021-06-01 09:29:20 +00:00
except ValueError as e :
LOG . info ( f " On field { field . name } : { e } " )
return int ( value )
2018-08-21 13:58:26 +00:00
2021-06-01 09:29:20 +00:00
if " int " in field . type :
2019-08-02 17:06:01 +00:00
return int ( value )
2021-06-01 09:29:20 +00:00
if field . type == " bool " :
2018-08-21 13:58:26 +00:00
return bool ( value )
2021-06-01 09:29:20 +00:00
if field . type == " string " :
2018-08-21 13:58:26 +00:00
return str ( value )
2021-06-01 09:29:20 +00:00
if field . type == " bytes " :
2018-08-21 13:58:26 +00:00
if isinstance ( value , str ) :
2018-09-12 22:44:08 +00:00
return bytes . fromhex ( value )
2018-08-21 13:58:26 +00:00
elif isinstance ( value , bytes ) :
return value
else :
2021-06-01 09:29:20 +00:00
raise TypeError ( f " can ' t convert { type ( value ) } value to bytes " )
2018-08-21 13:58:26 +00:00
2019-08-22 14:44:23 +00:00
def dict_to_proto ( message_type : Type [ MT ] , d : Dict [ str , Any ] ) - > MT :
2018-08-21 13:58:26 +00:00
params = { }
2021-06-01 09:29:20 +00:00
for field in message_type . FIELDS . values ( ) :
value = d . get ( field . name )
2018-08-21 13:58:26 +00:00
if value is None :
continue
2021-06-01 09:29:20 +00:00
if not field . repeated :
2018-08-21 13:58:26 +00:00
value = [ value ]
2021-07-21 11:28:52 +00:00
field_type_object = get_field_type_object ( field )
if safe_issubclass ( field_type_object , MessageType ) :
newvalue = [ dict_to_proto ( field_type_object , v ) for v in value ]
2018-08-21 13:58:26 +00:00
else :
2021-06-01 09:29:20 +00:00
newvalue = [ value_to_proto ( field , v ) for v in value ]
2018-08-21 13:58:26 +00:00
2021-06-01 09:29:20 +00:00
if not field . repeated :
2018-08-21 13:58:26 +00:00
newvalue = newvalue [ 0 ]
2021-06-01 09:29:20 +00:00
params [ field . name ] = newvalue
2018-08-21 13:58:26 +00:00
return message_type ( * * params )
2018-11-02 16:06:04 +00:00
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
2021-11-03 22:12:53 +00:00
def to_dict ( msg : " MessageType " , hexlify_bytes : bool = True ) - > Dict [ str , Any ] :
def convert_value ( value : Any ) - > Any :
2019-02-19 16:14:12 +00:00
if hexlify_bytes and isinstance ( value , bytes ) :
return value . hex ( )
elif isinstance ( value , MessageType ) :
return to_dict ( value , hexlify_bytes )
elif isinstance ( value , list ) :
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
2021-11-03 22:12:53 +00:00
return [ convert_value ( v ) for v in value ]
2021-06-01 09:29:20 +00:00
elif isinstance ( value , IntEnum ) :
return value . name
2019-02-19 16:14:12 +00:00
else :
return value
2018-11-02 16:06:04 +00:00
res = { }
for key , value in msg . __dict__ . items ( ) :
if value is None or value == [ ] :
continue
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
2021-11-03 22:12:53 +00:00
res [ key ] = convert_value ( value )
2019-02-19 16:14:12 +00:00
2018-11-02 16:06:04 +00:00
return res