style: remove quotes from type annotations
What changed, and why it matters
This commit is a pure code-style cleanup. It removes unnecessary quotation marks around type annotations (for example, changing 'Session' to Session) across many Python files. These changes do not alter what the code does, how it handles data, or how it protects secrets. There is no security impact.
No security action required. Treat as a normal style/refactoring commit during review and CI validation.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The commit removes forward-reference string quotes from PEP 484 type annotations now that the codebase uses syntax (e.g., from future annotations or Python 3.9+ builtins such as list[X]) that resolves names at type-check time without string literals. All modifications are annotation-only; no runtime logic, call signatures, serialization, cryptography, or device-interaction behavior is changed. The diff touches trezorlib, core apps, tests, and tooling, but every hunk is a syntactic modernization.
Changed components
core/src/apps/cardano/helpers/hash_builder_collection.pycore/src/trezor/loop.pycore/src/trezor/ui/layouts/menu.pycore/tools/analyze-memory-dump.pypython/src/trezorlib/_internal/emu_ble.pypython/src/trezorlib/_internal/emulator.pypython/src/trezorlib/_internal/translations.pypython/src/trezorlib/authentication.pypython/src/trezorlib/btc.pypython/src/trezorlib/cardano.pypython/src/trezorlib/cli/__init__.pypython/src/trezorlib/cli/benchmark.pypython/src/trezorlib/cli/btc.pypython/src/trezorlib/cli/cardano.pypython/src/trezorlib/cli/debug.pypython/src/trezorlib/cli/device.pypython/src/trezorlib/cli/ethereum.pypython/src/trezorlib/cli/firmware.pypython/src/trezorlib/cli/nem.pypython/src/trezorlib/cli/nostr.pypython/src/trezorlib/cli/settings.pypython/src/trezorlib/cli/solana.pypython/src/trezorlib/client.pypython/src/trezorlib/debuglink.pypython/src/trezorlib/device.pypython/src/trezorlib/ethereum.pypython/src/trezorlib/fido.pypython/src/trezorlib/misc.pypython/src/trezorlib/protobuf.pypython/src/trezorlib/ripple.pypython/src/trezorlib/solana.pypython/src/trezorlib/testing/common.pypython/src/trezorlib/testing/device_handler.pypython/src/trezorlib/thp/pairing.pypython/src/trezorlib/transport/bridge.pypython/src/trezorlib/transport/hid.pypython/src/trezorlib/transport/udp.pypython/src/trezorlib/transport/webusb.pytests/click_tests/common.pytests/click_tests/device_menu/common.pytests/common.pytests/conftest.pytests/input_flows.pytests/prodtest_tests/tropic_utils.pytests/upgrade_tests/test_firmware_upgrades.pyInspect captured patch +288 / −292
### core/src/apps/cardano/helpers/hash_builder_collection.py
@@ -23,7 +23,7 @@ def __init__(self, size: int) -> None:
self.size = size
self.remaining = size
self.hash_fn: HashContext | None = None
- self.parent: "HashBuilderCollection | None" = None
+ self.parent: HashBuilderCollection | None = None
self.has_unfinished_child = False
def start(self, hash_fn: HashContext) -> "HashBuilderCollection":
### core/src/trezor/loop.py
@@ -505,7 +505,7 @@ class spawn(Syscall[T]):
def __init__(self, task: Task[T]) -> None:
self.task = task
self.callback: Task | None = None
- self.finalizer_callback: Callable[["spawn"], None] | None = None
+ self.finalizer_callback: Callable[[spawn], None] | None = None
self.finished = False
self.return_value: Any = None
### core/src/trezor/ui/layouts/menu.py
@@ -35,7 +35,7 @@ def __init__(
name: str = "",
) -> None:
self.name = name
- self.children: "Sequence[MenuNode[R]]" = tuple(children)
+ self.children: Sequence[MenuNode[R]] = tuple(children)
class MenuLeaf(Generic[R]):
### core/tools/analyze-memory-dump.py
@@ -122,7 +122,7 @@ def __getattr__(self, key: str) -> Any:
raise AttributeError
return self.item[key]
- def find_modules(self) -> list["Item"]:
+ def find_modules(self) -> list[Item]:
return [it for it in self.backlinks if it.type == "module"]
def name(self) -> str | None:
### python/src/trezorlib/_internal/emu_ble.py
@@ -139,7 +139,7 @@ def __init__(self, device: str | None = None) -> None:
super().__init__()
@classmethod
- def _try_path(cls, path: str) -> "EmuBleTransport":
+ def _try_path(cls, path: str) -> EmuBleTransport:
d = cls(path)
try:
d.open()
@@ -157,16 +157,16 @@ def _try_path(cls, path: str) -> "EmuBleTransport":
@classmethod
def enumerate(
- cls, _models: Iterable["TrezorModel"] | None = None
- ) -> Iterable["EmuBleTransport"]:
+ cls, _models: Iterable[TrezorModel] | None = None
+ ) -> Iterable[EmuBleTransport]:
default_path = f"{cls.DEFAULT_HOST}:{cls.DEFAULT_PORT}"
try:
return [cls._try_path(default_path)]
except TransportException:
return []
@classmethod
- def find_by_path(cls, path: str, prefix_search: bool = False) -> "EmuBleTransport":
+ def find_by_path(cls, path: str, prefix_search: bool = False) -> EmuBleTransport:
try:
address = path.replace(f"{cls.PATH_PREFIX}:", "")
return cls._try_path(address)
@@ -222,7 +222,7 @@ def read_chunk(self, timeout: float | None = None) -> bytes:
raise TransportException(f"Unexpected chunk size: {len(chunk)}")
return chunk
- def find_debug(self) -> "UdpTransport":
+ def find_debug(self) -> UdpTransport:
host, port = self.device
return UdpTransport(f"{host}:{port - 3}")
### python/src/trezorlib/_internal/emulator.py
@@ -152,7 +152,7 @@ def _wait_until_ready(self, timeout: float = TROPIC_MODEL_WAIT_TIME) -> None:
LOG.info(f"Tropic model ready after {time.monotonic() - start:.3f} seconds")
- def __enter__(self) -> "TropicModel":
+ def __enter__(self) -> TropicModel:
return self
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
@@ -348,7 +348,7 @@ def restart(self) -> None:
prev_screenshot_dir, refresh_index=self.restart_amount
)
- def __enter__(self) -> "Emulator":
+ def __enter__(self) -> Emulator:
return self
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
### python/src/trezorlib/_internal/translations.py
@@ -325,7 +325,7 @@ def from_file(cls, file_path: Path) -> Self:
class KerningTable(BlobTable):
@classmethod
- def from_dir(cls, model_fonts: dict[str, str], font_dir: Path) -> "KerningTable":
+ def from_dir(cls, model_fonts: dict[str, str], font_dir: Path) -> KerningTable:
"""Example structure of the font dict:
(The key number corresponds to the index representation of each font set in `gen_font.py`)
{
### python/src/trezorlib/authentication.py
@@ -437,7 +437,7 @@ def _check_ca_extensions(self) -> bool:
return passed
- def is_issued_by(self, issuer: "Certificate", path_len: int) -> bool:
+ def is_issued_by(self, issuer: Certificate, path_len: int) -> bool:
"""Check if this certificate was issued by an issuer.
Returns True if:
### python/src/trezorlib/btc.py
@@ -47,13 +47,13 @@ class Vin(TypedDict):
vout: int
sequence: int
coinbase: str
- scriptSig: "ScriptSig"
+ scriptSig: ScriptSig
txinwitness: list[str]
class Vout(TypedDict):
value: float
int: int
- scriptPubKey: "ScriptPubKey"
+ scriptPubKey: ScriptPubKey
class Transaction(TypedDict):
txid: str
@@ -72,8 +72,8 @@ def __getitem__(self, __key: bytes) -> messages.TransactionType: ...
def __contains__(self, __key: bytes) -> bool: ...
-def from_json(json_dict: "Transaction") -> messages.TransactionType:
- def make_input(vin: "Vin") -> messages.TxInputType:
+def from_json(json_dict: Transaction) -> messages.TransactionType:
+ def make_input(vin: Vin) -> messages.TxInputType:
if "coinbase" in vin:
return messages.TxInputType(
prev_hash=b"\0" * 32,
@@ -90,7 +90,7 @@ def make_input(vin: "Vin") -> messages.TxInputType:
sequence=vin["sequence"],
)
- def make_bin_output(vout: "Vout") -> messages.TxOutputBinType:
+ def make_bin_output(vout: Vout) -> messages.TxOutputBinType:
return messages.TxOutputBinType(
amount=int(Decimal(vout["value"]) * (10**8)),
script_pubkey=bytes.fromhex(vout["scriptPubKey"]["hex"]),
@@ -106,8 +106,8 @@ def make_bin_output(vout: "Vout") -> messages.TxOutputBinType:
@workflow(capability=messages.Capability.Bitcoin)
def get_public_node(
- session: "Session",
- n: "Address",
+ session: Session,
+ n: Address,
ecdsa_curve_name: str | None = None,
show_display: bool = False,
coin_name: str | None = None,
@@ -141,9 +141,9 @@ def get_address(*args: Any, **kwargs: Any) -> str:
@workflow(capability=messages.Capability.Bitcoin)
def get_authenticated_address(
- session: "Session",
+ session: Session,
coin_name: str,
- n: "Address",
+ n: Address,
show_display: bool = False,
multisig: messages.MultisigRedeemScriptType | None = None,
script_type: messages.InputScriptType = messages.InputScriptType.SPENDADDRESS,
@@ -174,9 +174,9 @@ def get_authenticated_address(
@workflow(capability=messages.Capability.Bitcoin)
def get_ownership_id(
- session: "Session",
+ session: Session,
coin_name: str,
- n: "Address",
+ n: Address,
multisig: messages.MultisigRedeemScriptType | None = None,
script_type: messages.InputScriptType = messages.InputScriptType.SPENDADDRESS,
) -> bytes:
@@ -193,9 +193,9 @@ def get_ownership_id(
@workflow(capability=messages.Capability.Bitcoin)
def get_ownership_proof(
- session: "Session",
+ session: Session,
coin_name: str,
- n: "Address",
+ n: Address,
multisig: messages.MultisigRedeemScriptType | None = None,
script_type: messages.InputScriptType = messages.InputScriptType.SPENDADDRESS,
user_confirmation: bool = False,
@@ -224,9 +224,9 @@ def get_ownership_proof(
@workflow(capability=messages.Capability.Bitcoin)
def sign_message(
- session: "Session",
+ session: Session,
coin_name: str,
- n: "Address",
+ n: Address,
message: AnyStr,
script_type: messages.InputScriptType = messages.InputScriptType.SPENDADDRESS,
no_script_type: bool = False,
@@ -246,7 +246,7 @@ def sign_message(
def verify_message(
- session: "Session",
+ session: Session,
coin_name: str,
address: str,
signature: bytes,
@@ -271,7 +271,7 @@ def verify_message(
@workflow(capability=messages.Capability.Bitcoin)
def sign_tx(
- session: "Session",
+ session: Session,
coin_name: str,
inputs: Sequence[messages.TxInputType],
outputs: Sequence[messages.TxOutputType],
@@ -415,12 +415,12 @@ def copy_tx_meta(tx: messages.TransactionType) -> messages.TransactionType:
@workflow(capability=messages.Capability.Bitcoin)
def authorize_coinjoin(
- session: "Session",
+ session: Session,
coordinator: str,
max_rounds: int,
max_coordinator_fee_rate: int,
max_fee_per_kvbyte: int,
- n: "Address",
+ n: Address,
coin_name: str,
script_type: messages.InputScriptType = messages.InputScriptType.SPENDADDRESS,
) -> None:
### python/src/trezorlib/cardano.py
@@ -832,7 +832,7 @@ def get_address(*args: Any, **kwargs: Any) -> str:
@tools.workflow(capability=m.Capability.Cardano)
def get_authenticated_address(
- session: "Session",
+ session: Session,
address_parameters: m.CardanoAddressParametersType,
protocol_magic: int = PROTOCOL_MAGICS["mainnet"],
network_id: int = NETWORK_IDS["mainnet"],
@@ -855,7 +855,7 @@ def get_authenticated_address(
@tools.workflow(capability=m.Capability.Cardano)
def get_public_key(
- session: "Session",
+ session: Session,
address_n: list[int],
derivation_type: m.CardanoDerivationType = m.CardanoDerivationType.ICARUS,
show_display: bool = False,
@@ -872,7 +872,7 @@ def get_public_key(
@tools.workflow(capability=m.Capability.Cardano)
def get_native_script_hash(
- session: "Session",
+ session: Session,
native_script: m.CardanoNativeScript,
display_format: m.CardanoNativeScriptHashDisplayFormat = m.CardanoNativeScriptHashDisplayFormat.HIDE,
derivation_type: m.CardanoDerivationType = m.CardanoDerivationType.ICARUS,
@@ -889,7 +889,7 @@ def get_native_script_hash(
@tools.workflow(capability=m.Capability.Cardano)
def sign_tx(
- session: "Session",
+ session: Session,
signing_mode: m.CardanoTxSigningMode,
inputs: list[InputWithPath],
outputs: list[OutputWithData],
@@ -1015,7 +1015,7 @@ def sign_tx(
@tools.workflow(capability=m.Capability.Cardano)
def sign_message(
- session: "Session",
+ session: Session,
signing_path: Path,
payload: bytes,
prefer_hex_display: bool,
### python/src/trezorlib/cli/__init__.py
@@ -559,13 +559,13 @@ def with_session(
def decorator(
func: FuncWithSession,
- ) -> "t.Callable[P, R]":
+ ) -> t.Callable[P, R]:
@click.pass_obj
@functools.wraps(func)
def function_with_session(
- obj: TrezorConnection, *args: "P.args", **kwargs: "P.kwargs"
- ) -> "R":
+ obj: TrezorConnection, *args: P.args, **kwargs: P.kwargs
+ ) -> R:
with obj.session_context(
prompt_passphrase=passphrase,
derive_cardano=cardano,
### python/src/trezorlib/cli/benchmark.py
@@ -28,7 +28,7 @@
from ..client import Session
-def list_names_patern(session: "Session", pattern: str | None = 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
@@ -43,7 +43,7 @@ def cli() -> None:
@cli.command()
@click.argument("pattern", required=False)
@with_session(passphrase=False)
-def list_names(session: "Session", pattern: str | None = 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:
@@ -56,7 +56,7 @@ def list_names(session: "Session", pattern: str | None = None) -> None:
@cli.command()
@click.argument("pattern", required=False)
@with_session(passphrase=False)
-def run(session: "Session", pattern: str | None) -> 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
@@ -178,7 +178,7 @@ def cli() -> None:
@click.option("-C", "--chunkify", is_flag=True)
@with_session
def get_address(
- session: "Session",
+ session: Session,
coin: str,
address: str,
script_type: messages.InputScriptType | None,
@@ -257,7 +257,7 @@ def get_address(
@click.option("-i", "--ignore-xpub-magic", is_flag=True)
@with_session
def get_public_node(
- session: "Session",
+ session: Session,
coin: str,
address: str,
curve: str | None,
@@ -297,7 +297,7 @@ def _append_descriptor_checksum(desc: str) -> str:
def _get_descriptor(
- session: "Session",
+ session: Session,
coin: str | None,
account: int,
purpose: int | None,
@@ -370,7 +370,7 @@ def _get_descriptor(
@click.option("-d", "--show-display", is_flag=True)
@with_session
def get_descriptor(
- session: "Session",
+ session: Session,
coin: str | None,
account: int,
account_type: int | None,
@@ -396,7 +396,7 @@ def get_descriptor(
@click.option("-C", "--chunkify", is_flag=True)
@click.argument("json_file", type=click.File())
@with_session
-def sign_tx(session: "Session", json_file: TextIO, chunkify: bool) -> None:
+def sign_tx(session: Session, json_file: TextIO, chunkify: bool) -> None:
"""Sign transaction.
Transaction data must be provided in a JSON file. See `transaction-format.md` for
@@ -454,7 +454,7 @@ def sign_tx(session: "Session", json_file: TextIO, chunkify: bool) -> None:
@click.argument("message")
@with_session
def sign_message(
- session: "Session",
+ session: Session,
coin: str,
address: str,
message: str,
@@ -493,7 +493,7 @@ def sign_message(
@click.argument("message")
@with_session
def verify_message(
- session: "Session",
+ session: Session,
coin: str,
address: str,
signature: str,
### python/src/trezorlib/cli/cardano.py
@@ -66,7 +66,7 @@ def cli() -> None:
@click.option("-T", "--tag-cbor-sets", is_flag=True)
@with_session(cardano=True)
def sign_tx(
- session: "Session",
+ session: Session,
file: TextIO,
signing_mode: messages.CardanoTxSigningMode,
protocol_magic: int,
@@ -212,7 +212,7 @@ def sign_tx(
@click.option("-C", "--chunkify", is_flag=True)
@with_session(cardano=True)
def get_address(
- session: "Session",
+ session: Session,
address: str,
address_type: messages.CardanoAddressType,
staking_address: str,
@@ -285,7 +285,7 @@ def get_address(
@click.option("-d", "--show-display", is_flag=True)
@with_session(cardano=True)
def get_public_key(
- session: "Session",
+ session: Session,
address: str,
derivation_type: messages.CardanoDerivationType,
show_display: bool,
@@ -313,7 +313,7 @@ def get_public_key(
)
@with_session(cardano=True)
def get_native_script_hash(
- session: "Session",
+ session: Session,
file: TextIO,
display_format: messages.CardanoNativeScriptHashDisplayFormat,
derivation_type: messages.CardanoDerivationType,
@@ -337,7 +337,7 @@ def get_native_script_hash(
)
@with_session(cardano=True)
def sign_message(
- session: "Session",
+ session: Session,
file: TextIO,
derivation_type: messages.CardanoDerivationType,
) -> messages.CardanoMessageSignature:
### python/src/trezorlib/cli/debug.py
@@ -94,7 +94,7 @@ def cli() -> None:
)
@click.option("-s", "--stop", is_flag=True, help="Stop the recording")
@click.pass_obj
-def record(obj: "TrezorConnection", directory: Path | None, stop: bool) -> None:
+def record(obj: TrezorConnection, directory: Path | None, stop: bool) -> None:
"""Record screen changes into a specified directory.
Recording can be stopped with `-s / --stop` option.
@@ -106,7 +106,7 @@ def record(obj: "TrezorConnection", directory: Path | None, stop: bool) -> None:
@cli.command()
@with_session(seedless=True)
-def prodtest_t1(session: "Session") -> None:
+def prodtest_t1(session: Session) -> None:
"""Perform a prodtest on Model One.
Only available on PRODTEST firmware and on T1B1. Formerly named self-test.
@@ -116,7 +116,7 @@ def prodtest_t1(session: "Session") -> None:
@cli.command()
@with_session(seedless=True)
-def optiga_set_sec_max(session: "Session") -> None:
+def optiga_set_sec_max(session: Session) -> None:
"""Set Optiga's security event counter to maximum."""
debug_transport = session.client.transport.find_debug()
debug_transport.open()
@@ -128,7 +128,7 @@ def optiga_set_sec_max(session: "Session") -> None:
@cli.command()
@click.argument("filter", required=False)
@with_session(seedless=True)
-def set_log_filter(session: "Session", filter: str) -> None:
+def set_log_filter(session: Session, filter: str) -> None:
"""Set logging filter string."""
debug_transport = session.client.transport.find_debug()
debug_transport.open()
@@ -175,7 +175,7 @@ def set_log_filter(session: "Session", filter: str) -> None:
)
@with_session(seedless=True)
def set_battery_state(
- session: "Session",
+ session: Session,
soc: int | None,
usb_connected: bool | None,
wireless_connected: bool | None,
### python/src/trezorlib/cli/device.py
@@ -71,7 +71,7 @@ def cli() -> None:
is_flag=True,
)
@with_session(seedless=True)
-def wipe(session: "Session", bootloader: bool) -> None:
+def wipe(session: Session, bootloader: bool) -> None:
"""Reset device to factory defaults and remove all private data."""
features = session.features
if bootloader:
@@ -112,7 +112,7 @@ def wipe(session: "Session", bootloader: bool) -> None:
@click.option("-n", "--no-backup", is_flag=True)
@with_session(seedless=True)
def load(
- session: "Session",
+ session: Session,
mnemonic: t.Sequence[str],
pin: str,
passphrase_protection: bool,
@@ -181,7 +181,7 @@ def load(
@click.option("-b", "--unlock-repeated-backup", is_flag=True)
@with_session(seedless=True)
def recover(
- session: "Session",
+ session: Session,
words: str,
expand: bool,
pin_protection: bool,
@@ -243,7 +243,7 @@ def recover(
@click.option("-e", "--entropy-check-count", type=click.IntRange(0))
@with_session(seedless=True)
def setup(
- session: "Session",
+ session: Session,
strength: int | None,
passphrase_protection: bool,
pin_protection: bool,
@@ -314,7 +314,7 @@ def setup(
@click.option("-m", "--method", "method", type=ChoiceType(BACKUP_METHOD))
@with_session(seedless=True)
def backup(
- session: "Session",
+ session: Session,
group_threshold: int | None = None,
groups: t.Sequence[tuple[int, int]] = (),
method: messages.BackupMethod = messages.BackupMethod.Display,
@@ -337,7 +337,7 @@ def backup(
@cli.command()
@click.argument("operation", type=ChoiceType(SD_PROTECT_OPERATIONS))
@with_session(seedless=True)
-def sd_protect(session: "Session", operation: messages.SdProtectOperationType) -> None:
+def sd_protect(session: Session, operation: messages.SdProtectOperationType) -> None:
"""Secure the device with SD card protection.
When SD card protection is enabled, a randomly generated secret is stored
@@ -358,7 +358,7 @@ def sd_protect(session: "Session", operation: messages.SdProtectOperationType) -
@cli.command()
@click.pass_obj
-def reboot_to_bootloader(obj: "TrezorConnection") -> None:
+def reboot_to_bootloader(obj: TrezorConnection) -> None:
"""Reboot device into bootloader mode."""
# avoid using @with_session because it closes the session afterwards,
# which triggers double prompt on device
@@ -368,14 +368,14 @@ def reboot_to_bootloader(obj: "TrezorConnection") -> None:
@cli.command()
@with_session(seedless=True)
-def tutorial(session: "Session") -> None:
+def tutorial(session: Session) -> None:
"""Show on-device tutorial."""
device.show_device_tutorial(session)
@cli.command()
@with_session(seedless=True)
-def unlock_bootloader(session: "Session") -> None:
+def unlock_bootloader(session: Session) -> None:
"""Unlocks bootloader. Irreversible."""
device.unlock_bootloader(session)
@@ -389,7 +389,7 @@ def unlock_bootloader(session: "Session") -> None:
help="Dialog expiry in seconds.",
)
@with_session(seedless=True)
-def set_busy(session: "Session", enable: bool | None, expiry: int | None) -> None:
+def set_busy(session: Session, enable: bool | None, expiry: int | None) -> None:
"""Show a "Do not disconnect" dialog."""
if enable is False:
device.set_busy(session, None)
@@ -445,7 +445,7 @@ def _print_auth_data(signature: bytes, certificates: t.Sequence[bytes]) -> None:
)
@with_session(seedless=True)
def authenticate(
- session: "Session",
+ session: Session,
hex_challenge: str | None,
p256_root: t.BinaryIO | None,
ed25519_root: t.BinaryIO | None,
@@ -549,15 +549,15 @@ def format(self, record: logging.LogRecord) -> str:
@cli.command()
@with_session(seedless=True)
-def serial_number(session: "Session") -> str:
+def serial_number(session: Session) -> str:
"""Get serial number."""
return device.get_serial_number(session)
@cli.command()
@click.option("--all", is_flag=True, help="Forget all devices.")
@click.pass_obj
-def forget(obj: "TrezorConnection", all: bool) -> None:
+def forget(obj: TrezorConnection, all: bool) -> None:
"""Forget a THP pairing key.
Forgets the THP pairing key for the currently connected device.
### python/src/trezorlib/cli/ethereum.py
@@ -75,7 +75,7 @@ def _print_eth_dependencies_and_die() -> NoReturn:
sys.exit(1)
-def _get_web3() -> "web3.Web3":
+def _get_web3() -> web3.Web3:
global _WEB3_INSTANCE
if _WEB3_INSTANCE is None:
try:
@@ -134,7 +134,7 @@ def _list_units(ctx: click.Context, param: Any, value: bool) -> None:
def _erc20_contract(
- token_address: "ChecksumAddress", to_address: str, amount: int
+ token_address: ChecksumAddress, to_address: str, amount: int
) -> str:
min_abi = [
{
@@ -154,7 +154,7 @@ def _erc20_contract(
def _format_access_list(
access_list: list[EthereumAccessList],
-) -> "_rlp.RLPItem":
+) -> _rlp.RLPItem:
return [
(ethereum.decode_hex(item.address), item.storage_keys) for item in access_list
]
@@ -296,7 +296,7 @@ def cli(
@click.option("-C", "--chunkify", is_flag=True)
@with_session
def get_address(
- session: "Session", address: str, show_display: bool, chunkify: bool
+ session: Session, address: str, show_display: bool, chunkify: bool
) -> str:
"""Get Ethereum address in hex encoding."""
address_n = tools.parse_path(address)
@@ -308,7 +308,7 @@ def get_address(
@click.option("-n", "--address", required=True, help=PATH_HELP)
@click.option("-d", "--show-display", is_flag=True)
@with_session
-def get_public_node(session: "Session", address: str, show_display: bool) -> dict:
+def get_public_node(session: Session, address: str, show_display: bool) -> dict:
"""Get Ethereum public node of given path."""
address_n = tools.parse_path(address)
result = ethereum.get_public_node(session, address_n, show_display=show_display)
@@ -372,7 +372,7 @@ def get_public_node(session: "Session", address: str, show_display: bool) -> dic
@click.argument("amount", callback=_amount_to_int)
@with_session
def sign_tx(
- session: "Session",
+ session: Session,
chain_id: int,
address: str,
amount: int,
@@ -560,7 +560,7 @@ def sign_tx(
@click.argument("message")
@with_session
def sign_message(
- session: "Session", address: str, message: str, chunkify: bool
+ session: Session, address: str, message: str, chunkify: bool
) -> dict[str, str]:
"""Sign message with Ethereum address."""
address_n = tools.parse_path(address)
@@ -584,7 +584,7 @@ def sign_message(
@click.argument("file", type=click.File("r"))
@with_session
def sign_typed_data(
- session: "Session", address: str, metamask_v4_compat: bool, file: TextIO
+ session: Session, address: str, metamask_v4_compat: bool, file: TextIO
) -> dict[str, str]:
"""Sign typed data (EIP-712) with Ethereum address.
@@ -617,7 +617,7 @@ def sign_typed_data(
@click.argument("message")
@with_session
def verify_message(
- session: "Session",
+ session: Session,
address: str,
signature: str,
message: str,
@@ -636,7 +636,7 @@ def verify_message(
@click.argument("message_hash_hex")
@with_session
def sign_typed_data_hash(
- session: "Session", address: str, domain_hash_hex: str, message_hash_hex: str
+ session: Session, address: str, domain_hash_hex: str, message_hash_hex: str
) -> dict[str, str]:
"""
Sign hash of typed data (EIP-712) with Ethereum address.
### python/src/trezorlib/cli/firmware.py
@@ -54,7 +54,7 @@ def _print_version(version: tuple[int, int, int, int]) -> None:
click.echo(f"Firmware version {major}.{minor}.{patch} build {build}")
-def _is_bootloader_onev2(client: "TrezorClient") -> bool:
+def _is_bootloader_onev2(client: TrezorClient) -> bool:
"""Check if bootloader is capable of installing the Trezor One v2 firmware directly.
This is the case from bootloader version 1.8.0, and also holds for firmware version
@@ -89,7 +89,7 @@ def _print_firmware_model(hw_model: bytes | fw_models.Model) -> None:
click.echo(f"Suspicious hardware model code: {hw_model.hex()} ({hw_model!r})")
-def print_firmware_version(fw: "firmware.FirmwareType") -> None:
+def print_firmware_version(fw: firmware.FirmwareType) -> None:
"""Print out the firmware version and details."""
if isinstance(fw, firmware.LegacyFirmware):
if fw.embedded_v2:
@@ -109,7 +109,7 @@ def print_firmware_version(fw: "firmware.FirmwareType") -> None:
def validate_signatures(
- fw: "firmware.FirmwareType", prompt_unsigned: bool = True
+ fw: firmware.FirmwareType, prompt_unsigned: bool = True
) -> None:
"""Check the signatures on the firmware.
@@ -151,7 +151,7 @@ def validate_signatures(
def validate_fingerprint(
- fw: "firmware.FirmwareType",
+ fw: firmware.FirmwareType,
expected_fingerprint: str | None = None,
) -> None:
"""Determine and validate the firmware fingerprint.
@@ -172,7 +172,7 @@ def validate_fingerprint(
def check_device_match(
- fw: "firmware.FirmwareType", model: TrezorModel, bootloader_onev2: bool
+ fw: firmware.FirmwareType, model: TrezorModel, bootloader_onev2: bool
) -> None:
"""Validate if the device and firmware are compatible.
@@ -268,7 +268,7 @@ def _should_use_bitcoin_only(features: messages.Features) -> bool:
def find_best_firmware_version(
- client: "TrezorClient",
+ client: TrezorClient,
version: str | None,
bitcoin_only: bool | None,
) -> tuple[str, str]:
@@ -426,7 +426,7 @@ def extract_embedded_fw(
def upload_firmware_into_device(
- session: "Session",
+ session: Session,
firmware_data: bytes,
) -> None:
"""Perform the final act of loading the firmware into Trezor."""
@@ -452,9 +452,7 @@ def upload_firmware_into_device(
_PROBE_TIMEOUT = 1.0
-def _answers(
- transport: "Transport", mapping: "ProtobufMapping", reconnect: bool
-) -> bool:
+def _answers(transport: Transport, mapping: ProtobufMapping, reconnect: bool) -> bool:
"""Whether the device answers a message right now. A Busy failure does not
count: the nRF sends it on its own while the main MCU is not accepting
messages, e.g. during a reboot. Without `reconnect`, a closed link counts
@@ -478,7 +476,7 @@ def _answers(
def _wait_for_device(
- obj: "TrezorConnection", mapping: "ProtobufMapping", message: str
+ obj: TrezorConnection, mapping: ProtobufMapping, message: str
) -> None:
"""Close the connection and wait for the device to leave and come back: the
device still answers for a moment before it reboots, so a reconnect could
@@ -516,7 +514,7 @@ def _wait_for_device(
pass
-def _is_strict_update(client: "TrezorClient", firmware_data: bytes) -> bool:
+def _is_strict_update(client: TrezorClient, firmware_data: bytes) -> bool:
"""Check if the firmware is from the same vendor and the
firmware is newer than the currently installed firmware.
"""
@@ -566,7 +564,7 @@ def cli() -> None:
@click.pass_obj
# fmt: on
def verify(
- obj: "TrezorConnection",
+ obj: TrezorConnection,
filename: BinaryIO,
check_device: bool,
fingerprint: str | None,
@@ -610,7 +608,7 @@ def verify(
@click.pass_obj
# fmt: on
def download(
- obj: "TrezorConnection",
+ obj: TrezorConnection,
output: BinaryIO | None,
model: TrezorModel | None,
version: str | None,
@@ -671,7 +669,7 @@ def download(
# fmt: on
@click.pass_obj
def update(
- obj: "TrezorConnection",
+ obj: TrezorConnection,
filename: BinaryIO | None,
url: str | None,
version: str | None,
@@ -754,7 +752,7 @@ def update(
@cli.command()
@click.argument("hex_challenge", required=False)
@with_session(seedless=True)
-def get_hash(session: "Session", hex_challenge: str | None) -> 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
@@ -43,7 +43,7 @@ def cli() -> None:
@click.option("-C", "--chunkify", is_flag=True)
@with_session
def get_address(
- session: "Session",
+ session: Session,
address: str,
network: int,
show_display: bool,
@@ -62,7 +62,7 @@ def get_address(
@click.option("-C", "--chunkify", is_flag=True)
@with_session
def sign_tx(
- session: "Session",
+ session: Session,
address: str,
file: TextIO,
broadcast: str | None,
### python/src/trezorlib/cli/nostr.py
@@ -40,7 +40,7 @@ def cli() -> None:
@click.option("-a", "--account", default=0, help="Account index")
@with_session
def get_pubkey(
- session: "Session",
+ session: Session,
account: int,
) -> str:
"""Return the pubkey derived by the given path."""
@@ -58,7 +58,7 @@ def get_pubkey(
@click.argument("event")
@with_session
def sign_event(
- session: "Session",
+ session: Session,
account: int,
event: str,
) -> dict[str, str]:
### python/src/trezorlib/cli/settings.py
@@ -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: bool | None, 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: bool | None, 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: bool | None, 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
@@ -217,22 +217,22 @@ def wipe_code(session: "Session", enable: bool | None, remove: bool) -> None:
@click.option("-l", "--label", "_ignore", is_flag=True, hidden=True, expose_value=False)
@click.argument("label")
@with_session(seedless=True)
-def label(session: "Session", label: str) -> None:
+def label(session: Session, label: str) -> None:
"""Set new device label."""
device.apply_settings(session, label=label)
@cli.command()
@with_session(seedless=True)
-def brightness(session: "Session") -> None:
+def brightness(session: Session) -> None:
"""Set display brightness."""
device.set_brightness(session)
@cli.command()
@click.argument("enable", type=ChoiceType({"on": True, "off": False}))
@with_session(seedless=True)
-def haptic_feedback(session: "Session", enable: bool) -> None:
+def haptic_feedback(session: Session, enable: bool) -> None:
"""Enable or disable haptic feedback."""
device.apply_settings(session, haptic_feedback=enable)
@@ -245,7 +245,7 @@ def haptic_feedback(session: "Session", enable: bool) -> None:
@click.option("-d/-D", "--display/--no-display", default=None)
@with_session(seedless=True)
def language(
- session: "Session", path_or_url: str | None, remove: bool, display: bool | None
+ session: Session, path_or_url: str | None, remove: bool, display: bool | None
) -> None:
"""Set new language with translations."""
if remove != (path_or_url is None):
@@ -275,7 +275,7 @@ def language(
@cli.command()
@click.argument("rotation", type=ChoiceType(ROTATION))
@with_session(seedless=True)
-def display_rotation(session: "Session", rotation: messages.DisplayRotation) -> None:
+def display_rotation(session: Session, rotation: messages.DisplayRotation) -> None:
"""Set display rotation.
Configure display rotation for Trezor Model T. The options are
@@ -287,7 +287,7 @@ def display_rotation(session: "Session", rotation: messages.DisplayRotation) ->
@cli.command()
@click.argument("delay", type=str)
@with_session(seedless=True)
-def auto_lock_delay(session: "Session", delay: str) -> None:
+def auto_lock_delay(session: Session, delay: str) -> None:
"""Set auto-lock delay (in seconds)."""
if not session.features.pin_protection:
@@ -305,7 +305,7 @@ def auto_lock_delay(session: "Session", delay: str) -> None:
@cli.command()
@click.argument("flags")
@with_session(seedless=True)
-def flags(session: "Session", flags: str) -> None:
+def flags(session: Session, flags: str) -> None:
"""Set device flags."""
if flags.lower().startswith("0b"):
flags_int = int(flags, 2)
@@ -323,7 +323,7 @@ def flags(session: "Session", flags: str) -> None:
)
@click.option("-q", "--quality", type=int, default=90, help="JPEG quality (0-100)")
@with_session(seedless=True)
-def homescreen(session: "Session", filename: str, quality: int) -> None:
+def homescreen(session: Session, filename: str, quality: int) -> None:
"""Set new homescreen.
To revert to default homescreen, use 'trezorctl set homescreen default'
@@ -387,7 +387,7 @@ def homescreen(session: "Session", filename: str, quality: int) -> None:
@click.argument("level", type=ChoiceType(SAFETY_LEVELS))
@with_session(seedless=True)
def safety_checks(
- session: "Session", always: bool, level: messages.SafetyCheckLevel
+ session: Session, always: bool, level: messages.SafetyCheckLevel
) -> None:
"""Set safety check level.
@@ -406,7 +406,7 @@ def safety_checks(
@cli.command()
@click.argument("enable", type=ChoiceType({"on": True, "off": False}))
@with_session(seedless=True)
-def experimental_features(session: "Session", enable: bool) -> None:
+def experimental_features(session: Session, enable: bool) -> None:
"""Enable or disable experimental message types.
This is a developer feature. Use with caution.
@@ -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: bool | None) -> 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
@@ -450,7 +450,7 @@ def passphrase_on(session: "Session", force_on_device: bool | None) -> None:
@passphrase.command(name="off")
@with_session(seedless=True)
-def passphrase_off(session: "Session") -> None:
+def passphrase_off(session: Session) -> None:
"""Disable passphrase."""
device.apply_settings(session, use_passphrase=False)
@@ -466,7 +466,7 @@ def passphrase_off(session: "Session") -> None:
@passphrase.command(name="hide")
@click.argument("hide", type=ChoiceType({"on": True, "off": False}))
@with_session(seedless=True)
-def hide_passphrase_from_host(session: "Session", hide: bool) -> None:
+def hide_passphrase_from_host(session: Session, hide: bool) -> None:
"""Enable or disable hiding passphrase coming from host.
This is a developer feature. Use with caution.
### python/src/trezorlib/cli/solana.py
@@ -42,7 +42,7 @@ def cli() -> None:
@click.option("-d", "--show-display", is_flag=True)
@with_session
def get_public_key(
- session: "Session",
+ session: Session,
address: str,
show_display: bool,
) -> bytes:
@@ -57,7 +57,7 @@ def get_public_key(
@click.option("-C", "--chunkify", is_flag=True)
@with_session
def get_address(
- session: "Session",
+ session: Session,
address: str,
show_display: bool,
chunkify: bool,
@@ -87,7 +87,7 @@ def _get_token(token: str | None) -> bytes | None:
@click.option("-t", "--token", type=str)
@with_session
def sign_tx(
- session: "Session",
+ session: Session,
address: str,
serialized_tx: str,
additional_info: TextIO | None,
@@ -151,7 +151,7 @@ def sign_tx(
@click.option("-C", "--chunkify", is_flag=True)
@with_session
def sign_message(
- session: "Session",
+ session: Session,
address: str,
message: str,
signer: tuple[str, ...],
@@ -193,7 +193,7 @@ def sign_message(
@click.option("-C", "--chunkify", is_flag=True)
@with_session
def verify_message(
- session: "Session",
+ session: Session,
message: str,
signer: tuple[str, ...],
signature: tuple[str, ...],
### python/src/trezorlib/client.py
@@ -597,7 +597,7 @@ def get_default_client(
pin_callback: t.Callable[[messages.PinMatrixRequest], str] | None = None,
code_entry_callback: t.Callable[[], str] | None = None,
**kwargs: t.Any,
-) -> "TrezorClient":
+) -> TrezorClient:
"""Get a client for a connected Trezor device.
Returns a TrezorClient instance with minimum fuss.
### python/src/trezorlib/debuglink.py
@@ -59,7 +59,7 @@ def __call__(
self,
hold_ms: int | None = None,
wait: bool | None = None,
- ) -> "None": ...
+ ) -> None: ...
InputFlowType = t.Generator[None, messages.ButtonRequest, None]
@@ -80,7 +80,7 @@ class LayoutType(Enum):
Eckhart = auto()
@classmethod
- def from_model(cls, model: models.TrezorModel) -> "LayoutType":
+ def from_model(cls, model: models.TrezorModel) -> LayoutType:
# The model's UI layout is sourced from the single-source model registry
# (trezorlib._modeldata); LayoutType member names match those layout
# names, so a new model is handled without touching this function.
@@ -93,7 +93,7 @@ def from_model(cls, model: models.TrezorModel) -> "LayoutType":
raise ValueError(f"Unknown model: {model}")
@classmethod
- def from_internal_name(cls, internal_name: str) -> "LayoutType":
+ def from_internal_name(cls, internal_name: str) -> LayoutType:
model = models.by_internal_name(internal_name)
if model is not None and model.layout:
return cls[model.layout]
@@ -505,15 +505,15 @@ def _make_input_func(
button: messages.DebugButton | None = None,
physical_button: messages.DebugPhysicalButton | None = None,
swipe: messages.DebugSwipeDirection | None = None,
-) -> "InputFunc":
+) -> InputFunc:
decision = messages.DebugLinkDecision(
button=button,
physical_button=physical_button,
swipe=swipe,
)
def input_func(
- self: "DebugLink",
+ self: DebugLink,
hold_ms: int | None = None,
wait: bool | None = None,
) -> None:
@@ -525,7 +525,7 @@ def input_func(
class DebugLink:
- def __init__(self, transport: "Transport", auto_interact: bool = True) -> None:
+ def __init__(self, transport: Transport, auto_interact: bool = True) -> None:
transport.open(reopen=True)
self.transport = transport
@@ -1077,7 +1077,7 @@ def reset_input_flow(self) -> None:
next(self.input_flow) # start default input flow generator
def default_input_flow(
- self, on_page: t.Callable[["LayoutContent"], None] | None = None
+ self, on_page: t.Callable[[LayoutContent], None] | None = None
) -> InputFlowType:
while True:
br = yield
@@ -1209,7 +1209,7 @@ def visit_menu_items(
def _paginate_and_confirm(
self,
pages: int | None,
- on_page: t.Callable[["LayoutContent"], None] | None = None,
+ on_page: t.Callable[[LayoutContent], None] | None = None,
) -> None:
# TODO: we should check for `debuglink.layout` instead of `debuglink.model` but it fails emu sanity check of T3W1
if pages is None:
@@ -1278,7 +1278,7 @@ def __init__(
self.fields: dict[str, t.Any] = {}
self.update_fields(**fields)
- def update_fields(self, **fields: t.Any) -> "MessageFilter":
+ def update_fields(self, **fields: t.Any) -> MessageFilter:
for name, value in fields.items():
try:
self.fields[name] = self.from_message_or_type(value)
@@ -1288,9 +1288,7 @@ def update_fields(self, **fields: t.Any) -> "MessageFilter":
return self
@classmethod
- def from_message_or_type(
- cls, message_or_type: "ExpectedMessage"
- ) -> "MessageFilter":
+ def from_message_or_type(cls, message_or_type: ExpectedMessage) -> MessageFilter:
if isinstance(message_or_type, cls):
return message_or_type
if isinstance(message_or_type, protobuf.MessageType):
@@ -1302,7 +1300,7 @@ def from_message_or_type(
raise TypeError("Invalid kind of expected response")
@classmethod
- def from_message(cls, message: protobuf.MessageType) -> "MessageFilter":
+ def from_message(cls, message: protobuf.MessageType) -> MessageFilter:
fields = {}
for field in message.FIELDS.values():
value = getattr(message, field.name)
@@ -1356,7 +1354,7 @@ def to_string(self, maxwidth: int = 80) -> str:
class MessageFilterGenerator:
- def __getattr__(self, key: str) -> t.Callable[..., "MessageFilter"]:
+ def __getattr__(self, key: str) -> t.Callable[..., MessageFilter]:
message_type = getattr(messages, key)
return MessageFilter(message_type).update_fields
@@ -1367,7 +1365,7 @@ def __getattr__(self, key: str) -> t.Callable[..., "MessageFilter"]:
if t.TYPE_CHECKING:
class DebugSession(client.Session[client.TrezorClient, t.Any]):
- test_ctx: "TrezorTestContext"
+ test_ctx: TrezorTestContext
debug: DebugLink
layout_type: LayoutType
@@ -1673,7 +1671,7 @@ def _filter_message(self, msg: protobuf.MessageType) -> protobuf.MessageType:
else:
return msg
- def __enter__(self) -> "TrezorTestContext":
+ def __enter__(self) -> TrezorTestContext:
# For usage in with/expected_responses
if self.in_with_statement:
raise RuntimeError("Do not nest!")
@@ -2098,7 +2096,7 @@ def word_count_repeated_cancel(self) -> Coords:
raise ValueError("Wrong layout type")
# select word component buttons
- def word_check_words(self) -> "list[Coords]":
+ def word_check_words(self) -> list[Coords]:
if self.layout_type in (LayoutType.Bolt, LayoutType.Delizia):
return [
(self._mid(), self._grid(self._height(), 4, 1)),
@@ -2115,7 +2113,7 @@ def word_check_words(self) -> "list[Coords]":
raise ValueError("Wrong layout type")
# vertical menu buttons
- def vertical_menu_items(self) -> "list[Coords]":
+ def vertical_menu_items(self) -> list[Coords]:
if self.layout_type is LayoutType.Delizia:
return [
(self._mid(), self._grid(self._height(), 4, 1)),
@@ -2132,7 +2130,7 @@ def vertical_menu_items(self) -> "list[Coords]":
raise ValueError("Wrong layout type")
# vertical menu buttons
- def vertical_menu_prev_next(self) -> "list[Coords]":
+ def vertical_menu_prev_next(self) -> list[Coords]:
if self.layout_type is LayoutType.Delizia:
return [
(self._left(), self._grid(self._height(), 4, 3)),
@@ -2238,7 +2236,7 @@ class ButtonActions:
def __init__(self, debuglink: DebugLink) -> None:
self.debuglink = debuglink
- def _passphrase_choices(self, char: str) -> "tuple[str, ...]":
+ def _passphrase_choices(self, char: str) -> tuple[str, ...]:
if char in " *#" or char.islower():
if self.debuglink.layout_type is LayoutType.Bolt:
return PASSPHRASE_LOWERCASE_BOLT
@@ -2258,7 +2256,7 @@ def _passphrase_choices(self, char: str) -> "tuple[str, ...]":
else:
return PASSPHRASE_SPECIAL
- def _label_choices(self, char: str) -> "tuple[str, ...]":
+ def _label_choices(self, char: str) -> tuple[str, ...]:
if char in " *#" or char.islower():
if self.debuglink.layout_type is LayoutType.Eckhart:
return LABEL_LOWERCASE_ECKHART
### python/src/trezorlib/device.py
@@ -46,7 +46,7 @@
@workflow(refresh_features=True)
def apply_settings(
- session: "Session",
+ session: Session,
label: str | None = None,
language: str | None = None,
use_passphrase: bool | None = None,
@@ -88,8 +88,8 @@ def apply_settings(
def _send_chunked_data(
- session: "Session",
- request: "messages.DataChunkRequest",
+ session: Session,
+ request: messages.DataChunkRequest,
language_data: bytes,
) -> None:
response = request
@@ -103,7 +103,7 @@ def _send_chunked_data(
@workflow(refresh_features=True)
def change_language(
- session: "Session",
+ session: Session,
language_data: bytes,
show_display: bool | None = None,
) -> None:
@@ -119,33 +119,33 @@ def change_language(
@workflow(refresh_features=True)
-def apply_flags(session: "Session", flags: int) -> None:
+def apply_flags(session: Session, flags: int) -> None:
session.call(messages.ApplyFlags(flags=flags), expect=messages.Success)
@workflow(refresh_features=True)
-def change_pin(session: "Session", remove: bool = False) -> None:
+def change_pin(session: Session, remove: bool = False) -> None:
session.call(messages.ChangePin(remove=remove), expect=messages.Success)
@workflow(refresh_features=True)
-def change_wipe_code(session: "Session", remove: bool = False) -> None:
+def change_wipe_code(session: Session, remove: bool = False) -> None:
session.call(messages.ChangeWipeCode(remove=remove), expect=messages.Success)
@workflow(refresh_features=True)
-def sd_protect(session: "Session", operation: messages.SdProtectOperationType) -> None:
+def sd_protect(session: Session, operation: messages.SdProtectOperationType) -> None:
session.call(messages.SdProtect(operation=operation), expect=messages.Success)
@workflow(invalidate_client=True)
-def wipe(session: "Session") -> None:
+def wipe(session: Session) -> None:
session.call(messages.WipeDevice(), expect=messages.Success)
@workflow(refresh_features=True)
def recover(
- session: "Session",
+ session: Session,
word_count: int = 24,
passphrase_protection: bool = False,
pin_protection: bool = True,
@@ -269,7 +269,7 @@ def _seed_from_entropy(
def reset(
- session: "Session",
+ session: Session,
display_random: bool = False,
strength: int | None = None,
passphrase_protection: bool = False,
@@ -323,7 +323,7 @@ def _get_external_entropy() -> bytes:
@workflow(refresh_features=True)
def setup(
- session: "Session",
+ session: Session,
*,
strength: int | None = None,
passphrase_protection: bool = True,
@@ -437,7 +437,7 @@ def setup(
def _reset_no_entropycheck(
- session: "Session",
+ session: Session,
msg: messages.ResetDevice,
get_entropy: Callable[[], bytes],
) -> None:
@@ -459,7 +459,7 @@ def _reset_no_entropycheck(
def _reset_with_entropycheck(
- session: "Session",
+ session: Session,
reset_msg: messages.ResetDevice,
entropy_check_count: int,
paths: Iterable[Address],
@@ -592,7 +592,7 @@ def verify_entropy_commitment(
@workflow(refresh_features=True)
def backup(
- session: "Session",
+ session: Session,
group_threshold: int | None = None,
groups: Iterable[tuple[int, int]] = (),
backup_method: messages.BackupMethod | None = None,
@@ -611,12 +611,12 @@ def backup(
@workflow()
-def cancel_authorization(session: "Session") -> None:
+def cancel_authorization(session: Session) -> None:
session.call(messages.CancelAuthorization(), expect=messages.Success)
@workflow()
-def unlock_path(session: "Session", n: "Address") -> bytes:
+def unlock_path(session: Session, n: Address) -> bytes:
resp = session.call(
messages.UnlockPath(address_n=n), expect=messages.UnlockedPathRequest
)
@@ -632,7 +632,7 @@ def unlock_path(session: "Session", n: "Address") -> bytes:
@workflow()
def reboot_to_bootloader(
- session: "Session",
+ session: Session,
boot_command: messages.BootCommand = messages.BootCommand.STOP_AND_WAIT,
firmware_header: bytes | None = None,
) -> None:
@@ -646,17 +646,17 @@ def reboot_to_bootloader(
@workflow()
-def show_device_tutorial(session: "Session") -> None:
+def show_device_tutorial(session: Session) -> None:
session.call(messages.ShowDeviceTutorial(), expect=messages.Success)
@workflow()
-def unlock_bootloader(session: "Session") -> None:
+def unlock_bootloader(session: Session) -> None:
session.call(messages.UnlockBootloader(), expect=messages.Success)
@workflow(refresh_features=True)
-def set_busy(session: "Session", expiry_ms: int | None) -> 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.
@@ -671,7 +671,7 @@ def set_busy(session: "Session", expiry_ms: int | None) -> None:
def _fetch_proof_chunks(
- session: "Session",
+ session: Session,
chunk_size: int,
proof_type: messages.AuthenticityProofType,
index: int | None,
@@ -708,7 +708,7 @@ def _fetch_proof_chunks(
@overload
def _fetch_proof_part(
- session: "Session",
+ session: Session,
chunk_size: int,
part: messages.AuthenticityProofType,
signature_size: int,
@@ -717,7 +717,7 @@ def _fetch_proof_part(
@overload
def _fetch_proof_part(
- session: "Session",
+ session: Session,
chunk_size: int,
part: messages.AuthenticityProofType,
signature_size: None,
@@ -726,7 +726,7 @@ def _fetch_proof_part(
def _fetch_proof_part(
- session: "Session",
+ session: Session,
chunk_size: int,
part: messages.AuthenticityProofType,
signature_size: int | None,
@@ -750,7 +750,7 @@ def _fetch_proof_part(
def _fetch_proof(
- session: "Session",
+ session: Session,
chunk_size: int,
sizes: messages.AuthenticityProofSizes,
) -> messages.AuthenticityProof:
@@ -787,7 +787,7 @@ def _fetch_proof(
@workflow()
def authenticate(
- session: "Session", challenge: bytes, chunk_size: int = 1024
+ session: Session, challenge: bytes, chunk_size: int = 1024
) -> messages.AuthenticityProof:
stream = chunk_size > 0
try:
@@ -812,16 +812,16 @@ def authenticate(
@workflow()
-def set_brightness(session: "Session", value: int | None = None) -> None:
+def set_brightness(session: Session, value: int | None = None) -> None:
session.call(messages.SetBrightness(value=value), expect=messages.Success)
@workflow()
-def get_serial_number(session: "Session") -> str:
+def get_serial_number(session: Session) -> str:
ret = session.call(messages.GetSerialNumber(), expect=messages.SerialNumber)
return ret.serial_number
@workflow()
-def get_telemetry(session: "Session") -> messages.Telemetry:
+def get_telemetry(session: Session) -> messages.Telemetry:
return session.call(messages.TelemetryGet(), expect=messages.Telemetry)
### python/src/trezorlib/ethereum.py
@@ -159,8 +159,8 @@ def get_address(*args: Any, **kwargs: Any) -> str:
@workflow(capability=messages.Capability.Ethereum)
def get_authenticated_address(
- session: "Session",
- n: "Address",
+ session: Session,
+ n: Address,
show_display: bool = False,
encoded_network: bytes | None = None,
chunkify: bool = False,
@@ -179,7 +179,7 @@ def get_authenticated_address(
@workflow(capability=messages.Capability.Ethereum)
def get_public_node(
- session: "Session", n: "Address", show_display: bool = False
+ session: Session, n: Address, show_display: bool = False
) -> messages.EthereumPublicKey:
return session.call(
messages.EthereumGetPublicKey(address_n=n, show_display=show_display),
@@ -188,7 +188,7 @@ def get_public_node(
def _answer_definition_request(
- source: "Source",
+ source: Source,
req: messages.EthereumDefinitionRequest,
) -> messages.EthereumDefinitionAck:
"""Answer a firmware `EthereumDefinitionRequest` from `source`."""
@@ -255,7 +255,7 @@ def from_response(cls, msg: messages.EthereumTxRequest) -> Self | None:
def _ethereum_sign_loop(
- session: "Session",
+ session: Session,
msg: messages.EthereumSignTx | messages.EthereumSignTxEIP1559,
data: bytes,
definition_source: Source | None,
@@ -293,8 +293,8 @@ def _ethereum_sign_loop(
@workflow(capability=messages.Capability.Ethereum)
def sign_tx(
- session: "Session",
- n: "Address",
+ session: Session,
+ n: Address,
nonce: int,
gas_price: int,
gas_limit: int,
@@ -344,8 +344,8 @@ def sign_tx(
@workflow(capability=messages.Capability.Ethereum)
def sign_tx_eip1559(
- session: "Session",
- n: "Address",
+ session: Session,
+ n: Address,
*,
nonce: int,
gas_limit: int,
@@ -389,8 +389,8 @@ def sign_tx_eip1559(
@workflow(capability=messages.Capability.Ethereum)
def sign_message(
- session: "Session",
- n: "Address",
+ session: Session,
+ n: Address,
message: AnyStr,
encoded_network: bytes | None = None,
chunkify: bool = False,
@@ -408,8 +408,8 @@ def sign_message(
@workflow(capability=messages.Capability.Ethereum)
def sign_typed_data(
- session: "Session",
- n: "Address",
+ session: Session,
+ n: Address,
data: dict[str, Any],
*,
metamask_v4_compat: bool = True,
@@ -433,7 +433,7 @@ def sign_typed_data(
while isinstance(response, messages.EthereumTypedDataStructRequest):
struct_name = response.name
- members: list["messages.EthereumStructMember"] = []
+ members: list[messages.EthereumStructMember] = []
for field in types[struct_name]:
field_type = get_field_type(field["type"], types)
struct_member = messages.EthereumStructMember(
@@ -486,7 +486,7 @@ def sign_typed_data(
@workflow(capability=messages.Capability.Ethereum)
def verify_message(
- session: "Session",
+ session: Session,
address: str,
signature: bytes,
message: AnyStr,
@@ -509,8 +509,8 @@ def verify_message(
@workflow(capability=messages.Capability.Ethereum)
def sign_typed_data_hash(
- session: "Session",
- n: "Address",
+ session: Session,
+ n: Address,
domain_hash: bytes,
message_hash: bytes | None,
encoded_network: bytes | None = None,
### python/src/trezorlib/fido.py
@@ -28,7 +28,7 @@
@workflow()
def list_credentials(
- session: "Session", batch_size: int | None = 10
+ session: Session, batch_size: int | None = 10
) -> Sequence[messages.WebAuthnCredential]:
creds = []
msg = messages.WebAuthnListResidentCredentials(batch_size=batch_size)
@@ -41,29 +41,29 @@ def list_credentials(
@workflow()
-def add_credential(session: "Session", credential_id: bytes) -> None:
+def add_credential(session: Session, credential_id: bytes) -> None:
session.call(
messages.WebAuthnAddResidentCredential(credential_id=credential_id),
expect=messages.Success,
)
@workflow()
-def remove_credential(session: "Session", index: int) -> None:
+def remove_credential(session: Session, index: int) -> None:
session.call(
messages.WebAuthnRemoveResidentCredential(index=index), expect=messages.Success
)
@workflow()
-def set_counter(session: "Session", u2f_counter: int) -> None:
+def set_counter(session: Session, u2f_counter: int) -> None:
session.call(
messages.SetU2FCounter(u2f_counter=u2f_counter), expect=messages.Success
)
@workflow()
-def get_next_counter(session: "Session") -> int:
+def get_next_counter(session: Session) -> int:
return session.call(
messages.GetNextU2FCounter(), expect=messages.NextU2FCounter
).u2f_counter
### python/src/trezorlib/misc.py
@@ -27,13 +27,13 @@
@workflow(capability=messages.Capability.Crypto)
-def get_entropy(session: "Session", size: int) -> bytes:
+def get_entropy(session: Session, size: int) -> bytes:
return session.call(messages.GetEntropy(size=size), expect=messages.Entropy).entropy
@workflow(capability=messages.Capability.Crypto)
def sign_identity(
- session: "Session",
+ session: Session,
identity: messages.IdentityType,
challenge_hidden: bytes,
challenge_visual: str,
@@ -52,7 +52,7 @@ def sign_identity(
@workflow(capability=messages.Capability.Crypto)
def get_ecdh_session_key(
- session: "Session",
+ session: Session,
identity: messages.IdentityType,
peer_public_key: bytes,
ecdsa_curve_name: str | None = None,
@@ -69,8 +69,8 @@ def get_ecdh_session_key(
@workflow(capability=messages.Capability.Crypto)
def encrypt_keyvalue(
- session: "Session",
- n: "Address",
+ session: Session,
+ n: Address,
key: str,
value: bytes,
ask_on_encrypt: bool = True,
@@ -93,8 +93,8 @@ def encrypt_keyvalue(
@workflow(capability=messages.Capability.Crypto)
def decrypt_keyvalue(
- session: "Session",
- n: "Address",
+ session: Session,
+ n: Address,
key: str,
value: bytes,
ask_on_encrypt: bool = True,
@@ -116,13 +116,13 @@ def decrypt_keyvalue(
@workflow(capability=messages.Capability.Crypto)
-def get_nonce(session: "Session") -> bytes:
+def get_nonce(session: Session) -> bytes:
return session.call(messages.GetNonce(), expect=messages.Nonce).nonce
@workflow()
def payment_notification(
- session: "Session", payment_req: messages.PaymentRequest
+ session: Session, payment_req: messages.PaymentRequest
) -> None:
session.call(
messages.PaymentNotification(payment_req=payment_req), expect=messages.Success
### python/src/trezorlib/protobuf.py
@@ -477,7 +477,7 @@ def load_message(reader: Reader, msg_type: type[MT]) -> MT:
return msg_type(**msg_dict)
-def dump_message(writer: Writer, msg: "MessageType") -> None:
+def dump_message(writer: Writer, msg: MessageType) -> None:
repvalue = [0]
mtype = msg.__class__
@@ -547,7 +547,7 @@ def dump_message(writer: Writer, msg: "MessageType") -> None:
def format_message(
- pb: "MessageType",
+ pb: MessageType,
indent: int = 0,
sep: str = " " * 4,
truncate_after: int | None = 256,
@@ -670,7 +670,7 @@ def dict_to_proto(message_type: type[MT], d: dict[str, t.Any]) -> MT:
return message_type(**params)
-def to_dict(msg: "MessageType", hexlify_bytes: bool = True) -> dict[str, t.Any]:
+def to_dict(msg: MessageType, hexlify_bytes: bool = True) -> dict[str, t.Any]:
def convert_value(value: t.Any) -> t.Any:
if hexlify_bytes and isinstance(value, bytes):
return value.hex()
### python/src/trezorlib/ripple.py
@@ -37,8 +37,8 @@ def get_address(*args: Any, **kwargs: Any) -> str:
@workflow(capability=messages.Capability.Ripple)
def get_authenticated_address(
- session: "Session",
- address_n: "Address",
+ session: Session,
+ address_n: Address,
show_display: bool = False,
chunkify: bool = False,
) -> messages.RippleAddress:
@@ -52,8 +52,8 @@ def get_authenticated_address(
@workflow(capability=messages.Capability.Ripple)
def sign_tx(
- session: "Session",
- address_n: "Address",
+ session: Session,
+ address_n: Address,
msg: messages.RippleSignTx,
chunkify: bool = False,
payment_req: messages.PaymentRequest | None = None,
### python/src/trezorlib/solana.py
@@ -27,7 +27,7 @@
@workflow(capability=messages.Capability.Solana)
def get_public_key(
- session: "Session",
+ session: Session,
address_n: list[int],
show_display: bool,
) -> bytes:
@@ -43,7 +43,7 @@ def get_address(*args: Any, **kwargs: Any) -> str:
@workflow(capability=messages.Capability.Solana)
def get_authenticated_address(
- session: "Session",
+ session: Session,
address_n: list[int],
show_display: bool,
chunkify: bool = False,
@@ -60,7 +60,7 @@ def get_authenticated_address(
@workflow(capability=messages.Capability.Solana)
def sign_tx(
- session: "Session",
+ session: Session,
address_n: list[int],
serialized_tx: bytes,
additional_info: messages.SolanaTxAdditionalInfo | None,
@@ -81,7 +81,7 @@ def sign_tx(
@workflow(capability=messages.Capability.Solana)
def sign_message(
- session: "Session",
+ session: Session,
address_n: list[int],
message: messages.SolanaOffchainMessageV1,
chunkify: bool = False,
@@ -96,7 +96,7 @@ def sign_message(
@workflow(capability=messages.Capability.Solana)
def verify_message(
- session: "Session",
+ session: Session,
message: messages.SolanaOffchainMessageV1,
signatures: list[bytes],
chunkify: bool = False,
### python/src/trezorlib/testing/common.py
@@ -31,7 +31,7 @@
PRIVATE_KEYS_DEV = [byte * 32 for byte in (b"\xdd", b"\xde", b"\xdf")]
-def get_text_possible_pagination(debug: "DebugLink", br: messages.ButtonRequest) -> str:
+def get_text_possible_pagination(debug: DebugLink, br: messages.ButtonRequest) -> str:
"""
Read all text content from the device, handling possible pagination.
@@ -55,7 +55,7 @@ def get_text_possible_pagination(debug: "DebugLink", br: messages.ButtonRequest)
def swipe_if_necessary(
- debug: "DebugLink",
+ debug: DebugLink,
br_code: messages.ButtonRequestType | None = None,
br_name: str | None = None,
) -> BRGeneratorType:
@@ -77,7 +77,7 @@ def swipe_if_necessary(
swipe_till_the_end(debug, br)
-def swipe_till_the_end(debug: "DebugLink", br: messages.ButtonRequest) -> None:
+def swipe_till_the_end(debug: DebugLink, br: messages.ButtonRequest) -> None:
"""
Swipe through all pages until the end.
### python/src/trezorlib/testing/device_handler.py
@@ -79,7 +79,7 @@ class BackgroundDeviceHandler:
_pool = ThreadPoolExecutor()
- def __init__(self, client: "Client", nowait: bool = False) -> None:
+ def __init__(self, client: Client, nowait: bool = False) -> None:
"""
Initialize the handler with a client.
@@ -91,7 +91,7 @@ def __init__(self, client: "Client", nowait: bool = False) -> None:
self.task = None
self.nowait = nowait
- def _configure_client(self, client: "Client") -> None:
+ def _configure_client(self, client: Client) -> None:
"""
Configure the client for background handling and set up the mock UI.
@@ -118,7 +118,7 @@ def get_session(self, *args: t.Any, **kwargs: t.Any) -> None:
def run_with_session(
self,
- function: t.Callable[tx.Concatenate["Session", P], t.Any],
+ function: t.Callable[tx.Concatenate[Session, P], t.Any],
seedless: bool = False,
*args: P.args,
**kwargs: P.kwargs,
@@ -153,8 +153,8 @@ def task_function(*args: t.Any, **kwargs: t.Any) -> t.Any:
def run_with_provided_session(
self,
- session: "Session",
- function: t.Callable[tx.Concatenate["Session", P], t.Any],
+ session: Session,
+ function: t.Callable[tx.Concatenate[Session, P], t.Any],
*args: P.args,
**kwargs: P.kwargs,
) -> None:
@@ -196,7 +196,7 @@ def kill_task(self) -> None:
pass
self.task = None
- def restart(self, emulator: "Emulator") -> None:
+ def restart(self, emulator: Emulator) -> None:
"""
Restart the emulator and reconfigure the client.
@@ -228,7 +228,7 @@ def result(self, timeout: float | None = None) -> t.Any:
finally:
self.task = None
- def features(self) -> "Features":
+ def features(self) -> Features:
"""
Refresh and return the client's features.
@@ -243,7 +243,7 @@ def features(self) -> "Features":
self.client.refresh_features()
return self.client.features
- def debuglink(self) -> "DebugLink":
+ def debuglink(self) -> DebugLink:
"""
Get the debuglink for the client.
@@ -264,7 +264,7 @@ def check_finalize(self) -> bool:
return False
return True
- def __enter__(self) -> "BackgroundDeviceHandler":
+ def __enter__(self) -> BackgroundDeviceHandler:
"""
Enter the context manager.
### python/src/trezorlib/thp/pairing.py
@@ -146,7 +146,7 @@ def channel(self) -> Channel:
return self.client.channel
@property
- def methods(self) -> t.Collection[type["PairingMethod"]]:
+ def methods(self) -> t.Collection[type[PairingMethod]]:
return {
m
for m in PairingMethod.METHODS_AVAILABLE
### python/src/trezorlib/transport/bridge.py
@@ -73,7 +73,7 @@ def supports_protocolV2() -> bool:
class BridgeHandle:
- def __init__(self, transport: "BridgeTransport") -> None:
+ def __init__(self, transport: BridgeTransport) -> None:
self.transport = transport
def read_buf(self, timeout: float | None = None) -> bytes:
@@ -95,7 +95,7 @@ def read_buf(self, timeout: float | None = None) -> bytes:
class BridgeHandleLegacy(BridgeHandle):
- def __init__(self, transport: "BridgeTransport") -> None:
+ def __init__(self, transport: BridgeTransport) -> None:
super().__init__(transport)
self.request: str | None = None
@@ -165,7 +165,7 @@ def _call(
@classmethod
def enumerate(
cls, models: t.Iterable[TrezorModel] | None = None
- ) -> t.Iterable["BridgeTransport"]:
+ ) -> t.Iterable[BridgeTransport]:
try:
legacy = is_legacy_bridge()
return [
### python/src/trezorlib/transport/hid.py
@@ -61,13 +61,13 @@ def get_path(self) -> str:
@classmethod
def enumerate(
- cls, models: t.Iterable["TrezorModel"] | None = None, debug: bool = False
- ) -> t.Iterable["HidTransport"]:
+ cls, models: t.Iterable[TrezorModel] | None = None, debug: bool = False
+ ) -> t.Iterable[HidTransport]:
if models is None:
models = {TREZOR_ONE}
usb_ids = [id for model in models for id in model.usb_ids]
- devices: list["HidTransport"] = []
+ devices: list[HidTransport] = []
for dev in hid.enumerate(0, 0):
usb_id = (dev["vendor_id"], dev["product_id"])
if usb_id not in usb_ids:
@@ -81,7 +81,7 @@ def enumerate(
devices.append(HidTransport(dev))
return devices
- def find_debug(self) -> "HidTransport":
+ def find_debug(self) -> HidTransport:
# For v1 protocol, find debug USB interface for the same serial number
for debug in HidTransport.enumerate(debug=True):
if debug.device["serial_number"] == self.device["serial_number"]:
### python/src/trezorlib/transport/udp.py
@@ -80,7 +80,7 @@ def __init__(self, device: str | None = None) -> None:
super().__init__()
@classmethod
- def _try_path(cls, path: str) -> "UdpTransport":
+ def _try_path(cls, path: str) -> UdpTransport:
d = cls(path)
try:
d.open()
@@ -98,16 +98,16 @@ def _try_path(cls, path: str) -> "UdpTransport":
@classmethod
def enumerate(
- cls, models: Iterable["TrezorModel"] | None = None
- ) -> Iterable["UdpTransport"]:
+ cls, models: Iterable[TrezorModel] | None = None
+ ) -> Iterable[UdpTransport]:
default_path = f"{cls.DEFAULT_HOST}:{cls.DEFAULT_PORT}"
try:
return [cls._try_path(default_path)]
except TransportException:
return []
@classmethod
- def find_by_path(cls, path: str, prefix_search: bool = False) -> "UdpTransport":
+ def find_by_path(cls, path: str, prefix_search: bool = False) -> UdpTransport:
try:
address = path.replace(f"{cls.PATH_PREFIX}:", "")
return cls._try_path(address)
@@ -155,7 +155,7 @@ def read_chunk(self, *, timeout: float | None = None) -> bytes:
raise TransportException(f"Unexpected chunk size: {len(chunk)}")
return chunk
- def find_debug(self) -> "UdpTransport":
+ def find_debug(self) -> UdpTransport:
host, port = self.device
return UdpTransport(f"{host}:{port + 1}")
### python/src/trezorlib/transport/webusb.py
@@ -57,7 +57,7 @@ class WebUsbTransport(Transport):
def __init__(
self,
- device: "usb1.USBDevice",
+ device: usb1.USBDevice,
debug: bool = False,
) -> None:
@@ -72,8 +72,8 @@ def __init__(
@classmethod
def enumerate(
- cls, models: Iterable["TrezorModel"] | None = None, usb_reset: bool = False
- ) -> Iterable["WebUsbTransport"]:
+ cls, models: Iterable[TrezorModel] | None = None, usb_reset: bool = False
+ ) -> Iterable[WebUsbTransport]:
if cls.context is None:
cls.context = usb1.USBContext()
cls.context.open()
@@ -82,7 +82,7 @@ def enumerate(
if models is None:
models = ALL_MODELS
usb_ids = [id for model in models for id in model.usb_ids]
- devices: list["WebUsbTransport"] = []
+ devices: list[WebUsbTransport] = []
for dev in cls.context.getDeviceIterator(skip_on_error=True):
usb_id = (dev.getVendorID(), dev.getProductID())
if usb_id not in usb_ids:
@@ -177,7 +177,7 @@ def read_chunk(self, *, timeout: float | None = None) -> bytes:
except Exception as e:
raise TransportException(f"USB read failed: {e}") from e
- def find_debug(self) -> "WebUsbTransport":
+ def find_debug(self) -> WebUsbTransport:
# For v1 protocol, find debug USB interface for the same serial number
return self.__class__(self.device, debug=True)
### tests/click_tests/common.py
@@ -96,7 +96,7 @@ def get_char_category(char: str) -> KeyboardCategory:
return KeyboardCategory.Special
-def go_next(debug: "DebugLink") -> LayoutContent:
+def go_next(debug: DebugLink) -> LayoutContent:
if debug.layout_type in (LayoutType.Bolt, LayoutType.Eckhart):
debug.click(debug.screen_buttons.ok())
elif debug.layout_type is LayoutType.Caesar:
@@ -108,7 +108,7 @@ def go_next(debug: "DebugLink") -> LayoutContent:
return debug.read_layout()
-def go_back(debug: "DebugLink", r_middle: bool = False) -> LayoutContent:
+def go_back(debug: DebugLink, r_middle: bool = False) -> LayoutContent:
if debug.layout_type in (LayoutType.Bolt, LayoutType.Delizia, LayoutType.Eckhart):
debug.click(debug.screen_buttons.cancel())
elif debug.layout_type is LayoutType.Caesar:
@@ -122,7 +122,7 @@ def go_back(debug: "DebugLink", r_middle: bool = False) -> LayoutContent:
def navigate_to_action_and_press(
- debug: "DebugLink",
+ debug: DebugLink,
wanted_action: str,
all_actions: AllActionsType,
is_carousel: bool = True,
@@ -163,7 +163,7 @@ def _carousel_steps(current_index: int, wanted_index: int, length: int) -> int:
return steps_forward if steps_forward <= steps_backward else -steps_backward
-def unlock_gesture(debug: "DebugLink") -> LayoutContent:
+def unlock_gesture(debug: DebugLink) -> LayoutContent:
if debug.layout_type in (LayoutType.Bolt, LayoutType.Eckhart):
debug.click(debug.screen_buttons.ok())
elif debug.layout_type is LayoutType.Caesar:
@@ -202,7 +202,7 @@ def keyboard_categories(layout_type: LayoutType) -> list[KeyboardCategory]:
raise ValueError("Wrong layout type")
-def get_category(debug: "DebugLink") -> KeyboardCategory:
+def get_category(debug: DebugLink) -> KeyboardCategory:
category = debug.read_layout().find_unique_value_by_key(
"active_layout", default="", only_type=str
)
@@ -213,7 +213,7 @@ def get_category(debug: "DebugLink") -> KeyboardCategory:
def go_to_category(
- debug: "DebugLink", category: KeyboardCategory, verify_layout: bool = False
+ debug: DebugLink, category: KeyboardCategory, verify_layout: bool = False
) -> None:
"""
Go to a specific category on the passphrase/label keyboard.
@@ -247,7 +247,7 @@ def go_to_category(
COORDS_PREV = (0, 0) # type: ignore
-def press_char(debug: "DebugLink", char: str) -> None:
+def press_char(debug: DebugLink, char: str) -> None:
"""Press a character on the passphrase/label keyboard."""
global COORDS_PREV
@@ -271,6 +271,6 @@ def press_char(debug: "DebugLink", char: str) -> None:
debug.click(coords)
-def delete_char(debug: "DebugLink") -> None:
+def delete_char(debug: DebugLink) -> None:
"""Deletes the last char"""
debug.click(debug.screen_buttons.pin_passphrase_erase())
### tests/click_tests/device_menu/common.py
@@ -226,7 +226,7 @@ def device_content():
content.extend([TR.regulatory__title, TR.words__about, TR.wipe__title])
return content
- lookup: dict["Menu", Callable[[], list[str] | None]] = {
+ lookup: dict[Menu, Callable[[], list[str] | None]] = {
Menu.ROOT: root_content,
Menu.PAIR_AND_CONNECT: connection_content,
Menu.SETTINGS: settings_content,
### tests/common.py
@@ -82,7 +82,7 @@
MOCK_GET_ENTROPY = mock.Mock(return_value=EXTERNAL_ENTROPY)
-def parametrize_using_common_fixtures(*paths: str) -> "MarkDecorator":
+def parametrize_using_common_fixtures(*paths: str) -> MarkDecorator:
fixtures = []
for path in paths:
fixtures.append(json.loads((COMMON_FIXTURES_DIR / path).read_text()))
@@ -171,8 +171,8 @@ def generate_entropy(
def click_through(
- debug: "DebugLink", screens: int, code: messages.ButtonRequestType | None = None
-) -> Generator[None, "ButtonRequest", None]:
+ debug: DebugLink, screens: int, code: messages.ButtonRequestType | None = None
+) -> Generator[None, ButtonRequest, None]:
"""Click through N dialog screens.
For use in an input flow function.
@@ -193,8 +193,8 @@ def input_flow():
def read_and_confirm_mnemonic(
- debug: "DebugLink", choose_wrong: bool = False
-) -> Generator[None, "ButtonRequest", str | None]:
+ debug: DebugLink, choose_wrong: bool = False
+) -> 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.
@@ -224,8 +224,8 @@ def input_flow():
def read_mnemonic_from_screen_bolt(
- debug: "DebugLink",
-) -> Generator[None, "ButtonRequest", list[str]]:
+ debug: DebugLink,
+) -> Generator[None, ButtonRequest, list[str]]:
mnemonic: list[str] = []
br = yield
assert br.pages is not None
@@ -242,8 +242,8 @@ def read_mnemonic_from_screen_bolt(
def read_mnemonic_from_screen_caesar(
- debug: "DebugLink",
-) -> Generator[None, "ButtonRequest", list[str]]:
+ debug: DebugLink,
+) -> Generator[None, ButtonRequest, list[str]]:
mnemonic: list[str] = []
yield # write down all 12 words in order
debug.press_yes()
@@ -262,8 +262,8 @@ def read_mnemonic_from_screen_caesar(
def read_mnemonic_from_screen_delizia(
- debug: "DebugLink",
-) -> Generator[None, "ButtonRequest", list[str]]:
+ debug: DebugLink,
+) -> Generator[None, ButtonRequest, list[str]]:
mnemonic: list[str] = []
br = yield
assert br.pages is not None
@@ -283,8 +283,8 @@ def read_mnemonic_from_screen_delizia(
def read_mnemonic_from_screen_eckhart(
- debug: "DebugLink",
-) -> Generator[None, "ButtonRequest", list[str]]:
+ debug: DebugLink,
+) -> Generator[None, ButtonRequest, list[str]]:
mnemonic: list[str] = []
br = yield
assert br.pages is not None
@@ -306,7 +306,7 @@ def read_mnemonic_from_screen_eckhart(
def check_share(
- debug: "DebugLink", mnemonic: list[str], choose_wrong: bool = False
+ debug: DebugLink, mnemonic: list[str], choose_wrong: bool = False
) -> bool:
"""
Given the mnemonic word list, proceed with the backup check:
@@ -340,14 +340,14 @@ def check_share(
return True
-def click_info_button_bolt(debug: "DebugLink") -> Generator[Any, Any, ButtonRequest]:
+def click_info_button_bolt(debug: DebugLink) -> Generator[Any, Any, ButtonRequest]:
"""Click Shamir backup info button and return back."""
debug.press_info()
debug.press_yes()
return (yield)
-def click_info_button_delizia_eckhart(debug: "DebugLink"):
+def click_info_button_delizia_eckhart(debug: DebugLink):
"""Click Shamir backup info button, scroll through it and return back."""
debug.click(debug.screen_buttons.menu())
layout = debug.read_layout()
@@ -376,7 +376,7 @@ def check_pin_backoff_time(attempts: int, start: float) -> None:
assert got >= expected
-def get_test_address(session: "Session") -> str:
+def get_test_address(session: Session) -> str:
"""Fetch a testnet address on a fixed path. Useful to make a pin/passphrase
protected call, or to identify the root secret (seed+passphrase)"""
return btc.get_address(session, "Testnet", TEST_ADDRESS_N)
### tests/conftest.py
@@ -152,7 +152,7 @@ def core_emulator(
@pytest.fixture(scope="session")
def emulator(
tropic_model_port: int | None, request: pytest.FixtureRequest
-) -> t.Generator["Emulator", None, None]:
+) -> t.Generator[Emulator, None, None]:
"""Fixture for getting emulator connection in case tests should operate it on their own.
Is responsible for starting it at the start of the session and stopping
@@ -541,7 +541,7 @@ def pytest_sessionfinish(session: pytest.Session, exitstatus: pytest.ExitCode) -
def pytest_terminal_summary(
- terminalreporter: "TerminalReporter", exitstatus: pytest.ExitCode, config: "Config"
+ terminalreporter: TerminalReporter, exitstatus: pytest.ExitCode, config: Config
) -> None:
println = terminalreporter.write_line
println("")
@@ -556,7 +556,7 @@ def pytest_terminal_summary(
)
-def pytest_addoption(parser: "Parser") -> None:
+def pytest_addoption(parser: Parser) -> None:
parser.addoption(
"--ui",
action="store",
@@ -618,7 +618,7 @@ def pytest_addoption(parser: "Parser") -> None:
)
-def pytest_configure(config: "Config") -> None:
+def pytest_configure(config: Config) -> None:
"""Called at testsuite setup time.
Registers known markers, enables verbose output if requested.
### tests/input_flows.py
@@ -1985,7 +1985,7 @@ def input_flow_common(self) -> BRGeneratorType:
yield from self.ETH.confirm_tx_staking(info=True)
-def get_mnemonic(debug: DebugLink) -> Generator[None, "messages.ButtonRequest", str]:
+def get_mnemonic(debug: DebugLink) -> Generator[None, messages.ButtonRequest, str]:
"""Used for BIP39 or SLIP-39 1-of-1 backup."""
# mnemonic phrases
[mnemonic] = yield from load_N_shares(debug, n=1)
@@ -2177,7 +2177,7 @@ def load_N_shares(
debug: DebugLink,
n: int,
method: messages.BackupMethod = messages.BackupMethod.Display,
-) -> Generator[None, "messages.ButtonRequest", list[str]]:
+) -> Generator[None, messages.ButtonRequest, list[str]]:
mnemonics: list[str] = []
for _ in range(n):
@@ -2213,7 +2213,7 @@ def load_N_groups(
debug: DebugLink,
groups: Sequence[tuple[int, int]],
method: messages.BackupMethod = messages.BackupMethod.Display,
-) -> Generator[None, "messages.ButtonRequest", list[list[str]]]:
+) -> Generator[None, messages.ButtonRequest, list[list[str]]]:
mnemonics: list[list[str]] = []
expected_br_name = "success_share_confirm"
if debug.layout_type is LayoutType.Eckhart:
@@ -2619,7 +2619,7 @@ def input_flow_common(self) -> BRGeneratorType:
def load_5_groups_5_shares(
debug: DebugLink,
backup_method: messages.BackupMethod = messages.BackupMethod.Display,
-) -> Generator[None, "messages.ButtonRequest", list[str]]:
+) -> Generator[None, messages.ButtonRequest, list[str]]:
mnemonics: list[str] = []
for _g in range(5):
@@ -4153,7 +4153,7 @@ class InputFlowConfirmAllWarnings(InputFlowBase):
def __init__(
self,
client: Client | DebugSession,
- on_page: Callable[["LayoutContent"], None] | None = None,
+ on_page: Callable[[LayoutContent], None] | None = None,
) -> None:
super().__init__(client)
self.on_page = on_page
### tests/prodtest_tests/tropic_utils.py
@@ -54,7 +54,7 @@ def __init__(self, raw: dict[str, t.Any]) -> None:
self.raw = raw
@classmethod
- def from_file(cls, path: Path | str) -> "TropicModelState":
+ def from_file(cls, path: Path | str) -> TropicModelState:
path = Path(path)
assert path.exists(), (
f"Tropic model output file was not generated: {path}. "
### tests/upgrade_tests/test_firmware_upgrades.py
@@ -87,7 +87,7 @@ def wrapper(*args, **kwargs):
return wrapper
-def _get_session(client: "Client", passphrase: str | None = "") -> "Session":
+def _get_session(client: Client, passphrase: str | None = "") -> Session:
# For now, just use the standard get_session method
# The special handling for protocol v1 < 2.3.0 is no longer needed
return client.get_session(passphrase=passphrase)
@@ -100,7 +100,7 @@ def test_upgrade_load(
model: str | None,
shared_profile_dir: str,
) -> None:
- def asserts(client: "Client"):
+ def asserts(client: Client):
client.refresh_features()
assert not client.features.pin_protection
assert not client.features.passphrase_protection
@@ -145,7 +145,7 @@ def test_upgrade_load_pin(
) -> None:
PIN = "1234"
- def asserts(client: "Client") -> None:
+ def asserts(client: Client) -> None:
assert client.features.pin_protection
assert not client.features.passphrase_protection
assert client.features.initialized
@@ -198,7 +198,7 @@ def test_storage_upgrade_progressive(
):
PIN = "1234"
- def asserts(client: "Client") -> None:
+ def asserts(client: Client) -> None:
assert client.features.pin_protection
assert not client.features.passphrase_protection
assert client.features.initialized
@@ -250,7 +250,7 @@ def test_upgrade_wipe_code(
PIN = "1234"
WIPE_CODE = "4321"
- def asserts(client: "Client"):
+ def asserts(client: Client):
assert client.features.pin_protection
assert not client.features.passphrase_protection
assert client.features.initialized
@@ -307,7 +307,7 @@ def test_upgrade_reset(
model: str | None,
shared_profile_dir: str,
):
- def asserts(client: "Client"):
+ def asserts(client: Client):
assert not client.features.pin_protection
assert not client.features.passphrase_protection
assert client.features.initialized
@@ -352,7 +352,7 @@ def test_upgrade_reset_skip_backup(
model: str | None,
shared_profile_dir: str,
):
- def asserts(client: "Client"):
+ def asserts(client: Client):
assert not client.features.pin_protection
assert not client.features.passphrase_protection
assert client.features.initialized
@@ -398,7 +398,7 @@ def test_upgrade_reset_no_backup(
model: str | None,
shared_profile_dir: str,
):
- def asserts(client: "Client"):
+ def asserts(client: Client):
assert not client.features.pin_protection
assert not client.features.passphrase_protection
assert client.features.initializedWhy 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.