1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-22 14:28:07 +00:00

style(core): remove old-style annotations (Set, Tuple, Union)

This commit is contained in:
matejcik 2022-01-07 15:13:54 +01:00 committed by matejcik
parent 5e1dce35b3
commit e20879189f
24 changed files with 92 additions and 109 deletions

View File

@ -9,7 +9,6 @@ from trezor.enums import InputScriptType, OutputScriptType
from trezor.utils import HashWriter, ensure from trezor.utils import HashWriter, ensure
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Tuple
from enum import IntEnum from enum import IntEnum
from apps.common.coininfo import CoinInfo from apps.common.coininfo import CoinInfo
from trezor.messages import TxInput from trezor.messages import TxInput
@ -128,7 +127,7 @@ def encode_bech32_address(prefix: str, witver: int, script: bytes) -> str:
return address return address
def decode_bech32_address(prefix: str, address: str) -> Tuple[int, bytes]: def decode_bech32_address(prefix: str, address: str) -> tuple[int, bytes]:
witver, raw = bech32.decode(prefix, address) witver, raw = bech32.decode(prefix, address)
if witver not in _BECH32_WITVERS: if witver not in _BECH32_WITVERS:
raise wire.ProcessError("Invalid address witness program") raise wire.ProcessError("Invalid address witness program")

View File

@ -13,7 +13,7 @@ from . import authorization
from .common import BITCOIN_NAMES from .common import BITCOIN_NAMES
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Awaitable, Callable, Iterable, TypeVar, Union from typing import Awaitable, Callable, Iterable, TypeVar
from typing_extensions import Protocol from typing_extensions import Protocol
from trezor.protobuf import MessageType from trezor.protobuf import MessageType
@ -32,16 +32,16 @@ if TYPE_CHECKING:
from apps.common.keychain import Keychain, MsgOut, Handler from apps.common.keychain import Keychain, MsgOut, Handler
from apps.common.paths import Bip32Path from apps.common.paths import Bip32Path
BitcoinMessage = Union[ BitcoinMessage = (
AuthorizeCoinJoin, AuthorizeCoinJoin
GetAddress, | GetAddress
GetOwnershipId, | GetOwnershipId
GetOwnershipProof, | GetOwnershipProof
GetPublicKey, | GetPublicKey
SignMessage, | SignMessage
SignTx, | SignTx
VerifyMessage, | VerifyMessage
] )
class MsgWithAddressScriptType(Protocol): class MsgWithAddressScriptType(Protocol):
address_n: Bip32Path address_n: Bip32Path

View File

@ -12,7 +12,7 @@ if not utils.BITCOIN_ONLY:
from . import bitcoinlike, decred, zcash from . import bitcoinlike, decred, zcash
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Protocol, Union from typing import Protocol
from trezor.messages import ( from trezor.messages import (
SignTx, SignTx,
@ -29,14 +29,14 @@ if TYPE_CHECKING:
from ..authorization import CoinJoinAuthorization from ..authorization import CoinJoinAuthorization
TxAckType = Union[ TxAckType = (
TxAckInput, TxAckInput
TxAckOutput, | TxAckOutput
TxAckPrevMeta, | TxAckPrevMeta
TxAckPrevInput, | TxAckPrevInput
TxAckPrevOutput, | TxAckPrevOutput
TxAckPrevExtraData, | TxAckPrevExtraData
] )
class SignerClass(Protocol): class SignerClass(Protocol):
def __init__( # pylint: disable=super-init-not-called def __init__( # pylint: disable=super-init-not-called

View File

@ -19,7 +19,6 @@ from .helpers.utils import derive_public_key
from .layout import confirm_catalyst_registration, show_auxiliary_data_hash from .layout import confirm_catalyst_registration, show_auxiliary_data_hash
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Union
from trezor import wire from trezor import wire
from trezor.messages import ( from trezor.messages import (
@ -27,11 +26,11 @@ if TYPE_CHECKING:
CardanoTxAuxiliaryData, CardanoTxAuxiliaryData,
) )
CatalystRegistrationPayload = dict[int, Union[bytes, int]] CatalystRegistrationPayload = dict[int, bytes | int]
SignedCatalystRegistrationPayload = tuple[CatalystRegistrationPayload, bytes] SignedCatalystRegistrationPayload = tuple[CatalystRegistrationPayload, bytes]
CatalystRegistrationSignature = dict[int, bytes] CatalystRegistrationSignature = dict[int, bytes]
CatalystRegistration = dict[ CatalystRegistration = dict[
int, Union[CatalystRegistrationPayload, CatalystRegistrationSignature] int, CatalystRegistrationPayload | CatalystRegistrationSignature
] ]
from . import seed from . import seed

View File

@ -11,7 +11,7 @@ from apps.common.seed import derive_and_store_roots, get_seed
from .helpers import paths from .helpers import paths
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Callable, Awaitable, TypeVar, Union from typing import Callable, Awaitable, TypeVar
from apps.common.paths import Bip32Path from apps.common.paths import Bip32Path
from apps.common.keychain import MsgOut, Handler from apps.common.keychain import MsgOut, Handler
@ -23,12 +23,12 @@ if TYPE_CHECKING:
CardanoSignTxInit, CardanoSignTxInit,
) )
CardanoMessages = Union[ CardanoMessages = (
CardanoGetAddress, CardanoGetAddress
CardanoGetPublicKey, | CardanoGetPublicKey
CardanoGetNativeScriptHash, | CardanoGetNativeScriptHash
CardanoSignTxInit, | CardanoSignTxInit
] )
MsgIn = TypeVar("MsgIn", bound=CardanoMessages) MsgIn = TypeVar("MsgIn", bound=CardanoMessages)
HandlerWithKeychain = Callable[[wire.Context, MsgIn, "Keychain"], Awaitable[MsgOut]] HandlerWithKeychain = Callable[[wire.Context, MsgIn, "Keychain"], Awaitable[MsgOut]]

View File

@ -107,10 +107,10 @@ from .layout import (
from .seed import is_byron_path, is_multisig_path, is_shelley_path from .seed import is_byron_path, is_multisig_path, is_shelley_path
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Any, Union from typing import Any
from apps.common.paths import PathSchema from apps.common.paths import PathSchema
CardanoTxResponseType = Union[CardanoTxItemAck, CardanoTxWitnessResponse] CardanoTxResponseType = CardanoTxItemAck | CardanoTxWitnessResponse
MINTING_POLICY_ID_LENGTH = 28 MINTING_POLICY_ID_LENGTH = 28
MAX_ASSET_NAME_LENGTH = 32 MAX_ASSET_NAME_LENGTH = 32

View File

@ -11,12 +11,12 @@ from trezor import log, utils
from . import readers from . import readers
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Any, Generic, Iterator, Tuple, TypeVar, Union from typing import Any, Generic, Iterator, TypeVar
K = TypeVar("K") K = TypeVar("K")
V = TypeVar("V") V = TypeVar("V")
Value = Any Value = Any
CborSequence = Union[list[Value], Tuple[Value, ...]] CborSequence = list[Value] | tuple[Value, ...]
else: else:
# typechecker cheat: Generic[K, V] will be `object` which is a valid parent type # typechecker cheat: Generic[K, V] will be `object` which is a valid parent type
Generic = {(0, 0): object} Generic = {(0, 0): object}

View File

@ -3,7 +3,6 @@ from typing import TYPE_CHECKING
from trezor.utils import ensure from trezor.utils import ensure
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Union
from trezor.utils import Writer from trezor.utils import Writer
@ -71,7 +70,7 @@ def write_uint64_be(w: Writer, n: int) -> int:
return 8 return 8
def write_bytes_unchecked(w: Writer, b: Union[bytes, memoryview]) -> int: def write_bytes_unchecked(w: Writer, b: bytes | memoryview) -> int:
w.extend(b) w.extend(b)
return len(b) return len(b)

View File

@ -8,7 +8,7 @@ from apps.common.keychain import get_keychain
from . import CURVE, networks from . import CURVE, networks
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Callable, Iterable, TypeVar, Union from typing import Callable, Iterable, TypeVar
from trezor.messages import ( from trezor.messages import (
EthereumGetAddress, EthereumGetAddress,
@ -21,19 +21,16 @@ if TYPE_CHECKING:
from apps.common.keychain import MsgOut, Handler, HandlerWithKeychain from apps.common.keychain import MsgOut, Handler, HandlerWithKeychain
EthereumMessages = Union[ EthereumMessages = (
EthereumGetAddress, EthereumGetAddress
EthereumGetPublicKey, | EthereumGetPublicKey
EthereumSignTx, | EthereumSignTx
EthereumSignMessage, | EthereumSignMessage
EthereumSignTypedData, | EthereumSignTypedData
] )
MsgIn = TypeVar("MsgIn", bound=EthereumMessages) MsgIn = TypeVar("MsgIn", bound=EthereumMessages)
EthereumSignTxAny = Union[ EthereumSignTxAny = EthereumSignTx | EthereumSignTxEIP1559
EthereumSignTx,
EthereumSignTxEIP1559,
]
MsgInChainId = TypeVar("MsgInChainId", bound=EthereumSignTxAny) MsgInChainId = TypeVar("MsgInChainId", bound=EthereumSignTxAny)

View File

@ -19,7 +19,7 @@ from . import networks, tokens
from .helpers import address_from_bytes, decode_typed_data, get_type_name from .helpers import address_from_bytes, decode_typed_data, get_type_name
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Awaitable, Iterable, Optional from typing import Awaitable, Iterable
from trezor.wire import Context from trezor.wire import Context
@ -185,7 +185,7 @@ async def confirm_typed_value(
value: bytes, value: bytes,
parent_objects: list[str], parent_objects: list[str],
field: EthereumFieldType, field: EthereumFieldType,
array_index: Optional[int] = None, array_index: int | None = None,
) -> None: ) -> None:
type_name = get_type_name(field) type_name = get_type_name(field)

View File

@ -20,8 +20,6 @@ from .layout import (
) )
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Tuple
from apps.common.keychain import Keychain from apps.common.keychain import Keychain
from .keychain import EthereumSignTxAny from .keychain import EthereumSignTxAny
@ -97,7 +95,7 @@ async def sign_tx(
async def handle_erc20( async def handle_erc20(
ctx: wire.Context, msg: EthereumSignTxAny ctx: wire.Context, msg: EthereumSignTxAny
) -> Tuple[tokens.TokenInfo | None, bytes, bytes, int]: ) -> tuple[tokens.TokenInfo | None, bytes, bytes, int]:
token = None token = None
address_bytes = recipient = bytes_from_address(msg.to) address_bytes = recipient = bytes_from_address(msg.to)
value = int.from_bytes(msg.value, "big") value = int.from_bytes(msg.value, "big")
@ -124,7 +122,7 @@ def get_total_length(msg: EthereumSignTx, data_total: int) -> int:
if msg.tx_type is not None: if msg.tx_type is not None:
length += rlp.length(msg.tx_type) length += rlp.length(msg.tx_type)
fields: Tuple[rlp.RLPItem, ...] = ( fields: tuple[rlp.RLPItem, ...] = (
msg.nonce, msg.nonce,
msg.gas_price, msg.gas_price,
msg.gas_limit, msg.gas_limit,

View File

@ -19,8 +19,6 @@ from .layout import (
from .sign_tx import check_common_fields, handle_erc20, send_request_chunk from .sign_tx import check_common_fields, handle_erc20, send_request_chunk
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Tuple
from trezor.messages import EthereumSignTxEIP1559 from trezor.messages import EthereumSignTxEIP1559
from apps.common.keychain import Keychain from apps.common.keychain import Keychain
@ -90,7 +88,7 @@ async def sign_tx_eip1559(
rlp.write_header(sha, total_length, rlp.LIST_HEADER_BYTE) rlp.write_header(sha, total_length, rlp.LIST_HEADER_BYTE)
fields: Tuple[rlp.RLPItem, ...] = ( fields: tuple[rlp.RLPItem, ...] = (
msg.chain_id, msg.chain_id,
msg.nonce, msg.nonce,
msg.max_priority_fee, msg.max_priority_fee,
@ -124,7 +122,7 @@ async def sign_tx_eip1559(
def get_total_length(msg: EthereumSignTxEIP1559, data_total: int) -> int: def get_total_length(msg: EthereumSignTxEIP1559, data_total: int) -> int:
length = 0 length = 0
fields: Tuple[rlp.RLPItem, ...] = ( fields: tuple[rlp.RLPItem, ...] = (
msg.nonce, msg.nonce,
msg.gas_limit, msg.gas_limit,
bytes_from_address(msg.to), bytes_from_address(msg.to),

View File

@ -9,7 +9,6 @@ from .. import backup_types
if TYPE_CHECKING: if TYPE_CHECKING:
from trezor.enums import BackupType from trezor.enums import BackupType
from typing import Union
class RecoveryAborted(Exception): class RecoveryAborted(Exception):
@ -94,7 +93,7 @@ def process_slip39(words: str) -> tuple[bytes | None, slip39.Share]:
if TYPE_CHECKING: if TYPE_CHECKING:
Slip39State = Union[tuple[int, BackupType], tuple[None, None]] Slip39State = tuple[int, BackupType] | tuple[None, None]
def load_slip39_state() -> Slip39State: def load_slip39_state() -> Slip39State:

View File

@ -4,7 +4,6 @@ from typing import TYPE_CHECKING
from trezor.enums import MessageType from trezor.enums import MessageType
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Union
from trezor import protobuf from trezor import protobuf
from trezor.messages import ( from trezor.messages import (
@ -23,21 +22,21 @@ if TYPE_CHECKING:
StellarSetOptionsOp, StellarSetOptionsOp,
) )
StellarMessageType = Union[ StellarMessageType = (
StellarAccountMergeOp, StellarAccountMergeOp
StellarAllowTrustOp, | StellarAllowTrustOp
StellarBumpSequenceOp, | StellarBumpSequenceOp
StellarChangeTrustOp, | StellarChangeTrustOp
StellarCreateAccountOp, | StellarCreateAccountOp
StellarCreatePassiveSellOfferOp, | StellarCreatePassiveSellOfferOp
StellarManageDataOp, | StellarManageDataOp
StellarManageBuyOfferOp, | StellarManageBuyOfferOp
StellarManageSellOfferOp, | StellarManageSellOfferOp
StellarPathPaymentStrictReceiveOp, | StellarPathPaymentStrictReceiveOp
StellarPathPaymentStrictSendOp, | StellarPathPaymentStrictSendOp
StellarPaymentOp, | StellarPaymentOp
StellarSetOptionsOp, | StellarSetOptionsOp
] )
TX_TYPE = b"\x00\x00\x00\x02" TX_TYPE = b"\x00\x00\x00\x02"

View File

@ -18,7 +18,6 @@ from apps.common.writers import (
from . import CURVE, PATTERNS, SLIP44_ID, helpers, layout from . import CURVE, PATTERNS, SLIP44_ID, helpers, layout
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Union
from apps.common.keychain import Keychain from apps.common.keychain import Keychain
from trezor.wire import Context from trezor.wire import Context
from trezor.messages import ( from trezor.messages import (
@ -249,9 +248,10 @@ def _get_operation_bytes(w: Writer, msg: TezosSignTx) -> None:
def _encode_common( def _encode_common(
w: Writer, w: Writer,
operation: Union[ operation: TezosDelegationOp
TezosDelegationOp, TezosOriginationOp, TezosTransactionOp, TezosRevealOp | TezosOriginationOp
], | TezosTransactionOp
| TezosRevealOp,
str_operation: str, str_operation: str,
) -> None: ) -> None:
operation_tags = { operation_tags = {

View File

@ -24,15 +24,15 @@ from typing import TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from enum import IntEnum from enum import IntEnum
from typing import Sequence, Union, TypeVar from typing import Sequence, TypeVar
A = TypeVar("A") A = TypeVar("A")
B = TypeVar("B") B = TypeVar("B")
C = TypeVar("C") C = TypeVar("C")
# usage: OptionalTuple[int, list[int]] is either (None, None) or (someint, somelist) # usage: OptionalTuple[int, list[int]] is either (None, None) or (someint, somelist)
# but not (None, somelist) # but not (None, somelist)
OptionalTuple2 = Union[tuple[None, None], tuple[A, B]] OptionalTuple2 = tuple[None, None] | tuple[A, B]
OptionalTuple3 = Union[tuple[None, None, None], tuple[A, B, C]] OptionalTuple3 = tuple[None, None, None] | tuple[A, B, C]
else: else:
IntEnum = object IntEnum = object

View File

@ -2,7 +2,6 @@ from micropython import const
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Union
from trezor.utils import Writer from trezor.utils import Writer
# The intention below is basically: # The intention below is basically:
@ -13,8 +12,8 @@ if TYPE_CHECKING:
# a generic `Sequence` (because we do isinstance checks for a list). We are however # a generic `Sequence` (because we do isinstance checks for a list). We are however
# only reading from the list and passing into things that consume a RLPItem. Hence # only reading from the list and passing into things that consume a RLPItem. Hence
# we have to enumerate single-type lists as well as the universal list[RLPItem]. # we have to enumerate single-type lists as well as the universal list[RLPItem].
RLPList = Union[list[int], list[bytes], list["RLPItem"]] RLPList = list[int] | list[bytes] | list["RLPItem"]
RLPItem = Union[RLPList, bytes, int] RLPItem = RLPList | bytes | int
STRING_HEADER_BYTE = const(0x80) STRING_HEADER_BYTE = const(0x80)

View File

@ -38,9 +38,9 @@ from trezor.crypto import hmac, pbkdf2, random
from trezor.errors import MnemonicError from trezor.errors import MnemonicError
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Callable, Iterable, Tuple from typing import Callable, Iterable
Indices = Tuple[int, ...] Indices = tuple[int, ...]
MnemonicGroups = dict[int, tuple[int, set[tuple[int, bytes]]]] MnemonicGroups = dict[int, tuple[int, set[tuple[int, bytes]]]]

View File

@ -17,9 +17,9 @@ LINE_WIDTH = ui.WIDTH - TEXT_MARGIN_LEFT
LINE_WIDTH_PAGINATED = LINE_WIDTH - PAGINATION_MARGIN_RIGHT LINE_WIDTH_PAGINATED = LINE_WIDTH - PAGINATION_MARGIN_RIGHT
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Any, Sequence, Union from typing import Any, Sequence
TextContent = Union[str, int] TextContent = str | int
# needs to be different from all colors and font ids # needs to be different from all colors and font ids
BR = const(-256) BR = const(-256)

View File

@ -5,9 +5,7 @@ from trezor import ui
from trezor.ui import display, in_area from trezor.ui import display, in_area
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Union ButtonContent = str | bytes
ButtonContent = Union[str, bytes]
ButtonStyleType = type["ButtonDefault"] ButtonStyleType = type["ButtonDefault"]
ButtonStyleStateType = type["ButtonDefault.normal"] ButtonStyleStateType = type["ButtonDefault.normal"]

View File

@ -6,9 +6,9 @@ from trezor import res, ui
from ...constants import TEXT_HEADER_HEIGHT, TEXT_LINE_HEIGHT from ...constants import TEXT_HEADER_HEIGHT, TEXT_LINE_HEIGHT
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Iterable, Union from typing import Iterable
ChecklistItem = Union[str, Iterable[str]] ChecklistItem = str | Iterable[str]
_CHECKLIST_MAX_LINES = const(5) _CHECKLIST_MAX_LINES = const(5)
_CHECKLIST_OFFSET_X = const(24) _CHECKLIST_OFFSET_X = const(24)

View File

@ -5,11 +5,11 @@ from trezor.enums import ButtonRequestType
from trezor.messages import ButtonAck, ButtonRequest from trezor.messages import ButtonAck, ButtonRequest
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Any, Awaitable, Optional, Tuple, Union from typing import Any, Awaitable
LayoutType = Awaitable[Any] LayoutType = Awaitable[Any]
PropertyType = Tuple[Optional[str], Union[str, bytes, None]] PropertyType = tuple[str | None, str | bytes | None]
ExceptionType = Union[BaseException, type[BaseException]] ExceptionType = BaseException | type[BaseException]
if __debug__: if __debug__:

View File

@ -8,9 +8,9 @@ from trezorui2 import layout_new_confirm_action
from .common import interact from .common import interact
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import NoReturn, Type, Union from typing import NoReturn, Type
ExceptionType = Union[BaseException, Type[BaseException]] ExceptionType = BaseException | Type[BaseException]
async def confirm_action( async def confirm_action(

View File

@ -30,20 +30,18 @@ if TYPE_CHECKING:
Any, Any,
Iterator, Iterator,
Protocol, Protocol,
Union,
TypeVar, TypeVar,
Sequence, Sequence,
Set,
) )
from trezor.protobuf import MessageType from trezor.protobuf import MessageType
def unimport_begin() -> Set[str]: def unimport_begin() -> set[str]:
return set(sys.modules) return set(sys.modules)
def unimport_end(mods: Set[str], collect: bool = True) -> None: def unimport_end(mods: set[str], collect: bool = True) -> None:
# static check that the size of sys.modules never grows above value of # static check that the size of sys.modules never grows above value of
# MICROPY_LOADED_MODULES_DICT_SIZE, so that the sys.modules dict is never # MICROPY_LOADED_MODULES_DICT_SIZE, so that the sys.modules dict is never
# reallocated at run-time # reallocated at run-time
@ -72,7 +70,7 @@ def unimport_end(mods: Set[str], collect: bool = True) -> None:
class unimport: class unimport:
def __init__(self) -> None: def __init__(self) -> None:
self.mods: Set[str] | None = None self.mods: set[str] | None = None
def __enter__(self) -> None: def __enter__(self) -> None:
self.mods = unimport_begin() self.mods = unimport_begin()
@ -186,7 +184,7 @@ class HashWriter:
if TYPE_CHECKING: if TYPE_CHECKING:
BufferType = Union[bytearray, memoryview] BufferType = bytearray | memoryview
class BufferWriter: class BufferWriter:
@ -222,7 +220,7 @@ class BufferWriter:
class BufferReader: class BufferReader:
"""Seekable and readable view into a buffer.""" """Seekable and readable view into a buffer."""
def __init__(self, buffer: Union[bytes, memoryview]) -> None: def __init__(self, buffer: bytes | memoryview) -> None:
if isinstance(buffer, memoryview): if isinstance(buffer, memoryview):
self.buffer = buffer self.buffer = buffer
else: else: