1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-22 06:18: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
if TYPE_CHECKING:
from typing import Tuple
from enum import IntEnum
from apps.common.coininfo import CoinInfo
from trezor.messages import TxInput
@ -128,7 +127,7 @@ def encode_bech32_address(prefix: str, witver: int, script: bytes) -> str:
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)
if witver not in _BECH32_WITVERS:
raise wire.ProcessError("Invalid address witness program")

View File

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

View File

@ -12,7 +12,7 @@ if not utils.BITCOIN_ONLY:
from . import bitcoinlike, decred, zcash
if TYPE_CHECKING:
from typing import Protocol, Union
from typing import Protocol
from trezor.messages import (
SignTx,
@ -29,14 +29,14 @@ if TYPE_CHECKING:
from ..authorization import CoinJoinAuthorization
TxAckType = Union[
TxAckInput,
TxAckOutput,
TxAckPrevMeta,
TxAckPrevInput,
TxAckPrevOutput,
TxAckPrevExtraData,
]
TxAckType = (
TxAckInput
| TxAckOutput
| TxAckPrevMeta
| TxAckPrevInput
| TxAckPrevOutput
| TxAckPrevExtraData
)
class SignerClass(Protocol):
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
if TYPE_CHECKING:
from typing import Union
from trezor import wire
from trezor.messages import (
@ -27,11 +26,11 @@ if TYPE_CHECKING:
CardanoTxAuxiliaryData,
)
CatalystRegistrationPayload = dict[int, Union[bytes, int]]
CatalystRegistrationPayload = dict[int, bytes | int]
SignedCatalystRegistrationPayload = tuple[CatalystRegistrationPayload, bytes]
CatalystRegistrationSignature = dict[int, bytes]
CatalystRegistration = dict[
int, Union[CatalystRegistrationPayload, CatalystRegistrationSignature]
int, CatalystRegistrationPayload | CatalystRegistrationSignature
]
from . import seed

View File

@ -11,7 +11,7 @@ from apps.common.seed import derive_and_store_roots, get_seed
from .helpers import paths
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.keychain import MsgOut, Handler
@ -23,12 +23,12 @@ if TYPE_CHECKING:
CardanoSignTxInit,
)
CardanoMessages = Union[
CardanoGetAddress,
CardanoGetPublicKey,
CardanoGetNativeScriptHash,
CardanoSignTxInit,
]
CardanoMessages = (
CardanoGetAddress
| CardanoGetPublicKey
| CardanoGetNativeScriptHash
| CardanoSignTxInit
)
MsgIn = TypeVar("MsgIn", bound=CardanoMessages)
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
if TYPE_CHECKING:
from typing import Any, Union
from typing import Any
from apps.common.paths import PathSchema
CardanoTxResponseType = Union[CardanoTxItemAck, CardanoTxWitnessResponse]
CardanoTxResponseType = CardanoTxItemAck | CardanoTxWitnessResponse
MINTING_POLICY_ID_LENGTH = 28
MAX_ASSET_NAME_LENGTH = 32

View File

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

View File

@ -3,7 +3,6 @@ from typing import TYPE_CHECKING
from trezor.utils import ensure
if TYPE_CHECKING:
from typing import Union
from trezor.utils import Writer
@ -71,7 +70,7 @@ def write_uint64_be(w: Writer, n: int) -> int:
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)
return len(b)

View File

@ -8,7 +8,7 @@ from apps.common.keychain import get_keychain
from . import CURVE, networks
if TYPE_CHECKING:
from typing import Callable, Iterable, TypeVar, Union
from typing import Callable, Iterable, TypeVar
from trezor.messages import (
EthereumGetAddress,
@ -21,19 +21,16 @@ if TYPE_CHECKING:
from apps.common.keychain import MsgOut, Handler, HandlerWithKeychain
EthereumMessages = Union[
EthereumGetAddress,
EthereumGetPublicKey,
EthereumSignTx,
EthereumSignMessage,
EthereumSignTypedData,
]
EthereumMessages = (
EthereumGetAddress
| EthereumGetPublicKey
| EthereumSignTx
| EthereumSignMessage
| EthereumSignTypedData
)
MsgIn = TypeVar("MsgIn", bound=EthereumMessages)
EthereumSignTxAny = Union[
EthereumSignTx,
EthereumSignTxEIP1559,
]
EthereumSignTxAny = EthereumSignTx | EthereumSignTxEIP1559
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
if TYPE_CHECKING:
from typing import Awaitable, Iterable, Optional
from typing import Awaitable, Iterable
from trezor.wire import Context
@ -185,7 +185,7 @@ async def confirm_typed_value(
value: bytes,
parent_objects: list[str],
field: EthereumFieldType,
array_index: Optional[int] = None,
array_index: int | None = None,
) -> None:
type_name = get_type_name(field)

View File

@ -20,8 +20,6 @@ from .layout import (
)
if TYPE_CHECKING:
from typing import Tuple
from apps.common.keychain import Keychain
from .keychain import EthereumSignTxAny
@ -97,7 +95,7 @@ async def sign_tx(
async def handle_erc20(
ctx: wire.Context, msg: EthereumSignTxAny
) -> Tuple[tokens.TokenInfo | None, bytes, bytes, int]:
) -> tuple[tokens.TokenInfo | None, bytes, bytes, int]:
token = None
address_bytes = recipient = bytes_from_address(msg.to)
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:
length += rlp.length(msg.tx_type)
fields: Tuple[rlp.RLPItem, ...] = (
fields: tuple[rlp.RLPItem, ...] = (
msg.nonce,
msg.gas_price,
msg.gas_limit,

View File

@ -19,8 +19,6 @@ from .layout import (
from .sign_tx import check_common_fields, handle_erc20, send_request_chunk
if TYPE_CHECKING:
from typing import Tuple
from trezor.messages import EthereumSignTxEIP1559
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)
fields: Tuple[rlp.RLPItem, ...] = (
fields: tuple[rlp.RLPItem, ...] = (
msg.chain_id,
msg.nonce,
msg.max_priority_fee,
@ -124,7 +122,7 @@ async def sign_tx_eip1559(
def get_total_length(msg: EthereumSignTxEIP1559, data_total: int) -> int:
length = 0
fields: Tuple[rlp.RLPItem, ...] = (
fields: tuple[rlp.RLPItem, ...] = (
msg.nonce,
msg.gas_limit,
bytes_from_address(msg.to),

View File

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

View File

@ -4,7 +4,6 @@ from typing import TYPE_CHECKING
from trezor.enums import MessageType
if TYPE_CHECKING:
from typing import Union
from trezor import protobuf
from trezor.messages import (
@ -23,21 +22,21 @@ if TYPE_CHECKING:
StellarSetOptionsOp,
)
StellarMessageType = Union[
StellarAccountMergeOp,
StellarAllowTrustOp,
StellarBumpSequenceOp,
StellarChangeTrustOp,
StellarCreateAccountOp,
StellarCreatePassiveSellOfferOp,
StellarManageDataOp,
StellarManageBuyOfferOp,
StellarManageSellOfferOp,
StellarPathPaymentStrictReceiveOp,
StellarPathPaymentStrictSendOp,
StellarPaymentOp,
StellarSetOptionsOp,
]
StellarMessageType = (
StellarAccountMergeOp
| StellarAllowTrustOp
| StellarBumpSequenceOp
| StellarChangeTrustOp
| StellarCreateAccountOp
| StellarCreatePassiveSellOfferOp
| StellarManageDataOp
| StellarManageBuyOfferOp
| StellarManageSellOfferOp
| StellarPathPaymentStrictReceiveOp
| StellarPathPaymentStrictSendOp
| StellarPaymentOp
| StellarSetOptionsOp
)
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
if TYPE_CHECKING:
from typing import Union
from apps.common.keychain import Keychain
from trezor.wire import Context
from trezor.messages import (
@ -249,9 +248,10 @@ def _get_operation_bytes(w: Writer, msg: TezosSignTx) -> None:
def _encode_common(
w: Writer,
operation: Union[
TezosDelegationOp, TezosOriginationOp, TezosTransactionOp, TezosRevealOp
],
operation: TezosDelegationOp
| TezosOriginationOp
| TezosTransactionOp
| TezosRevealOp,
str_operation: str,
) -> None:
operation_tags = {

View File

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

View File

@ -2,7 +2,6 @@ from micropython import const
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Union
from trezor.utils import Writer
# 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
# 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].
RLPList = Union[list[int], list[bytes], list["RLPItem"]]
RLPItem = Union[RLPList, bytes, int]
RLPList = list[int] | list[bytes] | list["RLPItem"]
RLPItem = RLPList | bytes | int
STRING_HEADER_BYTE = const(0x80)

View File

@ -38,9 +38,9 @@ from trezor.crypto import hmac, pbkdf2, random
from trezor.errors import MnemonicError
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]]]]

View File

@ -17,9 +17,9 @@ LINE_WIDTH = ui.WIDTH - TEXT_MARGIN_LEFT
LINE_WIDTH_PAGINATED = LINE_WIDTH - PAGINATION_MARGIN_RIGHT
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
BR = const(-256)

View File

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

View File

@ -6,9 +6,9 @@ from trezor import res, ui
from ...constants import TEXT_HEADER_HEIGHT, TEXT_LINE_HEIGHT
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_OFFSET_X = const(24)

View File

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

View File

@ -8,9 +8,9 @@ from trezorui2 import layout_new_confirm_action
from .common import interact
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(

View File

@ -30,20 +30,18 @@ if TYPE_CHECKING:
Any,
Iterator,
Protocol,
Union,
TypeVar,
Sequence,
Set,
)
from trezor.protobuf import MessageType
def unimport_begin() -> Set[str]:
def unimport_begin() -> set[str]:
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
# MICROPY_LOADED_MODULES_DICT_SIZE, so that the sys.modules dict is never
# reallocated at run-time
@ -72,7 +70,7 @@ def unimport_end(mods: Set[str], collect: bool = True) -> None:
class unimport:
def __init__(self) -> None:
self.mods: Set[str] | None = None
self.mods: set[str] | None = None
def __enter__(self) -> None:
self.mods = unimport_begin()
@ -186,7 +184,7 @@ class HashWriter:
if TYPE_CHECKING:
BufferType = Union[bytearray, memoryview]
BufferType = bytearray | memoryview
class BufferWriter:
@ -222,7 +220,7 @@ class BufferWriter:
class BufferReader:
"""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):
self.buffer = buffer
else: