style: use PEP 604 syntax where possible
What changed, and why it matters
This is a pure code-style cleanup. It replaces older Python type annotations like `Optional[X]` and `Union[X, Y]` with the newer `X | None` and `X | Y` syntax, and adds `from __future__ import annotations` where needed so the new syntax works on Python 3.9. No behavior of the code changes, and there is no security relevance.
No security action needed. Treat as a normal style/refactoring commit.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The commit applies PEP 604 union syntax across the python/src/trezorlib package, tests, tools, docs, and a Mako template. It removes Optional and Union imports, rewrites annotations, and enables postponed evaluation of annotations via from __future__ import annotations to maintain Python 3.9 compatibility. The pyproject.toml change removes a per-file ruff ignore so the new syntax is linted in /python as well as /core. No runtime logic, parsing, cryptography, or device communication code is altered.
Changed components
python/src/trezorlib type annotationstests type annotationspython/tools type annotationspyproject.toml ruff lint configurationdocumentation code examplesInspect captured patch +2007 / −1985
### common/protob/pb2py
@@ -12,7 +12,6 @@ import sys
import tempfile
from dataclasses import dataclass
from pathlib import Path
-from typing import Optional
import click
import construct as c
@@ -234,7 +233,7 @@ class ProtoField:
@dataclass
class ProtoMessage:
name: str
- wire_type: Optional[int]
+ wire_type: int | None
orig: object
extensions: dict
### core/embed/rust/librust_qstr.h.mako
@@ -10,7 +10,6 @@ import json
import subprocess
import sys
from pathlib import Path
-from typing import Union, Set
RUST_SRC = THIS_FILE.parent / "src"
### docs/core/misc/codestyle.md
@@ -43,10 +43,10 @@ at top level. The style for doing that are as follows:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
- from typing import Any, TypeVar, Union
+ from typing import Any, TypeVar
from trezor.messages import SomeMessage
- TypeAlias = Union[int, str]
+ TypeAlias = int | str
T = TypeVar("T")
```
* If the module _only_ needs items from `typing`, you should not create a
### docs/developers/hello_world_in_core.md
@@ -145,7 +145,7 @@ We will create the `python/src/trezorlib/hello_world.py` file and fill it with c
```python
from __future__ import annotations
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
from . import messages
@@ -156,7 +156,7 @@ if TYPE_CHECKING:
def say_hello(
session: "Session",
name: str,
- amount: Optional[int],
+ amount: int | None,
show_display: bool,
) -> str:
return session.call(
@@ -177,7 +177,7 @@ This function is then called from the `CLI` function, which we will define in `p
```python
from __future__ import annotations
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
import click
@@ -201,7 +201,7 @@ def cli() -> None:
)
@with_session
def say_hello(
- session: "Session", name: str, amount: Optional[int], show_display: bool
+ session: "Session", name: str, amount: int | None, show_display: bool
) -> str:
"""Simply say hello to the supplied name."""
return hello_world.say_hello(session, name, amount, show_display=show_display)
### pyproject.toml
@@ -109,7 +109,7 @@ select = [
"UP006", # non-pep585-annotation: typing.Tuple -> tuple, typing.Type -> type, ...
"UP035", # deprecated-import: typing.Sequence -> collections.abc.Sequence, ...
- # PEP 604 (used in /core only)
+ # PEP 604 (in /python only where `from __future__ import annotations` is present, see target-version)
"UP007", # non-pep604-annotation-union: Union[int, str] -> int | str
"UP045", # non-pep604-annotation-optional: Optional[str] -> str | None
]
@@ -131,7 +131,3 @@ extra-standard-library = [
# `python` is needed for `from python.src.storage import ...` in storage tests
known-first-party = ["trezorlib", "apps", "coin_info", "marketcap", "ui_tests", "python"]
known-third-party = ["trezor", "storage"]
-
-[tool.ruff.lint.per-file-ignores]
-# PEP 604 syntax needs Python 3.10 - cannot be enforced e.g. in /python as it still supports Python 3.9.
-"!core/**/*.py" = ["UP007", "UP045"]
### python/src/trezorlib/_internal/emulator.py
@@ -26,7 +26,7 @@
import time
from collections.abc import Iterable, Sequence
from pathlib import Path
-from typing import Any, Optional, TextIO, Union, cast
+from typing import Any, TextIO, cast
from ..debuglink import DebugLinkNotFound, TrezorTestContext
from ..transport import Transport
@@ -72,7 +72,7 @@ def __init__(
configfile_output or self.profile_dir / "tropic_model_config_output.yml"
)
self.logfile = logfile or self.profile_dir / "trezor-tropic-model.log"
- self.process: Optional[subprocess.Popen] = None
+ self.process: subprocess.Popen | None = None
def start(self) -> None:
self.process = self._launch_process()
@@ -167,8 +167,8 @@ def __init__(
executable: Path,
profile_dir: str,
*,
- logfile: Union[TextIO, str, Path, None] = None,
- storage: Optional[bytes] = None,
+ logfile: TextIO | str | Path | None = None,
+ storage: bytes | None = None,
headless: bool = False,
debug: bool = True,
auto_interact: bool = True,
@@ -249,7 +249,7 @@ def _wait_until_ready(self, timeout: float = EMULATOR_WAIT_TIME) -> None:
LOG.info(f"Emulator ready after {time.monotonic() - start:.3f} seconds")
- def wait(self, timeout: Optional[float] = None) -> int:
+ def wait(self, timeout: float | None = None) -> int:
assert self.process is not None, "Emulator not started"
ret = self.process.wait(timeout=timeout)
_RUNNING_PIDS.remove(self.process)
@@ -278,8 +278,8 @@ def _launch_process(self) -> subprocess.Popen:
def start(
self,
- transport: Optional[UdpTransport] = None,
- debug_transport: Optional[Transport] = None,
+ transport: UdpTransport | None = None,
+ debug_transport: Transport | None = None,
) -> None:
if self.process:
if self.process.poll() is not None:
@@ -367,14 +367,14 @@ class CoreEmulator(Emulator):
def __init__(
self,
*args: Any,
- tropic_model_port: Optional[int] = None,
- port: Optional[int] = None,
+ tropic_model_port: int | None = None,
+ port: int | None = None,
main_args: Sequence[str] = ("-m", "main"),
- workdir: Optional[Path] = None,
- sdcard: Optional[bytes] = None,
+ workdir: Path | None = None,
+ sdcard: bytes | None = None,
disable_animation: bool = True,
heap_size: str = "20M",
- display_scale: Optional[float] = None,
+ display_scale: float | None = None,
**kwargs: Any,
) -> None:
super().__init__(*args, **kwargs)
### python/src/trezorlib/_internal/firmware_headers.py
@@ -90,11 +90,11 @@ def chunkify(data: bytes) -> str:
def format_container(
- pb: t.Union[c.Container, Struct, dict],
+ pb: c.Container | Struct | dict,
indent: int = 0,
sep: str = " " * 4,
- truncate_after: t.Optional[int] = 64,
- truncate_to: t.Optional[int] = 32,
+ truncate_after: int | None = 64,
+ truncate_to: int | None = 32,
) -> str:
def mostly_printable(bytes: bytes | bytearray) -> bool:
@@ -305,7 +305,7 @@ def insert_signature(self, slot: int, key_index: int, signature: bytes) -> None:
class CosiSignatureHeaderProto(Protocol):
- hw_model: t.Union[fw_models.Model, bytes]
+ hw_model: fw_models.Model | bytes
signature: bytes
sigmask: int
### python/src/trezorlib/_modeldata/__init__.py
@@ -41,9 +41,11 @@
``model.toml`` (or a parallel metadata file) to feed the generator.
"""
+from __future__ import annotations
+
from dataclasses import dataclass, field
from enum import Enum
-from typing import Callable, Optional
+from typing import Callable
def keys(*hexes: str) -> tuple[bytes, ...]:
@@ -97,7 +99,7 @@ class HashParams:
hash_function: Callable
chunk_size: int
- padding_byte: Optional[bytes]
+ padding_byte: bytes | None
@dataclass(frozen=True)
@@ -116,4 +118,4 @@ class ModelData:
# --- firmware verification ---
prod_keys: KeySet = field(default_factory=KeySet)
dev_keys: KeySet = field(default_factory=KeySet)
- hash_params: Optional[HashParams] = None
+ hash_params: HashParams | None = None
### python/src/trezorlib/_modeldata/registry.py
@@ -19,7 +19,7 @@
Once the firmware-side generator exists, the import list below is the only
thing it needs to emit/maintain (one line per ``core/embed/models/<NAME>``)."""
-from typing import Optional
+from __future__ import annotations
from . import D001, D002, D003, T1B1, T2B1, T2T1, T3B1, T3T1, T3T2, T3W1, ModelData
@@ -39,5 +39,5 @@
BY_INTERNAL_NAME: dict[str, ModelData] = {m.internal_name: m for m in ALL}
-def by_internal_name(internal_name: str) -> Optional[ModelData]:
+def by_internal_name(internal_name: str) -> ModelData | None:
return BY_INTERNAL_NAME.get(internal_name)
### python/src/trezorlib/_proto_messages.mako
@@ -2,9 +2,10 @@
# fmt: off
# isort:skip_file
+from __future__ import annotations
+
from collections.abc import Sequence
from enum import IntEnum
-from typing import Optional
from . import protobuf
% for enum in enums:
@@ -40,17 +41,17 @@ class ${message.name}(protobuf.MessageType):
self,
*,
% for field in required_fields:
- ${field.name}: "${field.python_type}",
+ ${field.name}: ${field.python_type},
% endfor
% for field in repeated_fields:
- ${field.name}: Optional[Sequence["${field.python_type}"]] = None,
+ ${field.name}: Sequence[${field.python_type}] | None = None,
% endfor
% for field in optional_fields:
- ${field.name}: Optional["${field.python_type}"] = ${field.default_value_repr},
+ ${field.name}: ${field.python_type} | None = ${field.default_value_repr},
% endfor
) -> None:
% for field in repeated_fields:
- self.${field.name}: Sequence["${field.python_type}"] = ${field.name} if ${field.name} is not None else []
+ self.${field.name}: Sequence[${field.python_type}] = ${field.name} if ${field.name} is not None else []
% endfor
% for field in required_fields + optional_fields:
self.${field.name} = ${field.name}
### python/src/trezorlib/btc.py
@@ -19,7 +19,7 @@
from collections.abc import Sequence
from copy import copy
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, AnyStr, Optional
+from typing import TYPE_CHECKING, Any, AnyStr
# TypedDict is not available in typing for python < 3.8
from typing_extensions import Protocol, TypedDict
@@ -108,13 +108,13 @@ def make_bin_output(vout: "Vout") -> messages.TxOutputBinType:
def get_public_node(
session: "Session",
n: "Address",
- ecdsa_curve_name: Optional[str] = None,
+ ecdsa_curve_name: str | None = None,
show_display: bool = False,
- coin_name: Optional[str] = None,
+ coin_name: str | None = None,
script_type: messages.InputScriptType = messages.InputScriptType.SPENDADDRESS,
ignore_xpub_magic: bool = False,
- unlock_path: Optional[list[int]] = None,
- unlock_path_mac: Optional[bytes] = None,
+ unlock_path: list[int] | None = None,
+ unlock_path_mac: bytes | None = None,
) -> messages.PublicKey:
if unlock_path:
session.call(
@@ -145,11 +145,11 @@ def get_authenticated_address(
coin_name: str,
n: "Address",
show_display: bool = False,
- multisig: Optional[messages.MultisigRedeemScriptType] = None,
+ multisig: messages.MultisigRedeemScriptType | None = None,
script_type: messages.InputScriptType = messages.InputScriptType.SPENDADDRESS,
ignore_xpub_magic: bool = False,
- unlock_path: Optional[list[int]] = None,
- unlock_path_mac: Optional[bytes] = None,
+ unlock_path: list[int] | None = None,
+ unlock_path_mac: bytes | None = None,
chunkify: bool = False,
) -> messages.Address:
if unlock_path:
@@ -177,7 +177,7 @@ def get_ownership_id(
session: "Session",
coin_name: str,
n: "Address",
- multisig: Optional[messages.MultisigRedeemScriptType] = None,
+ multisig: messages.MultisigRedeemScriptType | None = None,
script_type: messages.InputScriptType = messages.InputScriptType.SPENDADDRESS,
) -> bytes:
return session.call(
@@ -196,11 +196,11 @@ def get_ownership_proof(
session: "Session",
coin_name: str,
n: "Address",
- multisig: Optional[messages.MultisigRedeemScriptType] = None,
+ multisig: messages.MultisigRedeemScriptType | None = None,
script_type: messages.InputScriptType = messages.InputScriptType.SPENDADDRESS,
user_confirmation: bool = False,
- ownership_ids: Optional[list[bytes]] = None,
- commitment_data: Optional[bytes] = None,
+ ownership_ids: list[bytes] | None = None,
+ commitment_data: bytes | None = None,
preauthorized: bool = False,
) -> tuple[bytes, bytes]:
if preauthorized:
@@ -275,13 +275,13 @@ def sign_tx(
coin_name: str,
inputs: Sequence[messages.TxInputType],
outputs: Sequence[messages.TxOutputType],
- prev_txes: Optional["TxCacheType"] = None,
+ prev_txes: TxCacheType | None = None,
payment_reqs: Sequence[messages.PaymentRequest] = (),
preauthorized: bool = False,
- unlock_path: Optional[list[int]] = None,
- unlock_path_mac: Optional[bytes] = None,
+ unlock_path: list[int] | None = None,
+ unlock_path_mac: bytes | None = None,
**kwargs: Any,
-) -> tuple[Sequence[Optional[bytes]], bytes]:
+) -> tuple[Sequence[bytes | None], bytes]:
"""Sign a Bitcoin-like transaction.
Returns a list of signatures (one for each provided input) and the
@@ -318,7 +318,7 @@ def sign_tx(
res = session.call(signtx, expect=messages.TxRequest)
# Prepare structure for signatures
- signatures: list[Optional[bytes]] = [None] * len(inputs)
+ signatures: list[bytes | None] = [None] * len(inputs)
serialized_tx = b""
def copy_tx_meta(tx: messages.TransactionType) -> messages.TransactionType:
### python/src/trezorlib/cardano.py
@@ -14,6 +14,8 @@
# 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>.
+from __future__ import annotations
+
from collections.abc import Iterable, Iterator, Sequence
from ipaddress import ip_address
from itertools import chain
@@ -100,24 +102,24 @@
)
-def parse_optional_bytes(value: Optional[str]) -> Optional[bytes]:
+def parse_optional_bytes(value: str | None) -> bytes | None:
return bytes.fromhex(value) if value is not None else None
-def parse_optional_int(value: Optional[str]) -> Optional[int]:
+def parse_optional_int(value: str | None) -> int | None:
return int(value) if value is not None else None
def create_address_parameters(
address_type: m.CardanoAddressType,
address_n: list[int],
- address_n_staking: Optional[list[int]] = None,
- staking_key_hash: Optional[bytes] = None,
- block_index: Optional[int] = None,
- tx_index: Optional[int] = None,
- certificate_index: Optional[int] = None,
- script_payment_hash: Optional[bytes] = None,
- script_staking_hash: Optional[bytes] = None,
+ address_n_staking: list[int] | None = None,
+ staking_key_hash: bytes | None = None,
+ block_index: int | None = None,
+ tx_index: int | None = None,
+ certificate_index: int | None = None,
+ script_payment_hash: bytes | None = None,
+ script_staking_hash: bytes | None = None,
) -> m.CardanoAddressParametersType:
certificate_pointer = None
@@ -141,9 +143,9 @@ def create_address_parameters(
def _create_certificate_pointer(
- block_index: Optional[int],
- tx_index: Optional[int],
- certificate_index: Optional[int],
+ block_index: int | None,
+ tx_index: int | None,
+ certificate_index: int | None,
) -> m.CardanoBlockchainPointerType:
if block_index is None or tx_index is None or certificate_index is None:
raise ValueError("Invalid pointer parameters")
@@ -316,8 +318,8 @@ def _parse_address_parameters(
def parse_optional_address_parameters(
- address_parameters: Optional[dict],
-) -> Optional[m.CardanoAddressParametersType]:
+ address_parameters: dict | None,
+) -> m.CardanoAddressParametersType | None:
if address_parameters is None:
return None
@@ -332,7 +334,7 @@ def parse_optional_address_parameters(
def _parse_chunkable_data(
- data: Optional[bytes], chunk_type: type[Chunk]
+ data: bytes | None, chunk_type: type[Chunk]
) -> tuple[int, list[Chunk]]:
if data is None:
return 0, []
@@ -452,7 +454,7 @@ def parse_certificate(certificate: dict) -> CertificateWithPoolOwnersAndRelays:
):
raise CERTIFICATE_MISSING_FIELDS_ERROR
- pool_metadata: Optional[m.CardanoPoolMetadataType]
+ pool_metadata: m.CardanoPoolMetadataType | None
if pool_parameters.get("metadata") is not None:
pool_metadata = m.CardanoPoolMetadataType(
url=pool_parameters["metadata"]["url"],
@@ -518,7 +520,7 @@ def parse_certificate(certificate: dict) -> CertificateWithPoolOwnersAndRelays:
def _parse_credential(
obj: dict, error: ValueError
-) -> tuple[list[int], Optional[bytes], Optional[bytes]]:
+) -> tuple[list[int], bytes | None, bytes | None]:
if not any(k in obj for k in ("path", "script_hash", "key_hash")):
raise error
@@ -597,8 +599,8 @@ def parse_withdrawal(withdrawal: dict) -> m.CardanoTxWithdrawal:
def parse_auxiliary_data(
- auxiliary_data: Optional[dict],
-) -> Optional[m.CardanoTxAuxiliaryData]:
+ auxiliary_data: dict | None,
+) -> m.CardanoTxAuxiliaryData | None:
if auxiliary_data is None:
return None
@@ -665,7 +667,7 @@ def parse_mint(mint: Iterable[dict]) -> list[AssetGroupWithTokens]:
return _parse_token_bundle(mint, is_mint=True)
-def parse_script_data_hash(script_data_hash: Optional[str]) -> Optional[bytes]:
+def parse_script_data_hash(script_data_hash: str | None) -> bytes | None:
return parse_optional_bytes(script_data_hash)
@@ -892,26 +894,26 @@ def sign_tx(
inputs: list[InputWithPath],
outputs: list[OutputWithData],
fee: int,
- ttl: Optional[int],
- validity_interval_start: Optional[int],
+ ttl: int | None,
+ validity_interval_start: int | None,
certificates: Sequence[CertificateWithPoolOwnersAndRelays] = (),
withdrawals: Sequence[m.CardanoTxWithdrawal] = (),
protocol_magic: int = PROTOCOL_MAGICS["mainnet"],
network_id: int = NETWORK_IDS["mainnet"],
- auxiliary_data: Optional[m.CardanoTxAuxiliaryData] = None,
+ auxiliary_data: m.CardanoTxAuxiliaryData | None = None,
mint: Sequence[AssetGroupWithTokens] = (),
- script_data_hash: Optional[bytes] = None,
+ script_data_hash: bytes | None = None,
collateral_inputs: Sequence[CollateralInputWithPath] = (),
required_signers: Sequence[m.CardanoTxRequiredSigner] = (),
- collateral_return: Optional[OutputWithData] = None,
- total_collateral: Optional[int] = None,
+ collateral_return: OutputWithData | None = None,
+ total_collateral: int | None = None,
reference_inputs: Sequence[m.CardanoTxReferenceInput] = (),
additional_witness_requests: Sequence[Path] = (),
derivation_type: m.CardanoDerivationType = m.CardanoDerivationType.ICARUS,
include_network_id: bool = False,
chunkify: bool = False,
tag_cbor_sets: bool = False,
- payment_req: Optional[m.PaymentRequest] = None,
+ payment_req: m.PaymentRequest | None = None,
) -> dict[str, Any]:
witness_requests = _get_witness_requests(
inputs,
@@ -1017,10 +1019,10 @@ def sign_message(
signing_path: Path,
payload: bytes,
prefer_hex_display: bool,
- address_parameters: Optional[m.CardanoAddressParametersType] = None,
+ address_parameters: m.CardanoAddressParametersType | None = None,
derivation_type: m.CardanoDerivationType = m.CardanoDerivationType.ICARUS,
- protocol_magic: Optional[int] = None,
- network_id: Optional[int] = None,
+ protocol_magic: int | None = None,
+ network_id: int | None = None,
) -> m.CardanoMessageSignature:
response = session.call(
m.CardanoSignMessageInit(
### python/src/trezorlib/cli/benchmark.py
@@ -14,8 +14,10 @@
# 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>.
+from __future__ import annotations
+
from fnmatch import fnmatch
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
import click
@@ -26,7 +28,7 @@
from ..client import Session
-def list_names_patern(session: "Session", pattern: Optional[str] = None) -> list[str]:
+def list_names_patern(session: "Session", pattern: str | None = None) -> list[str]:
names = list(benchmark.list_names(session).names)
if pattern is None:
return names
@@ -41,7 +43,7 @@ def cli() -> None:
@cli.command()
@click.argument("pattern", required=False)
@with_session(passphrase=False)
-def list_names(session: "Session", pattern: Optional[str] = None) -> None:
+def list_names(session: "Session", pattern: str | None = None) -> None:
"""List names of all supported benchmarks"""
names = list_names_patern(session, pattern)
if len(names) == 0:
@@ -54,7 +56,7 @@ def list_names(session: "Session", pattern: Optional[str] = None) -> None:
@cli.command()
@click.argument("pattern", required=False)
@with_session(passphrase=False)
-def run(session: "Session", pattern: Optional[str]) -> None:
+def run(session: "Session", pattern: str | None) -> None:
"""Run benchmark"""
names = list_names_patern(session, pattern)
if len(names) == 0:
### python/src/trezorlib/cli/btc.py
@@ -18,7 +18,7 @@
import base64
import json
-from typing import TYPE_CHECKING, Optional, TextIO
+from typing import TYPE_CHECKING, TextIO
import click
import construct as c
@@ -139,7 +139,7 @@ def guess_script_type_from_path(address_n: list[int]) -> messages.InputScriptTyp
return messages.InputScriptType.SPENDADDRESS
-def get_unlock_path(address_n: list[int]) -> Optional[list[int]]:
+def get_unlock_path(address_n: list[int]) -> list[int] | None:
if address_n and address_n[0] == tools.H_(10025):
return address_n[:1]
return None
@@ -213,7 +213,7 @@ def get_address(
if script_type is None:
script_type = guess_script_type_from_path(address_n)
- multisig: Optional[messages.MultisigRedeemScriptType]
+ multisig: messages.MultisigRedeemScriptType | None
if multisig_xpub:
if multisig_threshold is None:
raise click.ClickException("Please specify signature threshold")
@@ -260,8 +260,8 @@ def get_public_node(
session: "Session",
coin: str,
address: str,
- curve: Optional[str],
- script_type: Optional[messages.InputScriptType],
+ curve: str | None,
+ script_type: messages.InputScriptType | None,
show_display: bool,
ignore_xpub_magic: bool,
) -> dict:
@@ -298,10 +298,10 @@ def _append_descriptor_checksum(desc: str) -> str:
def _get_descriptor(
session: "Session",
- coin: Optional[str],
+ coin: str | None,
account: int,
- purpose: Optional[int],
- script_type: Optional[messages.InputScriptType],
+ purpose: int | None,
+ script_type: messages.InputScriptType | None,
show_display: bool,
) -> str:
if purpose is None:
@@ -371,10 +371,10 @@ def _get_descriptor(
@with_session
def get_descriptor(
session: "Session",
- coin: Optional[str],
+ coin: str | None,
account: int,
- account_type: Optional[int],
- script_type: Optional[messages.InputScriptType],
+ account_type: int | None,
+ script_type: messages.InputScriptType | None,
show_display: bool,
) -> str:
"""Get descriptor of given account."""
@@ -458,7 +458,7 @@ def sign_message(
coin: str,
address: str,
message: str,
- script_type: Optional[messages.InputScriptType],
+ script_type: messages.InputScriptType | None,
electrum_compat: bool,
chunkify: bool,
) -> dict[str, str]:
### python/src/trezorlib/cli/cardano.py
@@ -14,8 +14,10 @@
# 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>.
+from __future__ import annotations
+
import json
-from typing import TYPE_CHECKING, Any, Optional, TextIO
+from typing import TYPE_CHECKING, Any, TextIO
import click
@@ -214,12 +216,12 @@ def get_address(
address: str,
address_type: messages.CardanoAddressType,
staking_address: str,
- staking_key_hash: Optional[str],
- block_index: Optional[int],
- tx_index: Optional[int],
- certificate_index: Optional[int],
- script_payment_hash: Optional[str],
- script_staking_hash: Optional[str],
+ staking_key_hash: str | None,
+ block_index: int | None,
+ tx_index: int | None,
+ certificate_index: int | None,
+ script_payment_hash: str | None,
+ script_staking_hash: str | None,
protocol_magic: int,
network_id: int,
show_display: bool,
### python/src/trezorlib/cli/ethereum.py
@@ -14,13 +14,15 @@
# 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>.
+from __future__ import annotations
+
import json
import re
import sys
import tarfile
from decimal import Decimal
from pathlib import Path
-from typing import TYPE_CHECKING, Any, AnyStr, NoReturn, Optional, TextIO, cast
+from typing import TYPE_CHECKING, Any, AnyStr, NoReturn, TextIO, cast
import click
@@ -62,7 +64,7 @@
# fmt: on
# So that we can import the web3 library only when really used and reuse the instance
-_WEB3_INSTANCE: Optional["web3.Web3"] = None
+_WEB3_INSTANCE: web3.Web3 | None = None
def _print_eth_dependencies_and_die() -> NoReturn:
@@ -86,9 +88,7 @@ def _get_web3() -> "web3.Web3":
return _WEB3_INSTANCE
-def _amount_to_int(
- ctx: click.Context, param: Any, value: Optional[str]
-) -> Optional[int]:
+def _amount_to_int(ctx: click.Context, param: Any, value: str | None) -> int | None:
if value is None:
return None
if value.isdigit():
@@ -174,29 +174,29 @@ def _hex_or_file(data: str) -> bytes:
class CliSource(definitions.Source):
- network: Optional[bytes] = None
- token: Optional[bytes] = None
- display_format: Optional[bytes] = None
+ network: bytes | None = None
+ token: bytes | None = None
+ display_format: bytes | None = None
delegate: definitions.Source = definitions.NullSource()
- def get_eth_network(self, chain_id: int) -> Optional[bytes]:
+ def get_eth_network(self, chain_id: int) -> bytes | None:
if self.network is not None:
return self.network
return self.delegate.get_eth_network(chain_id)
- def get_eth_network_by_slip44(self, slip44: int) -> Optional[bytes]:
+ def get_eth_network_by_slip44(self, slip44: int) -> bytes | None:
if self.network is not None:
return self.network
return self.delegate.get_eth_network_by_slip44(slip44)
- def get_eth_token(self, chain_id: int, address: Any) -> Optional[bytes]:
+ def get_eth_token(self, chain_id: int, address: Any) -> bytes | None:
if self.token is not None:
return self.token
return self.delegate.get_eth_token(chain_id, address)
def get_eth_display_format(
self, chain_id: int, address: AnyStr, func_sig: bytes
- ) -> Optional[bytes]:
+ ) -> bytes | None:
if self.display_format is not None:
return self.display_format
return self.delegate.get_eth_display_format(chain_id, address, func_sig)
@@ -205,7 +205,7 @@ def get_eth_display_format(
DEFINITIONS_SOURCE = CliSource()
-def _network_def_from_address_n(address_n: tools.Address) -> Optional[bytes]:
+def _network_def_from_address_n(address_n: tools.Address) -> bytes | None:
"""Get network definition bytes based on address_n.
Tries to extract the slip44 identifier and lookup the network definition.
@@ -240,11 +240,11 @@ def _network_def_from_address_n(address_n: tools.Address) -> Optional[bytes]:
"--display-format", help="ERC-7730 clear-signing contract descriptor blob."
)
def cli(
- defs: Optional[str],
- auto_definitions: Optional[bool],
- network: Optional[str],
- token: Optional[str],
- display_format: Optional[str],
+ defs: str | None,
+ auto_definitions: bool | None,
+ network: str | None,
+ token: str | None,
+ display_format: str | None,
) -> None:
"""Ethereum commands.
@@ -376,18 +376,18 @@ def sign_tx(
chain_id: int,
address: str,
amount: int,
- gas_limit: Optional[int],
- gas_price: Optional[int],
- nonce: Optional[int],
- data: Optional[str],
+ gas_limit: int | None,
+ gas_price: int | None,
+ nonce: int | None,
+ data: str | None,
publish: bool,
to_address: str,
- tx_type: Optional[int],
- token: Optional[str],
- max_gas_fee: Optional[int],
- max_priority_fee: Optional[int],
+ tx_type: int | None,
+ token: str | None,
+ max_gas_fee: int | None,
+ max_priority_fee: int | None,
access_list: list[EthereumAccessList],
- eip2718_type: Optional[int],
+ eip2718_type: int | None,
chunkify: bool,
) -> str:
"""Sign (and optionally publish) Ethereum transaction.
### python/src/trezorlib/cli/evolu.py
@@ -16,7 +16,7 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
import click
@@ -83,8 +83,8 @@ def sign_registration_request(
@with_session
def get_delegated_identity_key(
session: Session,
- credential: Optional[str] = None,
- rotation_index: Optional[int] = None,
+ credential: str | None = None,
+ rotation_index: int | None = None,
rotate: bool = False,
) -> dict[str, str | int | None]:
"""
@@ -113,7 +113,7 @@ def get_delegated_identity_key(
@with_session
def index_management(
session: Session,
- rotation_index: Optional[int] = None,
+ rotation_index: int | None = None,
) -> str:
"""
Read the rotation index for the delegated identity key.
### python/src/trezorlib/cli/firmware.py
@@ -14,11 +14,13 @@
# 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>.
+from __future__ import annotations
+
import os
import sys
import time
from collections.abc import Iterable
-from typing import TYPE_CHECKING, Any, BinaryIO, Optional, Union
+from typing import TYPE_CHECKING, Any, BinaryIO
from urllib.parse import urlparse
import click
@@ -70,7 +72,7 @@ def _get_file_name_from_url(url: str) -> str:
return os.path.basename(full_path)
-def _print_firmware_model(hw_model: Union[bytes, fw_models.Model]) -> None:
+def _print_firmware_model(hw_model: bytes | fw_models.Model) -> None:
try:
model_name = fw_models.Model.from_hw_model(hw_model).name
click.echo(f"{model_name} firmware image.")
@@ -150,7 +152,7 @@ def validate_signatures(
def validate_fingerprint(
fw: "firmware.FirmwareType",
- expected_fingerprint: Optional[str] = None,
+ expected_fingerprint: str | None = None,
) -> None:
"""Determine and validate the firmware fingerprint.
@@ -267,8 +269,8 @@ def _should_use_bitcoin_only(features: messages.Features) -> bool:
def find_best_firmware_version(
client: "TrezorClient",
- version: Optional[str],
- bitcoin_only: Optional[bool],
+ version: str | None,
+ bitcoin_only: bool | None,
) -> tuple[str, str]:
"""Get the url from which to download the firmware and its expected fingerprint.
@@ -372,9 +374,9 @@ def download_firmware_data(url: str) -> bytes:
def validate_firmware(
firmware_data: bytes,
- fingerprint: Optional[str] = None,
- model: Optional[TrezorModel] = None,
- bootloader_onev2: Optional[bool] = None,
+ fingerprint: str | None = None,
+ model: TrezorModel | None = None,
+ bootloader_onev2: bool | None = None,
verify_only: bool = False,
) -> None:
"""Validate the firmware through multiple tests.
@@ -567,7 +569,7 @@ def verify(
obj: "TrezorConnection",
filename: BinaryIO,
check_device: bool,
- fingerprint: Optional[str],
+ fingerprint: str | None,
) -> None:
"""Verify the integrity of the firmware data stored in a file.
@@ -577,8 +579,8 @@ def verify(
In case of validation failure exits with the appropriate exit code.
"""
# Deciding if to take the device into account
- bootloader_onev2: Optional[bool]
- model: Optional[TrezorModel]
+ bootloader_onev2: bool | None
+ model: TrezorModel | None
if check_device:
with obj.client_context() as client:
bootloader_onev2 = _is_bootloader_onev2(client)
@@ -609,12 +611,12 @@ def verify(
# fmt: on
def download(
obj: "TrezorConnection",
- output: Optional[BinaryIO],
- model: Optional[TrezorModel],
- version: Optional[str],
+ output: BinaryIO | None,
+ model: TrezorModel | None,
+ version: str | None,
skip_check: bool,
- fingerprint: Optional[str],
- bitcoin_only: Optional[bool],
+ fingerprint: str | None,
+ bitcoin_only: bool | None,
) -> None:
"""Download and save the firmware image.
@@ -670,14 +672,14 @@ def download(
@click.pass_obj
def update(
obj: "TrezorConnection",
- filename: Optional[BinaryIO],
- url: Optional[str],
- version: Optional[str],
+ filename: BinaryIO | None,
+ url: str | None,
+ version: str | None,
skip_check: bool,
- fingerprint: Optional[str],
+ fingerprint: str | None,
raw: bool,
dry_run: bool,
- bitcoin_only: Optional[bool],
+ bitcoin_only: bool | None,
) -> None:
"""Upload new firmware to device.
@@ -752,7 +754,7 @@ def update(
@cli.command()
@click.argument("hex_challenge", required=False)
@with_session(seedless=True)
-def get_hash(session: "Session", hex_challenge: Optional[str]) -> str:
+def get_hash(session: "Session", hex_challenge: str | None) -> str:
"""Get a hash of the installed firmware combined with the optional challenge."""
challenge = bytes.fromhex(hex_challenge) if hex_challenge else None
return firmware.get_hash(session, challenge).hex()
### python/src/trezorlib/cli/nem.py
@@ -14,8 +14,10 @@
# 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>.
+from __future__ import annotations
+
import json
-from typing import TYPE_CHECKING, Optional, TextIO
+from typing import TYPE_CHECKING, TextIO
import click
import requests
@@ -63,7 +65,7 @@ def sign_tx(
session: "Session",
address: str,
file: TextIO,
- broadcast: Optional[str],
+ broadcast: str | None,
chunkify: bool,
) -> dict:
"""Sign (and optionally broadcast) NEM transaction.
### python/src/trezorlib/cli/settings.py
@@ -18,7 +18,7 @@
import io
from pathlib import Path
-from typing import TYPE_CHECKING, Optional, cast
+from typing import TYPE_CHECKING, cast
import click
import requests
@@ -167,7 +167,7 @@ def image_to_jpeg(filename: Path, width: int, height: int, quality: int = 90) ->
return filename.read_bytes()
-def _should_remove(enable: Optional[bool], remove: bool) -> bool:
+def _should_remove(enable: bool | None, remove: bool) -> bool:
"""Helper to decide whether to remove something or not.
Needed for backwards compatibility purposes, so we can support
@@ -191,7 +191,7 @@ def cli() -> None:
@click.option("-r", "--remove", is_flag=True, hidden=True)
@click.argument("enable", type=ChoiceType({"on": True, "off": False}), required=False)
@with_session(seedless=True)
-def pin(session: "Session", enable: Optional[bool], remove: bool) -> None:
+def pin(session: "Session", enable: bool | None, remove: bool) -> None:
"""Set, change or remove PIN."""
# Remove argument is there for backwards compatibility
device.change_pin(session, remove=_should_remove(enable, remove))
@@ -201,7 +201,7 @@ def pin(session: "Session", enable: Optional[bool], remove: bool) -> None:
@click.option("-r", "--remove", is_flag=True, hidden=True)
@click.argument("enable", type=ChoiceType({"on": True, "off": False}), required=False)
@with_session(seedless=True)
-def wipe_code(session: "Session", enable: Optional[bool], remove: bool) -> None:
+def wipe_code(session: "Session", enable: bool | None, remove: bool) -> None:
"""Set or remove the wipe code.
The wipe code functions as a "self-destruct PIN". If the wipe code is ever
@@ -435,7 +435,7 @@ def passphrase_main() -> None:
@passphrase.command(name="on")
@click.option("-f/-F", "--force-on-device/--no-force-on-device", default=None)
@with_session(seedless=True)
-def passphrase_on(session: "Session", force_on_device: Optional[bool]) -> None:
+def passphrase_on(session: "Session", force_on_device: bool | None) -> None:
"""Enable passphrase."""
if session.features.passphrase_protection is not True:
use_passphrase = True
### python/src/trezorlib/cli/solana.py
@@ -18,7 +18,7 @@
import json
from pathlib import Path
-from typing import TYPE_CHECKING, Optional, TextIO
+from typing import TYPE_CHECKING, TextIO
import click
@@ -90,7 +90,7 @@ def sign_tx(
session: "Session",
address: str,
serialized_tx: str,
- additional_info: Optional[TextIO],
+ additional_info: TextIO | None,
token: str | None,
) -> str:
"""Sign Solana transaction.
### python/src/trezorlib/cli/trezorctl.py
@@ -24,7 +24,7 @@
import os
import time
from pathlib import Path
-from typing import Any, Callable, Optional, TypeVar, cast
+from typing import Any, Callable, TypeVar, cast
import click
@@ -110,7 +110,7 @@ class TrezorctlGroup(AliasedGroup):
subcommand of "ethereum" group.
"""
- def get_command(self, ctx: click.Context, cmd_name: str) -> Optional[click.Command]:
+ def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None:
cmd = super().get_command(ctx, cmd_name)
if cmd:
return cmd
### python/src/trezorlib/definitions.py
@@ -14,6 +14,8 @@
# 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>.
+from __future__ import annotations
+
import logging
import tarfile
import typing as t
@@ -124,16 +126,16 @@ def _normalize_eth_address(address: t.AnyStr) -> str:
class Source:
- def fetch_path(self, *components: str) -> t.Optional[bytes]:
+ def fetch_path(self, *components: str) -> bytes | None:
raise NotImplementedError
- def get_eth_network_by_slip44(self, slip44: int) -> t.Optional[bytes]:
+ def get_eth_network_by_slip44(self, slip44: int) -> bytes | None:
return self.fetch_path("eth", "slip44", str(slip44), "network.dat")
- def get_eth_network(self, chain_id: int) -> t.Optional[bytes]:
+ def get_eth_network(self, chain_id: int) -> bytes | None:
return self.fetch_path("eth", "chain-id", str(chain_id), "network.dat")
- def get_eth_token(self, chain_id: int, address: t.AnyStr) -> t.Optional[bytes]:
+ def get_eth_token(self, chain_id: int, address: t.AnyStr) -> bytes | None:
address_str = _normalize_eth_address(address)
return self.fetch_path(
@@ -142,7 +144,7 @@ def get_eth_token(self, chain_id: int, address: t.AnyStr) -> t.Optional[bytes]:
def get_eth_display_format(
self, chain_id: int, address: t.AnyStr, func_sig: bytes
- ) -> t.Optional[bytes]:
+ ) -> bytes | None:
"""Fetch an ERC-7730 clear-signing contract descriptor (display format).
Descriptors are keyed by the contract address and the 4-byte function
@@ -160,20 +162,20 @@ def get_eth_display_format(
f"{address_str}-{func_sig_str}.dat",
)
- def get_solana_token(self, mint_account: str) -> t.Optional[bytes]:
+ def get_solana_token(self, mint_account: str) -> bytes | None:
return self.fetch_path("solana", "token", f"{mint_account}.dat")
class NullSource(Source):
- def fetch_path(self, *components: str) -> t.Optional[bytes]:
+ def fetch_path(self, *components: str) -> bytes | None:
return None
class FilesystemSource(Source):
def __init__(self, root: Path) -> None:
self.root = root
- def fetch_path(self, *components: str) -> t.Optional[bytes]:
+ def fetch_path(self, *components: str) -> bytes | None:
path = self.root.joinpath(*components)
if not path.exists():
LOG.info("Requested definition at %s was not found", path)
@@ -186,7 +188,7 @@ class UrlSource(Source):
def __init__(self, base_url: str = DEFS_BASE_URL) -> None:
self.base_url = base_url
- def fetch_path(self, *components: str) -> t.Optional[bytes]:
+ def fetch_path(self, *components: str) -> bytes | None:
url = self.base_url + "/".join(components)
LOG.info("Downloading definition from %s", url)
r = requests.get(url)
@@ -201,7 +203,7 @@ class TarSource(Source):
def __init__(self, path: Path) -> None:
self.archive = tarfile.open(path)
- def fetch_path(self, *components: str) -> t.Optional[bytes]:
+ def fetch_path(self, *components: str) -> bytes | None:
inner_name = "/".join(components)
LOG.info("Extracting definition from %s:%s", self.archive.name, inner_name)
try:
### python/src/trezorlib/device.py
@@ -24,7 +24,7 @@
import time
import warnings
from collections.abc import Iterable, Sequence
-from typing import TYPE_CHECKING, Callable, Optional, overload
+from typing import TYPE_CHECKING, Callable, overload
from slip10 import SLIP10
@@ -47,18 +47,18 @@
@workflow(refresh_features=True)
def apply_settings(
session: "Session",
- label: Optional[str] = None,
- language: Optional[str] = None,
- use_passphrase: Optional[bool] = None,
- homescreen: Optional[bytes] = None,
- passphrase_always_on_device: Optional[bool] = None,
- auto_lock_delay_ms: Optional[int] = None,
- auto_lock_delay_battery_ms: Optional[int] = None,
- display_rotation: Optional[messages.DisplayRotation] = None,
- safety_checks: Optional[messages.SafetyCheckLevel] = None,
- experimental_features: Optional[bool] = None,
- hide_passphrase_from_host: Optional[bool] = None,
- haptic_feedback: Optional[bool] = None,
+ label: str | None = None,
+ language: str | None = None,
+ use_passphrase: bool | None = None,
+ homescreen: bytes | None = None,
+ passphrase_always_on_device: bool | None = None,
+ auto_lock_delay_ms: int | None = None,
+ auto_lock_delay_battery_ms: int | None = None,
+ display_rotation: messages.DisplayRotation | None = None,
+ safety_checks: messages.SafetyCheckLevel | None = None,
+ experimental_features: bool | None = None,
+ hide_passphrase_from_host: bool | None = None,
+ haptic_feedback: bool | None = None,
) -> None:
if language is not None:
warnings.warn(
@@ -149,15 +149,15 @@ def recover(
word_count: int = 24,
passphrase_protection: bool = False,
pin_protection: bool = True,
- label: Optional[str] = None,
- language: Optional[str] = None,
- input_callback: Optional[Callable] = None,
+ label: str | None = None,
+ language: str | None = None,
+ input_callback: Callable | None = None,
input_method: messages.RecoveryDeviceInputMethod = messages.RecoveryDeviceInputMethod.ScrambledWords,
- backup_method: Optional[messages.BackupMethod] = None,
- dry_run: Optional[bool] = None,
- u2f_counter: Optional[int] = None,
+ backup_method: messages.BackupMethod | None = None,
+ dry_run: bool | None = None,
+ u2f_counter: int | None = None,
*,
- type: Optional[messages.RecoveryType] = None,
+ type: messages.RecoveryType | None = None,
) -> None:
if language is not None:
warnings.warn(
@@ -271,11 +271,11 @@ def _seed_from_entropy(
def reset(
session: "Session",
display_random: bool = False,
- strength: Optional[int] = None,
+ strength: int | None = None,
passphrase_protection: bool = False,
pin_protection: bool = True,
- label: Optional[str] = None,
- language: Optional[str] = None,
+ label: str | None = None,
+ language: str | None = None,
u2f_counter: int = 0,
skip_backup: bool = False,
no_backup: bool = False,
@@ -325,16 +325,16 @@ def _get_external_entropy() -> bytes:
def setup(
session: "Session",
*,
- strength: Optional[int] = None,
+ strength: int | None = None,
passphrase_protection: bool = True,
pin_protection: bool = False,
- label: Optional[str] = None,
+ label: str | None = None,
u2f_counter: int = 0,
skip_backup: bool = False,
no_backup: bool = False,
- backup_type: Optional[messages.BackupType] = None,
- backup_method: Optional[messages.BackupMethod] = None,
- entropy_check_count: Optional[int] = None,
+ backup_type: messages.BackupType | None = None,
+ backup_method: messages.BackupMethod | None = None,
+ entropy_check_count: int | None = None,
paths: Iterable[Address] = [],
_get_entropy: Callable[[], bytes] = _get_external_entropy,
) -> Iterable[tuple[Address, str]]:
@@ -593,9 +593,9 @@ def verify_entropy_commitment(
@workflow(refresh_features=True)
def backup(
session: "Session",
- group_threshold: Optional[int] = None,
+ group_threshold: int | None = None,
groups: Iterable[tuple[int, int]] = (),
- backup_method: Optional[messages.BackupMethod] = None,
+ backup_method: messages.BackupMethod | None = None,
) -> None:
session.call(
messages.BackupDevice(
@@ -634,7 +634,7 @@ def unlock_path(session: "Session", n: "Address") -> bytes:
def reboot_to_bootloader(
session: "Session",
boot_command: messages.BootCommand = messages.BootCommand.STOP_AND_WAIT,
- firmware_header: Optional[bytes] = None,
+ firmware_header: bytes | None = None,
) -> None:
session.call(
messages.RebootToBootloader(
@@ -656,7 +656,7 @@ def unlock_bootloader(session: "Session") -> None:
@workflow(refresh_features=True)
-def set_busy(session: "Session", expiry_ms: Optional[int]) -> None:
+def set_busy(session: "Session", expiry_ms: int | None) -> None:
"""Sets or clears the busy state of the device.
In the busy state the device shows a "Do not disconnect" message instead of the homescreen.
@@ -812,7 +812,7 @@ def authenticate(
@workflow()
-def set_brightness(session: "Session", value: Optional[int] = None) -> None:
+def set_brightness(session: "Session", value: int | None = None) -> None:
session.call(messages.SetBrightness(value=value), expect=messages.Success)
### python/src/trezorlib/ethereum.py
@@ -14,11 +14,13 @@
# 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>.
+from __future__ import annotations
+
import re
import warnings
from collections.abc import Sequence
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any, AnyStr, Optional, Union
+from typing import TYPE_CHECKING, Any, AnyStr
from typing_extensions import Self
@@ -67,7 +69,7 @@ def parse_type_n(type_name: str) -> int:
raise ValueError(f"Could not parse type<N> from {type_name}.")
-def parse_array_n(type_name: str) -> Optional[int]:
+def parse_array_n(type_name: str) -> int | None:
"""Parse N in type[<N>] where "type" can itself be an array type."""
# sign that it is a dynamic array - we do not know <N>
if type_name.endswith("[]"):
@@ -160,7 +162,7 @@ def get_authenticated_address(
session: "Session",
n: "Address",
show_display: bool = False,
- encoded_network: Optional[bytes] = None,
+ encoded_network: bytes | None = None,
chunkify: bool = False,
) -> messages.EthereumAddress:
resp = session.call(
@@ -225,7 +227,7 @@ class SignTxResult:
s: bytes
auth7702_list: Sequence[Sequence[bytes]] # non-empty for EIP-7702 transactions.
- def __getitem__(self, i: int) -> Union[int, bytes]:
+ def __getitem__(self, i: int) -> int | bytes:
"""Used for backwards compatiblity, to allow accessing and unpacking the signature tuple."""
warnings.warn(
"Ethereum signature is a dataclass (`SignTxResult`), not a tuple.",
@@ -235,7 +237,7 @@ def __getitem__(self, i: int) -> Union[int, bytes]:
return (self.v, self.r, self.s)[i]
@classmethod
- def from_response(cls, msg: messages.EthereumTxRequest) -> Optional[Self]:
+ def from_response(cls, msg: messages.EthereumTxRequest) -> Self | None:
if (
msg.signature_v is not None
and msg.signature_r is not None
@@ -254,9 +256,9 @@ def from_response(cls, msg: messages.EthereumTxRequest) -> Optional[Self]:
def _ethereum_sign_loop(
session: "Session",
- msg: Union[messages.EthereumSignTx, messages.EthereumSignTxEIP1559],
+ msg: messages.EthereumSignTx | messages.EthereumSignTxEIP1559,
data: bytes,
- definition_source: Optional["Source"],
+ definition_source: Source | None,
) -> SignTxResult:
"""Shared request/response loop for sign_tx and sign_tx_eip1559."""
response = session.call(msg)
@@ -298,14 +300,14 @@ def sign_tx(
gas_limit: int,
to: str,
value: int,
- data: Optional[bytes] = None,
- chain_id: Optional[int] = None,
- tx_type: Optional[int] = None,
- definitions: Optional[messages.EthereumDefinitions] = None,
+ data: bytes | None = None,
+ chain_id: int | None = None,
+ tx_type: int | None = None,
+ definitions: messages.EthereumDefinitions | None = None,
chunkify: bool = False,
- payment_req: Optional[messages.PaymentRequest] = None,
- supports_definition_request: Optional[bool] = None,
- definition_source: Optional["Source"] = None,
+ payment_req: messages.PaymentRequest | None = None,
+ supports_definition_request: bool | None = None,
+ definition_source: Source | None = None,
) -> SignTxResult:
if chain_id is None:
raise exceptions.TrezorException("Chain ID cannot be undefined")
@@ -353,13 +355,13 @@ def sign_tx_eip1559(
chain_id: int,
max_gas_fee: int,
max_priority_fee: int,
- access_list: Optional[list[messages.EthereumAccessList]] = None,
- definitions: Optional[messages.EthereumDefinitions] = None,
+ access_list: list[messages.EthereumAccessList] | None = None,
+ definitions: messages.EthereumDefinitions | None = None,
chunkify: bool = False,
- payment_req: Optional[messages.PaymentRequest] = None,
- supports_definition_request: Optional[bool] = None,
- definition_source: Optional["Source"] = None,
- auth7702: Optional[messages.EthereumAuth7702] = None,
+ payment_req: messages.PaymentRequest | None = None,
+ supports_definition_request: bool | None = None,
+ definition_source: Source | None = None,
+ auth7702: messages.EthereumAuth7702 | None = None,
) -> SignTxResult:
length = len(data)
data, chunk = data[1024:], data[:1024]
@@ -390,7 +392,7 @@ def sign_message(
session: "Session",
n: "Address",
message: AnyStr,
- encoded_network: Optional[bytes] = None,
+ encoded_network: bytes | None = None,
chunkify: bool = False,
) -> messages.EthereumMessageSignature:
return session.call(
@@ -411,8 +413,8 @@ def sign_typed_data(
data: dict[str, Any],
*,
metamask_v4_compat: bool = True,
- definitions: Optional[messages.EthereumDefinitions] = None,
- show_message_hash: Optional[bytes] = None,
+ definitions: messages.EthereumDefinitions | None = None,
+ show_message_hash: bytes | None = None,
) -> messages.EthereumTypedDataSignature:
data = sanitize_typed_data(data)
types = data["types"]
@@ -510,8 +512,8 @@ def sign_typed_data_hash(
session: "Session",
n: "Address",
domain_hash: bytes,
- message_hash: Optional[bytes],
- encoded_network: Optional[bytes] = None,
+ message_hash: bytes | None,
+ encoded_network: bytes | None = None,
) -> messages.EthereumTypedDataSignature:
return session.call(
messages.EthereumSignTypedHash(
### python/src/trezorlib/evolu.py
@@ -16,7 +16,7 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
from . import messages
from .tools import workflow
@@ -29,7 +29,7 @@
def get_node(
session: Session,
proof: bytes,
- node_rotation_index: Optional[int] = None,
+ node_rotation_index: int | None = None,
) -> bytes:
return session.call(
messages.EvoluGetNode(
@@ -55,9 +55,9 @@ def sign_registration_request(
def get_delegated_identity_key(
session: Session,
- rotation_index: Optional[int] = None,
- thp_credential: Optional[bytes] = None,
- rotate: Optional[bool] = False,
+ rotation_index: int | None = None,
+ thp_credential: bytes | None = None,
+ rotate: bool | None = False,
) -> messages.EvoluDelegatedIdentityKey:
return session.call(
messages.EvoluGetDelegatedIdentityKey(
@@ -71,7 +71,7 @@ def get_delegated_identity_key(
def index_management(
session: Session,
- rotation_index: Optional[int] = None,
+ rotation_index: int | None = None,
) -> messages.EvoluIndexManagementResponse:
return session.call(
messages.EvoluIndexManagement(
### python/src/trezorlib/messages.py
[binary or diff unavailable]
### python/src/trezorlib/misc.py
@@ -14,7 +14,9 @@
# 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>.
-from typing import TYPE_CHECKING, Optional
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
from . import messages
from .tools import workflow
@@ -35,7 +37,7 @@ def sign_identity(
identity: messages.IdentityType,
challenge_hidden: bytes,
challenge_visual: str,
- ecdsa_curve_name: Optional[str] = None,
+ ecdsa_curve_name: str | None = None,
) -> messages.SignedIdentity:
return session.call(
messages.SignIdentity(
@@ -53,7 +55,7 @@ def get_ecdh_session_key(
session: "Session",
identity: messages.IdentityType,
peer_public_key: bytes,
- ecdsa_curve_name: Optional[str] = None,
+ ecdsa_curve_name: str | None = None,
) -> messages.ECDHSessionKey:
return session.call(
messages.GetECDHSessionKey(
### python/src/trezorlib/ripple.py
@@ -14,7 +14,9 @@
# 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>.
-from typing import TYPE_CHECKING, Any, Optional
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
from . import messages
from .protobuf import dict_to_proto
@@ -54,7 +56,7 @@ def sign_tx(
address_n: "Address",
msg: messages.RippleSignTx,
chunkify: bool = False,
- payment_req: Optional[messages.PaymentRequest] = None,
+ payment_req: messages.PaymentRequest | None = None,
) -> messages.RippleSignedTx:
msg.address_n = address_n
msg.chunkify = chunkify
### python/src/trezorlib/solana.py
@@ -14,7 +14,9 @@
# 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>.
-from typing import TYPE_CHECKING, Any, Optional
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
from . import exceptions, messages
from .tools import workflow
@@ -61,8 +63,8 @@ def sign_tx(
session: "Session",
address_n: list[int],
serialized_tx: bytes,
- additional_info: Optional[messages.SolanaTxAdditionalInfo],
- payment_req: Optional[messages.PaymentRequest] = None,
+ additional_info: messages.SolanaTxAdditionalInfo | None,
+ payment_req: messages.PaymentRequest | None = None,
chunkify: bool = False,
) -> bytes:
return session.call(
### python/src/trezorlib/testing/common.py
@@ -14,8 +14,10 @@
# 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>.
+from __future__ import annotations
+
from collections.abc import Generator
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
from .. import messages
from ..debuglink import LayoutType
@@ -54,8 +56,8 @@ def get_text_possible_pagination(debug: "DebugLink", br: messages.ButtonRequest)
def swipe_if_necessary(
debug: "DebugLink",
- br_code: Optional[messages.ButtonRequestType] = None,
- br_name: Optional[str] = None,
+ br_code: messages.ButtonRequestType | None = None,
+ br_name: str | None = None,
) -> BRGeneratorType:
"""
Generator that swipes through pages if necessary, based on button request code.
### python/tests/test_merkle_tree.py
@@ -14,7 +14,7 @@
# You should have received a copy of the License along with this library.
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
-import typing as t
+from __future__ import annotations
import pytest
@@ -90,7 +90,7 @@
@pytest.mark.parametrize("node, expected_hash", NODE_VECTORS)
-def test_node(node: t.Union[Node, Leaf], expected_hash: str) -> None:
+def test_node(node: Node | Leaf, expected_hash: str) -> None:
assert node.tree_hash.hex() == expected_hash
### python/tools/build_tx.py
@@ -16,9 +16,11 @@
# 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>.
+from __future__ import annotations
+
import decimal
import json
-from typing import Any, Optional
+from typing import Any
import click
import requests
@@ -48,7 +50,7 @@ def prompt(*args: Any, **kwargs: Any):
return click.prompt(*args, err=True, **kwargs)
-def _default_script_type(address_n: Optional[list[int]], script_types: Any) -> str:
+def _default_script_type(address_n: list[int] | None, script_types: Any) -> str:
script_type = "address"
if address_n is None:
### python/tools/deserialize_tx.py
@@ -16,9 +16,11 @@
# 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>.
+from __future__ import annotations
+
import os
import sys
-from typing import Any, Optional
+from typing import Any
try:
import construct as c
@@ -65,7 +67,7 @@ def __init__(self, const: bytes) -> None:
self.const = const
super().__init__(c.Optional(c.Const(const)))
- def _encode(self, obj: Any, context: Any, path: Any) -> Optional[bytes]:
+ def _encode(self, obj: Any, context: Any, path: Any) -> bytes | None:
return self.const if obj else None
def _decode(self, obj: Any, context: Any, path: Any) -> bool:
### tests/click_tests/test_passphrase_bde.py
@@ -17,7 +17,7 @@
import time
from collections.abc import Generator
from contextlib import contextmanager
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
import pytest
@@ -59,7 +59,7 @@ def _get_test_address(session: Session) -> str:
@contextmanager
def prepare_passphrase_dialogue(
- device_handler: "BackgroundDeviceHandler", address: Optional[str] = None
+ device_handler: "BackgroundDeviceHandler", address: str | None = None
) -> Generator["DebugLink", None, None]:
debug = device_handler.debuglink()
device_handler.get_session(passphrase=PassphraseSetting.ON_DEVICE)
### tests/click_tests/test_passphrase_caesar.py
@@ -16,7 +16,7 @@
from collections.abc import Generator
from contextlib import contextmanager
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
import pytest
@@ -90,7 +90,7 @@ def _get_test_address(session: Session) -> str:
@contextmanager
def prepare_passphrase_dialogue(
- device_handler: "BackgroundDeviceHandler", address: Optional[str] = None
+ device_handler: "BackgroundDeviceHandler", address: str | None = None
) -> Generator["DebugLink", None, None]:
debug = device_handler.debuglink()
device_handler.get_session(passphrase=PassphraseSetting.ON_DEVICE)
### tests/common.py
@@ -21,7 +21,7 @@
import time
from collections.abc import Generator
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any
from unittest import mock
import pytest
@@ -171,7 +171,7 @@ def generate_entropy(
def click_through(
- debug: "DebugLink", screens: int, code: Optional[messages.ButtonRequestType] = None
+ debug: "DebugLink", screens: int, code: messages.ButtonRequestType | None = None
) -> Generator[None, "ButtonRequest", None]:
"""Click through N dialog screens.
@@ -194,7 +194,7 @@ def input_flow():
def read_and_confirm_mnemonic(
debug: "DebugLink", choose_wrong: bool = False
-) -> Generator[None, "ButtonRequest", Optional[str]]:
+) -> Generator[None, "ButtonRequest", str | None]:
"""Read mnemonic words from the screen and answer
confirmation questions.
Return the full mnemonic or None if `choose_wrong` is True.
### tests/device_tests/bitcoin/test_multisig_change.py
@@ -14,8 +14,6 @@
# 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>.
-from typing import Optional
-
import pytest
from trezorlib import btc, messages
@@ -194,8 +192,8 @@ def _responses(
session: Session,
INP1: messages.TxInputType,
INP2: messages.TxInputType,
- change_indices: Optional[list[int]] = None,
- foreign_indices: Optional[list[int]] = None,
+ change_indices: list[int] | None = None,
+ foreign_indices: list[int] | None = None,
):
if change_indices is None:
change_indices = []Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.