From edc2add85ea8225b5c27ec1562eb684b6e8e1b0c Mon Sep 17 00:00:00 2001 From: matejcik Date: Tue, 15 Aug 2023 17:56:09 +0200 Subject: [PATCH] style(core): apply isort 5 [no changelog] --- core/src/apps/base.py | 19 +++++++++--------- core/src/apps/binance/get_address.py | 3 ++- core/src/apps/binance/get_public_key.py | 1 + core/src/apps/binance/helpers.py | 2 +- core/src/apps/binance/sign_tx.py | 5 +++-- core/src/apps/bitcoin/addresses.py | 6 ++++-- core/src/apps/bitcoin/authorization.py | 1 + core/src/apps/bitcoin/authorize_coinjoin.py | 1 + core/src/apps/bitcoin/common.py | 6 ++++-- core/src/apps/bitcoin/get_address.py | 5 +++-- core/src/apps/bitcoin/get_ownership_id.py | 3 ++- core/src/apps/bitcoin/get_ownership_proof.py | 4 +++- core/src/apps/bitcoin/keychain.py | 16 +++++++-------- core/src/apps/bitcoin/multisig.py | 2 ++ core/src/apps/bitcoin/ownership.py | 17 ++++++++-------- core/src/apps/bitcoin/scripts.py | 3 ++- core/src/apps/bitcoin/scripts_decred.py | 3 ++- core/src/apps/bitcoin/sign_message.py | 2 +- core/src/apps/bitcoin/sign_tx/__init__.py | 11 +++++----- core/src/apps/bitcoin/sign_tx/approvers.py | 4 ++-- core/src/apps/bitcoin/sign_tx/bitcoin.py | 13 +++--------- core/src/apps/bitcoin/sign_tx/bitcoinlike.py | 3 +++ core/src/apps/bitcoin/sign_tx/decred.py | 16 +++++---------- core/src/apps/bitcoin/sign_tx/helpers.py | 5 +++-- core/src/apps/bitcoin/sign_tx/layout.py | 5 +++-- core/src/apps/bitcoin/sign_tx/matchcheck.py | 1 + core/src/apps/bitcoin/sign_tx/omni.py | 1 + .../apps/bitcoin/sign_tx/payment_request.py | 3 +++ core/src/apps/bitcoin/sign_tx/progress.py | 2 ++ core/src/apps/bitcoin/sign_tx/sig_hasher.py | 6 +++++- core/src/apps/bitcoin/sign_tx/tx_info.py | 14 ++++++------- core/src/apps/bitcoin/sign_tx/zcash_v4.py | 13 ++++++++---- core/src/apps/bitcoin/verification.py | 4 +++- core/src/apps/bitcoin/verify_message.py | 15 ++++++++------ core/src/apps/bitcoin/writers.py | 7 +------ core/src/apps/cardano/addresses.py | 2 ++ core/src/apps/cardano/auxiliary_data.py | 2 +- core/src/apps/cardano/certificates.py | 1 + core/src/apps/cardano/get_address.py | 7 ++++--- .../apps/cardano/get_native_script_hash.py | 3 ++- core/src/apps/cardano/get_public_key.py | 5 ++++- .../cardano/helpers/account_path_check.py | 2 +- .../helpers/hash_builder_collection.py | 1 + core/src/apps/cardano/helpers/utils.py | 4 +++- core/src/apps/cardano/native_script.py | 7 +++++-- core/src/apps/cardano/seed.py | 13 ++++++------ core/src/apps/cardano/sign_tx/__init__.py | 3 ++- .../apps/cardano/sign_tx/ordinary_signer.py | 6 +----- core/src/apps/cardano/sign_tx/signer.py | 4 +++- core/src/apps/common/address_mac.py | 1 + core/src/apps/common/cbor.py | 1 + core/src/apps/common/keychain.py | 11 +++------- core/src/apps/common/paths.py | 11 ++-------- core/src/apps/common/request_pin.py | 4 ++-- core/src/apps/common/seed.py | 3 ++- core/src/apps/debug/__init__.py | 20 ++++++++----------- core/src/apps/debug/load_device.py | 5 +++-- core/src/apps/eos/actions/__init__.py | 5 +++-- core/src/apps/eos/actions/layout.py | 2 ++ core/src/apps/eos/get_public_key.py | 3 +++ core/src/apps/eos/sign_tx.py | 11 ++++++---- core/src/apps/eos/writers.py | 2 +- core/src/apps/ethereum/definitions.py | 4 +++- core/src/apps/ethereum/get_address.py | 5 ++++- core/src/apps/ethereum/get_public_key.py | 2 ++ core/src/apps/ethereum/helpers.py | 2 ++ core/src/apps/ethereum/keychain.py | 7 +------ core/src/apps/ethereum/layout.py | 6 +++++- core/src/apps/ethereum/sign_message.py | 6 ++---- core/src/apps/ethereum/sign_tx.py | 15 +++++++------- core/src/apps/ethereum/sign_tx_eip1559.py | 14 ++++++++----- core/src/apps/ethereum/sign_typed_data.py | 17 +++++++++------- core/src/apps/ethereum/verify_message.py | 2 +- core/src/apps/homescreen/__init__.py | 2 +- core/src/apps/management/apply_flags.py | 5 ++--- core/src/apps/management/apply_settings.py | 14 ++++++------- core/src/apps/management/change_wipe_code.py | 17 ++++++++-------- .../apps/management/get_next_u2f_counter.py | 2 +- .../apps/management/reboot_to_bootloader.py | 3 ++- .../management/recovery_device/__init__.py | 5 +++-- .../management/recovery_device/homescreen.py | 10 ++++++---- .../apps/management/recovery_device/layout.py | 9 ++++++--- .../recovery_device/word_validity.py | 1 + .../apps/management/reset_device/__init__.py | 16 +++++++-------- core/src/apps/management/sd_protect.py | 1 + core/src/apps/management/wipe_device.py | 2 +- core/src/apps/misc/cipher_key_value.py | 9 +++++---- core/src/apps/misc/cosi_commit.py | 1 + core/src/apps/misc/get_ecdh_session_key.py | 18 +++++++++-------- core/src/apps/misc/get_entropy.py | 2 +- core/src/apps/misc/get_firmware_hash.py | 8 ++++---- core/src/apps/misc/sign_identity.py | 8 ++++++-- core/src/apps/monero/get_address.py | 2 +- core/src/apps/monero/get_tx_keys.py | 3 ++- core/src/apps/monero/get_watch_only.py | 3 ++- core/src/apps/monero/key_image_sync.py | 14 ++++++------- core/src/apps/monero/layout.py | 8 +++----- core/src/apps/monero/live_refresh.py | 14 ++++++++----- core/src/apps/monero/misc.py | 7 ++++--- core/src/apps/monero/sign_tx.py | 5 ++++- .../apps/monero/signing/offloading_keys.py | 4 ++++ core/src/apps/monero/signing/state.py | 8 +++++--- .../signing/step_01_init_transaction.py | 12 +++++------ .../apps/monero/signing/step_02_set_input.py | 11 ++++++---- .../apps/monero/signing/step_04_input_vini.py | 8 +++++--- .../monero/signing/step_05_all_inputs_set.py | 7 +++++-- .../apps/monero/signing/step_06_set_output.py | 13 ++++++------ .../monero/signing/step_07_all_outputs_set.py | 6 ++++-- .../apps/monero/signing/step_09_sign_input.py | 16 +++++++++------ .../apps/monero/signing/step_10_sign_final.py | 7 ++++--- core/src/apps/monero/xmr/addresses.py | 6 ++++-- core/src/apps/monero/xmr/bulletproof.py | 2 +- core/src/apps/monero/xmr/clsag.py | 4 +++- core/src/apps/monero/xmr/credentials.py | 4 +++- core/src/apps/monero/xmr/keccak_hasher.py | 1 + core/src/apps/monero/xmr/key_image.py | 4 +++- core/src/apps/monero/xmr/mlsag_hasher.py | 1 + core/src/apps/monero/xmr/range_signatures.py | 4 +--- .../monero/xmr/serialize/message_types.py | 4 ++-- core/src/apps/nem/get_address.py | 5 ++++- core/src/apps/nem/helpers.py | 1 + core/src/apps/nem/mosaic/layout.py | 1 + core/src/apps/nem/multisig/layout.py | 1 + core/src/apps/nem/multisig/serialize.py | 1 + core/src/apps/nem/sign_tx.py | 5 +++-- core/src/apps/nem/transfer/__init__.py | 2 +- core/src/apps/nem/transfer/layout.py | 5 ++++- core/src/apps/nem/transfer/serialize.py | 8 +++----- core/src/apps/nem/validators.py | 9 +++------ core/src/apps/ripple/get_address.py | 5 ++++- core/src/apps/ripple/sign_tx.py | 5 ++++- core/src/apps/stellar/consts.py | 3 +-- core/src/apps/stellar/get_address.py | 7 +++++-- core/src/apps/stellar/layout.py | 1 - core/src/apps/stellar/operations/__init__.py | 2 +- core/src/apps/stellar/operations/layout.py | 4 +++- core/src/apps/stellar/operations/serialize.py | 3 +-- core/src/apps/stellar/sign_tx.py | 15 +++++++------- core/src/apps/tezos/get_address.py | 5 ++++- core/src/apps/tezos/get_public_key.py | 3 +++ core/src/apps/tezos/layout.py | 1 + core/src/apps/tezos/sign_tx.py | 16 +++++++++------ core/src/apps/webauthn/__init__.py | 3 ++- .../apps/webauthn/add_resident_credential.py | 5 +++-- core/src/apps/webauthn/credential.py | 1 + core/src/apps/webauthn/fido2.py | 11 ++++++---- .../webauthn/list_resident_credentials.py | 2 +- .../webauthn/remove_resident_credential.py | 3 ++- .../src/apps/webauthn/resident_credentials.py | 1 + core/src/apps/workflow_handlers.py | 5 +++-- core/src/apps/zcash/hasher.py | 8 +++++--- core/src/apps/zcash/signer.py | 17 ++++++++++------ core/src/apps/zcash/unified_addresses.py | 7 ++++++- core/src/session.py | 1 + core/src/storage/__init__.py | 2 +- core/src/storage/cache.py | 2 +- core/src/storage/device.py | 2 +- core/src/storage/sd_salt.py | 2 +- core/src/trezor/crypto/der.py | 3 +-- core/src/trezor/loop.py | 8 +------- core/src/trezor/pin.py | 1 + core/src/trezor/sdcard.py | 1 + core/src/trezor/ui/layouts/tr/__init__.py | 20 ++++++++++--------- core/src/trezor/ui/layouts/tr/fido.py | 3 +-- core/src/trezor/ui/layouts/tr/homescreen.py | 6 +++--- core/src/trezor/ui/layouts/tr/progress.py | 3 +-- core/src/trezor/ui/layouts/tr/recovery.py | 3 +-- core/src/trezor/ui/layouts/tr/reset.py | 6 +++--- core/src/trezor/ui/layouts/tt_v2/__init__.py | 19 ++++++++++-------- core/src/trezor/ui/layouts/tt_v2/fido.py | 4 ++-- .../src/trezor/ui/layouts/tt_v2/homescreen.py | 6 +++--- core/src/trezor/ui/layouts/tt_v2/progress.py | 3 +-- core/src/trezor/ui/layouts/tt_v2/recovery.py | 3 +-- core/src/trezor/ui/layouts/tt_v2/reset.py | 4 ++-- core/src/trezor/utils.py | 11 +++------- core/src/trezor/wire/__init__.py | 8 +------- core/src/trezor/wire/context.py | 2 +- 177 files changed, 588 insertions(+), 458 deletions(-) diff --git a/core/src/apps/base.py b/core/src/apps/base.py index 3a6d8e5eb2..ef513d6138 100644 --- a/core/src/apps/base.py +++ b/core/src/apps/base.py @@ -11,15 +11,15 @@ from . import workflow_handlers if TYPE_CHECKING: from trezor import protobuf from trezor.messages import ( - Features, - Initialize, - EndSession, - GetFeatures, Cancel, + CancelAuthorization, + DoPreauthorized, + EndSession, + Features, + GetFeatures, + Initialize, LockDevice, Ping, - DoPreauthorized, - CancelAuthorization, SetBusy, ) @@ -41,10 +41,9 @@ def busy_expiry_ms() -> int: def get_features() -> Features: import storage.recovery as storage_recovery - from trezor.enums import Capability from trezor.messages import Features - from trezor.ui import WIDTH, HEIGHT + from trezor.ui import HEIGHT, WIDTH from apps.common import mnemonic, safety_checks @@ -206,8 +205,8 @@ async def handle_EndSession(msg: EndSession) -> Success: async def handle_Ping(msg: Ping) -> Success: if msg.button_protection: - from trezor.ui.layouts import confirm_action from trezor.enums import ButtonRequestType as B + from trezor.ui.layouts import confirm_action await confirm_action("ping", "Confirm", "ping", br_code=B.ProtectCall) return Success(message=msg.message) @@ -216,6 +215,7 @@ async def handle_Ping(msg: Ping) -> Success: async def handle_DoPreauthorized(msg: DoPreauthorized) -> protobuf.MessageType: from trezor.messages import PreauthorizedRequest from trezor.wire.context import call_any, get_context + from apps.common import authorization if not authorization.is_set(): @@ -241,6 +241,7 @@ async def handle_UnlockPath(msg: UnlockPath) -> protobuf.MessageType: from trezor.messages import UnlockedPathRequest from trezor.ui.layouts import confirm_action from trezor.wire.context import call_any, get_context + from apps.common.paths import SLIP25_PURPOSE from apps.common.seed import Slip21Node, get_seed from apps.common.writers import write_uint32_le diff --git a/core/src/apps/binance/get_address.py b/core/src/apps/binance/get_address.py index 522b06deb6..5f9ad6254d 100644 --- a/core/src/apps/binance/get_address.py +++ b/core/src/apps/binance/get_address.py @@ -3,7 +3,8 @@ from typing import TYPE_CHECKING from apps.common.keychain import auto_keychain if TYPE_CHECKING: - from trezor.messages import BinanceGetAddress, BinanceAddress + from trezor.messages import BinanceAddress, BinanceGetAddress + from apps.common.keychain import Keychain diff --git a/core/src/apps/binance/get_public_key.py b/core/src/apps/binance/get_public_key.py index a603188b7b..272731d512 100644 --- a/core/src/apps/binance/get_public_key.py +++ b/core/src/apps/binance/get_public_key.py @@ -4,6 +4,7 @@ from apps.common.keychain import auto_keychain if TYPE_CHECKING: from trezor.messages import BinanceGetPublicKey, BinancePublicKey + from apps.common.keychain import Keychain diff --git a/core/src/apps/binance/helpers.py b/core/src/apps/binance/helpers.py index 1bafaf18bd..52df2ec8a0 100644 --- a/core/src/apps/binance/helpers.py +++ b/core/src/apps/binance/helpers.py @@ -21,8 +21,8 @@ def _make_input_output(input_output: BinanceInputOutput) -> str: def produce_json_for_signing(envelope: BinanceSignTx, msg: MessageType) -> str: - from trezor.messages import BinanceCancelMsg, BinanceOrderMsg, BinanceTransferMsg from trezor import wire + from trezor.messages import BinanceCancelMsg, BinanceOrderMsg, BinanceTransferMsg # NOTE: not defining kwargs in format string saves 7 bytes per each argument ENVELOPE_BLUEPRINT = '{{"account_number":"{}","chain_id":"{}","data":null,"memo":"{}","msgs":[{}],"sequence":"{}","source":"{}"}}' diff --git a/core/src/apps/binance/sign_tx.py b/core/src/apps/binance/sign_tx.py index e57e35e4c9..ab5b127a57 100644 --- a/core/src/apps/binance/sign_tx.py +++ b/core/src/apps/binance/sign_tx.py @@ -3,14 +3,14 @@ from typing import TYPE_CHECKING from apps.common.keychain import auto_keychain if TYPE_CHECKING: - from trezor.messages import BinanceSignTx, BinanceSignedTx + from trezor.messages import BinanceSignedTx, BinanceSignTx + from apps.common.keychain import Keychain @auto_keychain(__name__) async def sign_tx(envelope: BinanceSignTx, keychain: Keychain) -> BinanceSignedTx: from trezor import wire - from trezor.wire.context import call_any from trezor.crypto.curve import secp256k1 from trezor.crypto.hashlib import sha256 from trezor.enums import MessageType @@ -21,6 +21,7 @@ async def sign_tx(envelope: BinanceSignTx, keychain: Keychain) -> BinanceSignedT BinanceTransferMsg, BinanceTxRequest, ) + from trezor.wire.context import call_any from apps.common import paths diff --git a/core/src/apps/bitcoin/addresses.py b/core/src/apps/bitcoin/addresses.py index 70ced13d1f..1c78ca1016 100644 --- a/core/src/apps/bitcoin/addresses.py +++ b/core/src/apps/bitcoin/addresses.py @@ -11,10 +11,11 @@ from .common import ecdsa_hash_pubkey, encode_bech32_address from .scripts import output_script_native_segwit, write_output_script_multisig if TYPE_CHECKING: - from trezor.messages import MultisigRedeemScriptType from trezor.crypto import bip32 - from apps.common.coininfo import CoinInfo from trezor.enums import InputScriptType + from trezor.messages import MultisigRedeemScriptType + + from apps.common.coininfo import CoinInfo def get_address( @@ -24,6 +25,7 @@ def get_address( multisig: MultisigRedeemScriptType | None = None, ) -> str: from trezor.enums import InputScriptType + from .multisig import multisig_get_pubkeys, multisig_pubkey_index node_public_key = node.public_key() # result_cache diff --git a/core/src/apps/bitcoin/authorization.py b/core/src/apps/bitcoin/authorization.py index 802992da11..69cd317ae6 100644 --- a/core/src/apps/bitcoin/authorization.py +++ b/core/src/apps/bitcoin/authorization.py @@ -22,6 +22,7 @@ class CoinJoinAuthorization: def check_get_ownership_proof(self, msg: GetOwnershipProof) -> bool: from trezor import utils + from .writers import write_bytes_prefixed params = self.params # local_cache_attribute diff --git a/core/src/apps/bitcoin/authorize_coinjoin.py b/core/src/apps/bitcoin/authorize_coinjoin.py index 8f5704450b..2833d2bf60 100644 --- a/core/src/apps/bitcoin/authorize_coinjoin.py +++ b/core/src/apps/bitcoin/authorize_coinjoin.py @@ -6,6 +6,7 @@ from .keychain import with_keychain if TYPE_CHECKING: from trezor.messages import AuthorizeCoinJoin, Success + from apps.common.coininfo import CoinInfo from apps.common.keychain import Keychain diff --git a/core/src/apps/bitcoin/common.py b/core/src/apps/bitcoin/common.py index b70dda1012..5f9642100e 100644 --- a/core/src/apps/bitcoin/common.py +++ b/core/src/apps/bitcoin/common.py @@ -8,10 +8,12 @@ from trezor.enums import InputScriptType, OutputScriptType if TYPE_CHECKING: from enum import IntEnum - from apps.common.coininfo import CoinInfo + + from trezor.crypto import bip32 from trezor.messages import TxInput from trezor.utils import HashWriter - from trezor.crypto import bip32 + + from apps.common.coininfo import CoinInfo else: IntEnum = object diff --git a/core/src/apps/bitcoin/get_address.py b/core/src/apps/bitcoin/get_address.py index af5572bea4..4dd302433e 100644 --- a/core/src/apps/bitcoin/get_address.py +++ b/core/src/apps/bitcoin/get_address.py @@ -3,9 +3,10 @@ from typing import TYPE_CHECKING from .keychain import with_keychain if TYPE_CHECKING: - from trezor.messages import GetAddress, HDNodeType, Address - from apps.common.keychain import Keychain + from trezor.messages import Address, GetAddress, HDNodeType + from apps.common.coininfo import CoinInfo + from apps.common.keychain import Keychain def _get_xpubs( diff --git a/core/src/apps/bitcoin/get_ownership_id.py b/core/src/apps/bitcoin/get_ownership_id.py index fdcdcf4bdd..dec6af5619 100644 --- a/core/src/apps/bitcoin/get_ownership_id.py +++ b/core/src/apps/bitcoin/get_ownership_id.py @@ -4,6 +4,7 @@ from .keychain import with_keychain if TYPE_CHECKING: from trezor.messages import GetOwnershipId, OwnershipId + from apps.common.coininfo import CoinInfo from apps.common.keychain import Keychain @@ -12,9 +13,9 @@ if TYPE_CHECKING: async def get_ownership_id( msg: GetOwnershipId, keychain: Keychain, coin: CoinInfo ) -> OwnershipId: - from trezor.wire import DataError from trezor.enums import InputScriptType from trezor.messages import OwnershipId + from trezor.wire import DataError from apps.common.paths import validate_path diff --git a/core/src/apps/bitcoin/get_ownership_proof.py b/core/src/apps/bitcoin/get_ownership_proof.py index a91cc4dde6..187d5a4f14 100644 --- a/core/src/apps/bitcoin/get_ownership_proof.py +++ b/core/src/apps/bitcoin/get_ownership_proof.py @@ -4,8 +4,10 @@ from .keychain import with_keychain if TYPE_CHECKING: from trezor.messages import GetOwnershipProof, OwnershipProof + from apps.common.coininfo import CoinInfo from apps.common.keychain import Keychain + from .authorization import CoinJoinAuthorization @@ -16,10 +18,10 @@ async def get_ownership_proof( coin: CoinInfo, authorization: CoinJoinAuthorization | None = None, ) -> OwnershipProof: - from trezor.wire import DataError, ProcessError from trezor.enums import InputScriptType from trezor.messages import OwnershipProof from trezor.ui.layouts import confirm_action, confirm_blob + from trezor.wire import DataError, ProcessError from apps.common.paths import validate_path diff --git a/core/src/apps/bitcoin/keychain.py b/core/src/apps/bitcoin/keychain.py index a90da28099..4e07ea6a30 100644 --- a/core/src/apps/bitcoin/keychain.py +++ b/core/src/apps/bitcoin/keychain.py @@ -11,22 +11,21 @@ from .common import BITCOIN_NAMES if TYPE_CHECKING: from typing import Awaitable, Callable, Iterable, TypeVar - from typing_extensions import Protocol - - from trezor.protobuf import MessageType from trezor.messages import ( GetAddress, GetOwnershipId, - GetPublicKey, - VerifyMessage, GetOwnershipProof, + GetPublicKey, SignTx, + VerifyMessage, ) + from trezor.protobuf import MessageType + from typing_extensions import Protocol - from apps.common.keychain import Keychain, MsgOut, Handler - from apps.common.paths import Bip32Path from apps.common import coininfo + from apps.common.keychain import Handler, Keychain, MsgOut + from apps.common.paths import Bip32Path BitcoinMessage = ( AuthorizeCoinJoin @@ -251,9 +250,10 @@ def get_schemas_from_patterns( def _get_coin_by_name(coin_name: str | None) -> coininfo.CoinInfo: - from apps.common import coininfo from trezor import wire + from apps.common import coininfo + if coin_name is None: coin_name = "Bitcoin" diff --git a/core/src/apps/bitcoin/multisig.py b/core/src/apps/bitcoin/multisig.py index 2bd0f5b30d..a26252a253 100644 --- a/core/src/apps/bitcoin/multisig.py +++ b/core/src/apps/bitcoin/multisig.py @@ -4,12 +4,14 @@ from trezor.wire import DataError if TYPE_CHECKING: from trezor.messages import HDNodeType, MultisigRedeemScriptType + from apps.common import paths def multisig_fingerprint(multisig: MultisigRedeemScriptType) -> bytes: from trezor.crypto.hashlib import sha256 from trezor.utils import HashWriter + from .writers import write_bytes_fixed, write_uint32 if multisig.nodes: diff --git a/core/src/apps/bitcoin/ownership.py b/core/src/apps/bitcoin/ownership.py index da72993ddc..0305b803f9 100644 --- a/core/src/apps/bitcoin/ownership.py +++ b/core/src/apps/bitcoin/ownership.py @@ -12,10 +12,11 @@ from apps.common.readers import read_compact_size from .scripts import read_bip322_signature_proof if TYPE_CHECKING: - from trezor.messages import MultisigRedeemScriptType - from trezor.enums import InputScriptType - from apps.common.coininfo import CoinInfo from trezor.crypto import bip32 + from trezor.enums import InputScriptType + from trezor.messages import MultisigRedeemScriptType + + from apps.common.coininfo import CoinInfo from apps.common.keychain import Keychain # This module implements the SLIP-0019 proof of ownership format, see @@ -39,13 +40,11 @@ def generate_proof( commitment_data: bytes, ) -> tuple[bytes, bytes]: from trezor.enums import InputScriptType - from apps.bitcoin.writers import ( - write_bytes_fixed, - write_compact_size, - write_uint8, - ) - from .scripts import write_bip322_signature_proof + + from apps.bitcoin.writers import write_bytes_fixed, write_compact_size, write_uint8 + from . import common + from .scripts import write_bip322_signature_proof flags = 0 if user_confirmed: diff --git a/core/src/apps/bitcoin/scripts.py b/core/src/apps/bitcoin/scripts.py index c9193ef077..1a61888997 100644 --- a/core/src/apps/bitcoin/scripts.py +++ b/core/src/apps/bitcoin/scripts.py @@ -38,8 +38,8 @@ def write_input_script_prefixed( pubkey: bytes, signature: bytes, ) -> None: - from trezor.crypto.hashlib import sha256 from trezor import wire + from trezor.crypto.hashlib import sha256 IST = InputScriptType # local_cache_global @@ -79,6 +79,7 @@ def write_input_script_prefixed( def output_derive_script(address: str, coin: CoinInfo) -> bytes: from trezor.crypto import base58, cashaddr + from apps.common import address_type if coin.bech32_prefix and address.startswith(coin.bech32_prefix): diff --git a/core/src/apps/bitcoin/scripts_decred.py b/core/src/apps/bitcoin/scripts_decred.py index 35c99de6b7..cc3f136017 100644 --- a/core/src/apps/bitcoin/scripts_decred.py +++ b/core/src/apps/bitcoin/scripts_decred.py @@ -14,8 +14,8 @@ from .scripts import ( # noqa: F401 from .writers import write_compact_size if TYPE_CHECKING: - from trezor.messages import MultisigRedeemScriptType from trezor.enums import InputScriptType + from trezor.messages import MultisigRedeemScriptType from apps.common.coininfo import CoinInfo @@ -34,6 +34,7 @@ def write_input_script_prefixed( ) -> None: from trezor import wire from trezor.enums import InputScriptType + from .multisig import multisig_pubkey_index if script_type == InputScriptType.SPENDADDRESS: diff --git a/core/src/apps/bitcoin/sign_message.py b/core/src/apps/bitcoin/sign_message.py index 4e6d4025e2..d777873dc0 100644 --- a/core/src/apps/bitcoin/sign_message.py +++ b/core/src/apps/bitcoin/sign_message.py @@ -3,7 +3,7 @@ from typing import TYPE_CHECKING from .keychain import with_keychain if TYPE_CHECKING: - from trezor.messages import SignMessage, MessageSignature + from trezor.messages import MessageSignature, SignMessage from apps.common.coininfo import CoinInfo from apps.common.keychain import Keychain diff --git a/core/src/apps/bitcoin/sign_tx/__init__.py b/core/src/apps/bitcoin/sign_tx/__init__.py index 15b9367bff..e6bd380e43 100644 --- a/core/src/apps/bitcoin/sign_tx/__init__.py +++ b/core/src/apps/bitcoin/sign_tx/__init__.py @@ -5,9 +5,10 @@ from trezor import utils from ..keychain import with_keychain if not utils.BITCOIN_ONLY: - from . import bitcoinlike, decred, zcash_v4 from apps.zcash.signer import Zcash + from . import bitcoinlike, decred, zcash_v4 + if TYPE_CHECKING: from typing import Protocol @@ -15,18 +16,18 @@ if TYPE_CHECKING: SignTx, TxAckInput, TxAckOutput, - TxAckPrevMeta, - TxAckPrevInput, - TxAckPrevOutput, TxAckPrevExtraData, + TxAckPrevInput, + TxAckPrevMeta, + TxAckPrevOutput, TxRequest, ) from apps.common.coininfo import CoinInfo from apps.common.keychain import Keychain - from . import approvers from ..authorization import CoinJoinAuthorization + from . import approvers TxAckType = ( TxAckInput diff --git a/core/src/apps/bitcoin/sign_tx/approvers.py b/core/src/apps/bitcoin/sign_tx/approvers.py index bbe601673a..840d1a31b3 100644 --- a/core/src/apps/bitcoin/sign_tx/approvers.py +++ b/core/src/apps/bitcoin/sign_tx/approvers.py @@ -17,14 +17,14 @@ from .tx_info import OriginalTxInfo if TYPE_CHECKING: from trezor.crypto import bip32 - from trezor.messages import SignTx, TxInput, TxOutput, TxAckPaymentRequest + from trezor.messages import SignTx, TxAckPaymentRequest, TxInput, TxOutput from apps.common.coininfo import CoinInfo from apps.common.keychain import Keychain from ..authorization import CoinJoinAuthorization - from .tx_info import TxInfo from .payment_request import PaymentRequestVerifier + from .tx_info import TxInfo # An Approver object computes the transaction totals and either prompts the user diff --git a/core/src/apps/bitcoin/sign_tx/bitcoin.py b/core/src/apps/bitcoin/sign_tx/bitcoin.py index 451ac48d38..10267415e5 100644 --- a/core/src/apps/bitcoin/sign_tx/bitcoin.py +++ b/core/src/apps/bitcoin/sign_tx/bitcoin.py @@ -23,23 +23,15 @@ if TYPE_CHECKING: from typing import Sequence from trezor.crypto import bip32 - - from trezor.messages import ( - PrevInput, - PrevOutput, - PrevTx, - SignTx, - TxInput, - TxOutput, - ) + from trezor.messages import PrevInput, PrevOutput, PrevTx, SignTx, TxInput, TxOutput from apps.common.coininfo import CoinInfo from apps.common.keychain import Keychain + from ..writers import Writer from . import approvers from .sig_hasher import SigHasher from .tx_info import TxInfo - from ..writers import Writer # the number of bytes to preallocate for serialized transaction chunks @@ -110,6 +102,7 @@ class Bitcoin: TxRequestDetailsType, TxRequestSerializedType, ) + from . import approvers from .tx_info import TxInfo diff --git a/core/src/apps/bitcoin/sign_tx/bitcoinlike.py b/core/src/apps/bitcoin/sign_tx/bitcoinlike.py index 8ab3377bed..d5af224736 100644 --- a/core/src/apps/bitcoin/sign_tx/bitcoinlike.py +++ b/core/src/apps/bitcoin/sign_tx/bitcoinlike.py @@ -6,13 +6,16 @@ from .bitcoin import Bitcoin if TYPE_CHECKING: from typing import Sequence + from trezor.messages import PrevTx, SignTx, TxInput + from .tx_info import OriginalTxInfo, TxInfo class Bitcoinlike(Bitcoin): async def sign_nonsegwit_bip143_input(self, i_sign: int) -> None: from trezor import wire + from .. import multisig from ..common import NONSEGWIT_INPUT_SCRIPT_TYPES diff --git a/core/src/apps/bitcoin/sign_tx/decred.py b/core/src/apps/bitcoin/sign_tx/decred.py index fd39159038..5ba638d99f 100644 --- a/core/src/apps/bitcoin/sign_tx/decred.py +++ b/core/src/apps/bitcoin/sign_tx/decred.py @@ -29,22 +29,15 @@ if TYPE_CHECKING: from typing import Sequence from trezor.crypto import bip32 - from trezor.messages import ( - SignTx, - TxInput, - TxOutput, - PrevTx, - PrevInput, - PrevOutput, - ) + from trezor.messages import PrevInput, PrevOutput, PrevTx, SignTx, TxInput, TxOutput from apps.common.coininfo import CoinInfo from apps.common.keychain import Keychain - from .sig_hasher import SigHasher - from . import approvers from ..common import SigHashType from ..writers import Writer + from . import approvers + from .sig_hasher import SigHasher # Decred input size (without script): 32 prevhash, 4 idx, 1 Decred tree, 4 sequence @@ -213,9 +206,10 @@ class Decred(Bitcoin): async def step4_serialize_inputs(self) -> None: from trezor.enums import DecredStakingSpendType + + from .. import multisig from ..common import SigHashType, ecdsa_sign from .progress import progress - from .. import multisig inputs_count = self.tx_info.tx.inputs_count # local_cache_attribute coin = self.coin # local_cache_attribute diff --git a/core/src/apps/bitcoin/sign_tx/helpers.py b/core/src/apps/bitcoin/sign_tx/helpers.py index a79d38688a..d8d37fda05 100644 --- a/core/src/apps/bitcoin/sign_tx/helpers.py +++ b/core/src/apps/bitcoin/sign_tx/helpers.py @@ -10,18 +10,19 @@ from . import layout if TYPE_CHECKING: from typing import Any, Awaitable - from trezor.enums import AmountUnit + from trezor.enums import AmountUnit from trezor.messages import ( PrevInput, PrevOutput, PrevTx, SignTx, + TxAckPaymentRequest, TxInput, TxOutput, TxRequest, - TxAckPaymentRequest, ) + from apps.common.coininfo import CoinInfo from apps.common.paths import Bip32Path diff --git a/core/src/apps/bitcoin/sign_tx/layout.py b/core/src/apps/bitcoin/sign_tx/layout.py index 68222b1687..7e656f74e0 100644 --- a/core/src/apps/bitcoin/sign_tx/layout.py +++ b/core/src/apps/bitcoin/sign_tx/layout.py @@ -19,9 +19,9 @@ from ..keychain import address_n_to_name if TYPE_CHECKING: from typing import Any + from trezor.enums import AmountUnit from trezor.messages import TxAckPaymentRequest, TxOutput from trezor.ui.layouts import LayoutType - from trezor.enums import AmountUnit from apps.common.coininfo import CoinInfo from apps.common.paths import Bip32Path @@ -63,9 +63,10 @@ async def confirm_output( amount_unit: AmountUnit, output_index: int, ) -> None: - from . import omni from trezor.enums import OutputScriptType + from . import omni + if output.script_type == OutputScriptType.PAYTOOPRETURN: data = output.op_return_data assert data is not None diff --git a/core/src/apps/bitcoin/sign_tx/matchcheck.py b/core/src/apps/bitcoin/sign_tx/matchcheck.py index fb91a024ff..a9db1aa11e 100644 --- a/core/src/apps/bitcoin/sign_tx/matchcheck.py +++ b/core/src/apps/bitcoin/sign_tx/matchcheck.py @@ -111,6 +111,7 @@ class ScriptTypeChecker(MatchChecker): def attribute_from_tx(self, txio: TxInput | TxOutput) -> Any: from trezor.enums import InputScriptType from trezor.messages import TxOutput + from ..common import CHANGE_OUTPUT_TO_INPUT_SCRIPT_TYPES if TxOutput.is_type_of(txio): diff --git a/core/src/apps/bitcoin/sign_tx/omni.py b/core/src/apps/bitcoin/sign_tx/omni.py index 870bb3bdcd..ef5dfcd12f 100644 --- a/core/src/apps/bitcoin/sign_tx/omni.py +++ b/core/src/apps/bitcoin/sign_tx/omni.py @@ -16,6 +16,7 @@ def is_valid(data: bytes) -> bool: def parse(data: bytes) -> str: from ustruct import unpack + from trezor.strings import format_amount if not is_valid(data): diff --git a/core/src/apps/bitcoin/sign_tx/payment_request.py b/core/src/apps/bitcoin/sign_tx/payment_request.py index d0c69bf02d..8f2f7b88a8 100644 --- a/core/src/apps/bitcoin/sign_tx/payment_request.py +++ b/core/src/apps/bitcoin/sign_tx/payment_request.py @@ -7,6 +7,7 @@ from .. import writers if TYPE_CHECKING: from trezor.messages import TxAckPaymentRequest, TxOutput + from apps.common import coininfo from apps.common.keychain import Keychain @@ -28,7 +29,9 @@ class PaymentRequestVerifier: from storage import cache from trezor.crypto.hashlib import sha256 from trezor.utils import HashWriter + from apps.common.address_mac import check_address_mac + from .. import writers # pylint: disable=import-outside-toplevel self.h_outputs = HashWriter(sha256()) diff --git a/core/src/apps/bitcoin/sign_tx/progress.py b/core/src/apps/bitcoin/sign_tx/progress.py index 5404623a5e..af8dc3683e 100644 --- a/core/src/apps/bitcoin/sign_tx/progress.py +++ b/core/src/apps/bitcoin/sign_tx/progress.py @@ -2,7 +2,9 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from trezor.messages import SignTx + from apps.common.coininfo import CoinInfo + from .tx_info import OriginalTxInfo # Checking previous transactions typically requires the following pieces of diff --git a/core/src/apps/bitcoin/sign_tx/sig_hasher.py b/core/src/apps/bitcoin/sign_tx/sig_hasher.py index 167d8e0e16..71930efad8 100644 --- a/core/src/apps/bitcoin/sign_tx/sig_hasher.py +++ b/core/src/apps/bitcoin/sign_tx/sig_hasher.py @@ -10,10 +10,13 @@ from ..writers import ( if TYPE_CHECKING: from typing import Protocol, Sequence - from ..common import SigHashType + from trezor.messages import PrevTx, SignTx, TxInput, TxOutput + from apps.common import coininfo + from ..common import SigHashType + class SigHasher(Protocol): def add_input(self, txi: TxInput, script_pubkey: bytes) -> None: ... @@ -85,6 +88,7 @@ class BitcoinSigHasher: ) -> bytes: from trezor.crypto.hashlib import sha256 from trezor.utils import HashWriter + from .. import scripts from ..writers import get_tx_hash diff --git a/core/src/apps/bitcoin/sign_tx/tx_info.py b/core/src/apps/bitcoin/sign_tx/tx_info.py index 7176654c20..c495cc5144 100644 --- a/core/src/apps/bitcoin/sign_tx/tx_info.py +++ b/core/src/apps/bitcoin/sign_tx/tx_info.py @@ -5,17 +5,14 @@ from .. import common, writers if TYPE_CHECKING: from typing import Protocol - from trezor.messages import ( - PrevTx, - SignTx, - TxInput, - TxOutput, - ) + + from trezor.messages import PrevTx, SignTx, TxInput, TxOutput from trezor.utils import HashWriter - from .sig_hasher import SigHasher from apps.common.coininfo import CoinInfo + from .sig_hasher import SigHasher + class Signer(Protocol): coin: CoinInfo @@ -58,10 +55,11 @@ class TxInfoBase: def __init__(self, signer: Signer, tx: SignTx | PrevTx) -> None: from trezor.crypto.hashlib import sha256 from trezor.utils import HashWriter + from .matchcheck import ( MultisigFingerprintChecker, - WalletPathChecker, ScriptTypeChecker, + WalletPathChecker, ) # Checksum of multisig inputs, used to validate change-output. diff --git a/core/src/apps/bitcoin/sign_tx/zcash_v4.py b/core/src/apps/bitcoin/sign_tx/zcash_v4.py index d7b3e2bc6e..38a6ecc100 100644 --- a/core/src/apps/bitcoin/sign_tx/zcash_v4.py +++ b/core/src/apps/bitcoin/sign_tx/zcash_v4.py @@ -9,15 +9,18 @@ from ..writers import TX_HASH_SIZE, write_bytes_reversed, write_uint32, write_ui from .bitcoinlike import Bitcoinlike if TYPE_CHECKING: + from typing import Sequence + from trezor.messages import PrevTx, SignTx, TxInput, TxOutput + from apps.common.coininfo import CoinInfo from apps.common.keychain import Keychain - from . import approvers - from typing import Sequence - from .sig_hasher import SigHasher - from .tx_info import OriginalTxInfo, TxInfo + from ..common import SigHashType from ..writers import Writer + from . import approvers + from .sig_hasher import SigHasher + from .tx_info import OriginalTxInfo, TxInfo _OVERWINTERED = const(0x8000_0000) @@ -48,6 +51,7 @@ class Zip243SigHasher: hash_type: int, ) -> bytes: import ustruct as struct + from ..scripts import write_bip143_script_code_prefixed from ..writers import get_tx_hash, write_bytes_fixed @@ -135,6 +139,7 @@ class ZcashV4(Bitcoinlike): async def step7_finish(self) -> None: from apps.common.writers import write_compact_size + from . import helpers serialized_tx = self.serialized_tx # local_cache_attribute diff --git a/core/src/apps/bitcoin/verification.py b/core/src/apps/bitcoin/verification.py index 2598c33abb..c4c4148ece 100644 --- a/core/src/apps/bitcoin/verification.py +++ b/core/src/apps/bitcoin/verification.py @@ -4,7 +4,9 @@ from trezor.wire import DataError if TYPE_CHECKING: from typing import Sequence + from apps.common.coininfo import CoinInfo + from .common import SigHashType @@ -17,8 +19,8 @@ class SignatureVerifier: coin: CoinInfo, ): from trezor import utils - from trezor.wire import DataError # local_cache_global from trezor.crypto.hashlib import sha256 + from trezor.wire import DataError # local_cache_global from .common import OP_0, OP_1, SigHashType, ecdsa_hash_pubkey from .scripts import ( diff --git a/core/src/apps/bitcoin/verify_message.py b/core/src/apps/bitcoin/verify_message.py index 2d18469f34..454d3f708f 100644 --- a/core/src/apps/bitcoin/verify_message.py +++ b/core/src/apps/bitcoin/verify_message.py @@ -1,17 +1,20 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from apps.common.coininfo import CoinInfo - from trezor.messages import VerifyMessage, Success from trezor.enums import InputScriptType + from trezor.messages import Success, VerifyMessage + + from apps.common.coininfo import CoinInfo def _address_to_script_type(address: str, coin: CoinInfo) -> InputScriptType: - from trezor.crypto import base58 - from trezor.wire import DataError - from trezor.enums import InputScriptType from trezor import utils + from trezor.crypto import base58 + from trezor.enums import InputScriptType + from trezor.wire import DataError + from apps.common import address_type + from . import common # Determines the script type from a non-multisig address. @@ -49,11 +52,11 @@ def _address_to_script_type(address: str, coin: CoinInfo) -> InputScriptType: async def verify_message(msg: VerifyMessage) -> Success: from trezor import utils - from trezor.wire import ProcessError from trezor.crypto.curve import secp256k1 from trezor.enums import InputScriptType from trezor.messages import Success from trezor.ui.layouts import confirm_signverify, show_success + from trezor.wire import ProcessError from apps.common import coins from apps.common.signverify import decode_message, message_digest diff --git a/core/src/apps/bitcoin/writers.py b/core/src/apps/bitcoin/writers.py index de76e10468..711aabc7c1 100644 --- a/core/src/apps/bitcoin/writers.py +++ b/core/src/apps/bitcoin/writers.py @@ -15,12 +15,7 @@ from apps.common.writers import ( # noqa: F401 ) if TYPE_CHECKING: - from trezor.messages import ( - PrevInput, - PrevOutput, - TxInput, - TxOutput, - ) + from trezor.messages import PrevInput, PrevOutput, TxInput, TxOutput from trezor.utils import HashWriter from apps.common.writers import Writer diff --git a/core/src/apps/cardano/addresses.py b/core/src/apps/cardano/addresses.py index 9ccc7c38ed..2bab218340 100644 --- a/core/src/apps/cardano/addresses.py +++ b/core/src/apps/cardano/addresses.py @@ -12,7 +12,9 @@ from .helpers.utils import get_public_key_hash if TYPE_CHECKING: from typing import Any + from trezor import messages + from .seed import Keychain diff --git a/core/src/apps/cardano/auxiliary_data.py b/core/src/apps/cardano/auxiliary_data.py index 9aa681bb38..3dab3a4c11 100644 --- a/core/src/apps/cardano/auxiliary_data.py +++ b/core/src/apps/cardano/auxiliary_data.py @@ -205,8 +205,8 @@ def get_hash_and_supplement( protocol_magic: int, network_id: int, ) -> tuple[bytes, messages.CardanoTxAuxiliaryDataSupplement]: - from trezor.enums import CardanoTxAuxiliaryDataSupplementType from trezor import messages + from trezor.enums import CardanoTxAuxiliaryDataSupplementType if parameters := auxiliary_data.cvote_registration_parameters: ( diff --git a/core/src/apps/cardano/certificates.py b/core/src/apps/cardano/certificates.py index 7ca8028b92..2c116860c0 100644 --- a/core/src/apps/cardano/certificates.py +++ b/core/src/apps/cardano/certificates.py @@ -11,6 +11,7 @@ if TYPE_CHECKING: from typing import Any from trezor import messages + from apps.common.cbor import CborSequence from . import seed diff --git a/core/src/apps/cardano/get_address.py b/core/src/apps/cardano/get_address.py index 5d08d13db5..c5a627dca2 100644 --- a/core/src/apps/cardano/get_address.py +++ b/core/src/apps/cardano/get_address.py @@ -3,19 +3,20 @@ from typing import TYPE_CHECKING from . import seed if TYPE_CHECKING: - from trezor.messages import CardanoGetAddress, CardanoAddress + from trezor.messages import CardanoAddress, CardanoGetAddress @seed.with_keychain async def get_address( msg: CardanoGetAddress, keychain: seed.Keychain ) -> CardanoAddress: - from trezor.messages import CardanoAddress from trezor import log, wire + from trezor.messages import CardanoAddress + + from . import addresses from .helpers.credential import Credential, should_show_credentials from .helpers.utils import validate_network_info from .layout import show_cardano_address, show_credentials - from . import addresses address_parameters = msg.address_parameters # local_cache_attribute diff --git a/core/src/apps/cardano/get_native_script_hash.py b/core/src/apps/cardano/get_native_script_hash.py index 145e9684e4..64c4f08501 100644 --- a/core/src/apps/cardano/get_native_script_hash.py +++ b/core/src/apps/cardano/get_native_script_hash.py @@ -10,8 +10,9 @@ if TYPE_CHECKING: async def get_native_script_hash( msg: CardanoGetNativeScriptHash, keychain: seed.Keychain ) -> CardanoNativeScriptHash: - from trezor.messages import CardanoNativeScriptHash from trezor.enums import CardanoNativeScriptHashDisplayFormat + from trezor.messages import CardanoNativeScriptHash + from . import layout, native_script native_script.validate_native_script(msg.script) diff --git a/core/src/apps/cardano/get_public_key.py b/core/src/apps/cardano/get_public_key.py index 910eafd11e..87d9d0eb40 100644 --- a/core/src/apps/cardano/get_public_key.py +++ b/core/src/apps/cardano/get_public_key.py @@ -13,7 +13,9 @@ async def get_public_key( ) -> CardanoPublicKey: from trezor import log, wire from trezor.ui.layouts import show_pubkey + from apps.common import paths + from .helpers.paths import SCHEMA_MINT, SCHEMA_PUBKEY address_n = msg.address_n # local_cache_attribute @@ -40,8 +42,9 @@ async def get_public_key( def _get_public_key( keychain: seed.Keychain, derivation_path: list[int] ) -> CardanoPublicKey: + from trezor.messages import CardanoPublicKey, HDNodeType + from .helpers.utils import derive_public_key - from trezor.messages import HDNodeType, CardanoPublicKey node = keychain.derive(derivation_path) diff --git a/core/src/apps/cardano/helpers/account_path_check.py b/core/src/apps/cardano/helpers/account_path_check.py index f9791d943f..4b85ad2367 100644 --- a/core/src/apps/cardano/helpers/account_path_check.py +++ b/core/src/apps/cardano/helpers/account_path_check.py @@ -9,8 +9,8 @@ if TYPE_CHECKING: CardanoPoolOwner, CardanoTxCertificate, CardanoTxOutput, - CardanoTxWitnessRequest, CardanoTxWithdrawal, + CardanoTxWitnessRequest, ) diff --git a/core/src/apps/cardano/helpers/hash_builder_collection.py b/core/src/apps/cardano/helpers/hash_builder_collection.py index c846ed488a..b9344c1d59 100644 --- a/core/src/apps/cardano/helpers/hash_builder_collection.py +++ b/core/src/apps/cardano/helpers/hash_builder_collection.py @@ -4,6 +4,7 @@ from apps.common import cbor if TYPE_CHECKING: from typing import Any, Generic, TypeVar + from trezor import wire from trezor.utils import HashContext diff --git a/core/src/apps/cardano/helpers/utils.py b/core/src/apps/cardano/helpers/utils.py index 388ad77dfe..0cc1f8fd09 100644 --- a/core/src/apps/cardano/helpers/utils.py +++ b/core/src/apps/cardano/helpers/utils.py @@ -6,9 +6,10 @@ from . import ADDRESS_KEY_HASH_SIZE, bech32 from .paths import ACCOUNT_PATH_INDEX if TYPE_CHECKING: - from .. import seed from trezor.wire import ProcessError + from .. import seed + def variable_length_encode(number: int) -> bytes: """ @@ -104,6 +105,7 @@ def validate_network_info(network_id: int, protocol_magic: int) -> None: consistency between various testnets (at least for now). """ from trezor import wire + from . import network_ids, protocol_magics is_mainnet_network_id = network_ids.is_mainnet(network_id) diff --git a/core/src/apps/cardano/native_script.py b/core/src/apps/cardano/native_script.py index 78a5c72d58..c8e12df7f2 100644 --- a/core/src/apps/cardano/native_script.py +++ b/core/src/apps/cardano/native_script.py @@ -5,6 +5,7 @@ from trezor.wire import ProcessError if TYPE_CHECKING: from typing import Any + from trezor import messages from apps.common.cbor import CborSequence @@ -13,9 +14,9 @@ if TYPE_CHECKING: def validate_native_script(script: messages.CardanoNativeScript | None) -> None: + from . import seed from .helpers import ADDRESS_KEY_HASH_SIZE from .helpers.paths import SCHEMA_MINT - from . import seed INVALID_NATIVE_SCRIPT = ProcessError("Invalid native script") @@ -120,10 +121,12 @@ def _validate_native_script_structure(script: messages.CardanoNativeScript) -> N def get_native_script_hash( keychain: seed.Keychain, script: messages.CardanoNativeScript ) -> bytes: - from .helpers import SCRIPT_HASH_SIZE from trezor.crypto import hashlib + from apps.common import cbor + from .helpers import SCRIPT_HASH_SIZE + script_cbor = cbor.encode(cborize_native_script(keychain, script)) prefixed_script_cbor = b"\00" + script_cbor return hashlib.blake2b(data=prefixed_script_cbor, outlen=SCRIPT_HASH_SIZE).digest() diff --git a/core/src/apps/cardano/seed.py b/core/src/apps/cardano/seed.py index e74c2508d5..4a7f7b2674 100644 --- a/core/src/apps/cardano/seed.py +++ b/core/src/apps/cardano/seed.py @@ -10,14 +10,14 @@ from apps.common.seed import get_seed from .helpers.paths import BYRON_ROOT, MINTING_ROOT, MULTISIG_ROOT, SHELLEY_ROOT if TYPE_CHECKING: - from typing import Callable, Awaitable, TypeVar - - from apps.common.paths import Bip32Path - from apps.common.keychain import MsgOut, Handler + from typing import Awaitable, Callable, TypeVar from trezor import messages - from trezor.enums import CardanoDerivationType from trezor.crypto import bip32 + from trezor.enums import CardanoDerivationType + + from apps.common.keychain import Handler, MsgOut + from apps.common.paths import Bip32Path CardanoMessages = ( messages.CardanoGetAddress @@ -137,9 +137,10 @@ def derive_and_store_secrets(passphrase: str) -> None: async def _get_keychain_bip39(derivation_type: CardanoDerivationType) -> Keychain: - from apps.common.seed import derive_and_store_roots from trezor.enums import CardanoDerivationType + from apps.common.seed import derive_and_store_roots + if not device.is_initialized(): raise wire.NotInitialized("Device is not initialized") diff --git a/core/src/apps/cardano/sign_tx/__init__.py b/core/src/apps/cardano/sign_tx/__init__.py index 75d6636284..c9144580e5 100644 --- a/core/src/apps/cardano/sign_tx/__init__.py +++ b/core/src/apps/cardano/sign_tx/__init__.py @@ -4,6 +4,7 @@ from .. import seed if TYPE_CHECKING: from typing import Type + from trezor.messages import CardanoSignTxFinished, CardanoSignTxInit @@ -11,9 +12,9 @@ if TYPE_CHECKING: async def sign_tx( msg: CardanoSignTxInit, keychain: seed.Keychain ) -> CardanoSignTxFinished: - from trezor.messages import CardanoSignTxFinished from trezor import log, wire from trezor.enums import CardanoTxSigningMode + from trezor.messages import CardanoSignTxFinished from .signer import Signer diff --git a/core/src/apps/cardano/sign_tx/ordinary_signer.py b/core/src/apps/cardano/sign_tx/ordinary_signer.py index 157f0ecdf0..40c8f7d4da 100644 --- a/core/src/apps/cardano/sign_tx/ordinary_signer.py +++ b/core/src/apps/cardano/sign_tx/ordinary_signer.py @@ -75,11 +75,7 @@ class OrdinarySigner(Signer): raise ProcessError("Invalid witness request") async def _show_witness_request(self, witness_path: list[int]) -> None: - from ..helpers.paths import ( - SCHEMA_PAYMENT, - SCHEMA_STAKING, - WITNESS_PATH_NAME, - ) + from ..helpers.paths import SCHEMA_PAYMENT, SCHEMA_STAKING, WITNESS_PATH_NAME # super() omitted intentionally # We only allow payment, staking or minting paths. diff --git a/core/src/apps/cardano/sign_tx/signer.py b/core/src/apps/cardano/sign_tx/signer.py index ade3d2b653..f8b22bc34a 100644 --- a/core/src/apps/cardano/sign_tx/signer.py +++ b/core/src/apps/cardano/sign_tx/signer.py @@ -22,9 +22,11 @@ from ..helpers.utils import derive_public_key if TYPE_CHECKING: from typing import Any, Awaitable, ClassVar + from trezor.enums import CardanoAddressType - from apps.common.paths import PathSchema + from apps.common import cbor + from apps.common.paths import PathSchema from ..helpers.hash_builder_collection import HashBuilderEmbeddedCBOR diff --git a/core/src/apps/common/address_mac.py b/core/src/apps/common/address_mac.py index 962249dd8a..f4eccf38f6 100644 --- a/core/src/apps/common/address_mac.py +++ b/core/src/apps/common/address_mac.py @@ -21,6 +21,7 @@ def check_address_mac( def get_address_mac(address: str, slip44: int, keychain: Keychain) -> bytes: from trezor.crypto import hmac + from .writers import write_bytes_unchecked, write_compact_size, write_uint32_le # k = Key(m/"SLIP-0024"/"Address MAC key") diff --git a/core/src/apps/common/cbor.py b/core/src/apps/common/cbor.py index 3441c844f2..7edaf9cac2 100644 --- a/core/src/apps/common/cbor.py +++ b/core/src/apps/common/cbor.py @@ -9,6 +9,7 @@ from trezor import log if TYPE_CHECKING: from typing import Any, Generic, Iterator, TypeVar + from trezor.utils import BufferReader K = TypeVar("K") diff --git a/core/src/apps/common/keychain.py b/core/src/apps/common/keychain.py index 9dd9ece3ff..019f20795f 100644 --- a/core/src/apps/common/keychain.py +++ b/core/src/apps/common/keychain.py @@ -6,16 +6,11 @@ from trezor.wire import DataError from . import paths, safety_checks if TYPE_CHECKING: - from typing import ( - Any, - Awaitable, - Callable, - Iterable, - TypeVar, - ) - from typing_extensions import Protocol + from typing import Any, Awaitable, Callable, Iterable, TypeVar from trezor.protobuf import MessageType + from typing_extensions import Protocol + from .seed import Slip21Node T = TypeVar("T") diff --git a/core/src/apps/common/paths.py b/core/src/apps/common/paths.py index cfaecc035a..afc7a979c1 100644 --- a/core/src/apps/common/paths.py +++ b/core/src/apps/common/paths.py @@ -5,15 +5,8 @@ HARDENED = const(0x8000_0000) SLIP25_PURPOSE = const(10025 | HARDENED) if TYPE_CHECKING: - from typing import ( - Any, - Callable, - Collection, - Container, - Iterable, - Sequence, - TypeVar, - ) + from typing import Any, Callable, Collection, Container, Iterable, Sequence, TypeVar + from typing_extensions import Protocol Bip32Path = Sequence[int] diff --git a/core/src/apps/common/request_pin.py b/core/src/apps/common/request_pin.py index b0ca647224..be2b3b4ab7 100644 --- a/core/src/apps/common/request_pin.py +++ b/core/src/apps/common/request_pin.py @@ -16,7 +16,7 @@ async def _request_sd_salt( if not utils.USE_SD_CARD: return None else: - from .sdcard import request_sd_salt, SdCardUnavailable + from .sdcard import SdCardUnavailable, request_sd_salt try: return await request_sd_salt() @@ -49,7 +49,7 @@ async def request_pin( async def request_pin_confirm(*args: Any, **kwargs: Any) -> str: - from trezor.ui.layouts import pin_mismatch_popup, confirm_reenter_pin + from trezor.ui.layouts import confirm_reenter_pin, pin_mismatch_popup while True: pin1 = await request_pin("Enter new PIN", *args, **kwargs) diff --git a/core/src/apps/common/seed.py b/core/src/apps/common/seed.py index eb9f8905ba..d773909b40 100644 --- a/core/src/apps/common/seed.py +++ b/core/src/apps/common/seed.py @@ -9,9 +9,10 @@ from . import mnemonic from .passphrase import get as get_passphrase if TYPE_CHECKING: - from .paths import Bip32Path, Slip21Path from trezor.crypto import bip32 + from .paths import Bip32Path, Slip21Path + class Slip21Node: """ diff --git a/core/src/apps/debug/__init__.py b/core/src/apps/debug/__init__.py index a006045c9b..e6426045ca 100644 --- a/core/src/apps/debug/__init__.py +++ b/core/src/apps/debug/__init__.py @@ -4,36 +4,31 @@ if not __debug__: halt("debug mode inactive") if __debug__: - from storage import debug as storage - from storage.debug import debug_events + from typing import TYPE_CHECKING import trezorui2 - + from storage import debug as storage + from storage.debug import debug_events from trezor import log, loop, utils, wire + from trezor.enums import MessageType + from trezor.messages import DebugLinkLayout, Success from trezor.ui import display from trezor.wire import context - from trezor.enums import MessageType - from trezor.messages import ( - DebugLinkLayout, - Success, - ) from apps import workflow_handlers - from typing import TYPE_CHECKING - if TYPE_CHECKING: - from trezor.ui import Layout from trezor.messages import ( DebugLinkDecision, DebugLinkEraseSdCard, DebugLinkGetState, DebugLinkRecordScreen, DebugLinkReseedRandom, + DebugLinkResetDebugEvents, DebugLinkState, DebugLinkWatchLayout, - DebugLinkResetDebugEvents, ) + from trezor.ui import Layout swipe_chan = loop.chan() result_chan = loop.chan() @@ -194,6 +189,7 @@ if __debug__: msg: DebugLinkGetState, ) -> DebugLinkState | None: from trezor.messages import DebugLinkState + from apps.common import mnemonic, passphrase m = DebugLinkState() diff --git a/core/src/apps/debug/load_device.py b/core/src/apps/debug/load_device.py index 909bd3babd..ce873e3218 100644 --- a/core/src/apps/debug/load_device.py +++ b/core/src/apps/debug/load_device.py @@ -10,9 +10,10 @@ async def load_device(msg: LoadDevice) -> Success: from trezor.crypto import bip39, slip39 from trezor.enums import BackupType from trezor.messages import Success - from apps.management import backup_types - from trezor.wire import UnexpectedMessage, ProcessError from trezor.ui.layouts import confirm_action + from trezor.wire import ProcessError, UnexpectedMessage + + from apps.management import backup_types mnemonics = msg.mnemonics # local_cache_attribute diff --git a/core/src/apps/eos/actions/__init__.py b/core/src/apps/eos/actions/__init__.py index 56f72e4412..485bab8b35 100644 --- a/core/src/apps/eos/actions/__init__.py +++ b/core/src/apps/eos/actions/__init__.py @@ -1,8 +1,8 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.utils import Writer, HashWriter from trezor.messages import EosTxActionAck + from trezor.utils import HashWriter, Writer async def process_action( @@ -86,9 +86,10 @@ async def process_action( async def _process_unknown_action(w: Writer, action: EosTxActionAck) -> None: from trezor.crypto.hashlib import sha256 - from trezor.utils import HashWriter from trezor.messages import EosTxActionAck, EosTxActionRequest + from trezor.utils import HashWriter from trezor.wire.context import call + from .. import writers from . import layout diff --git a/core/src/apps/eos/actions/layout.py b/core/src/apps/eos/actions/layout.py index b599d247ca..22a8659cb1 100644 --- a/core/src/apps/eos/actions/layout.py +++ b/core/src/apps/eos/actions/layout.py @@ -7,6 +7,7 @@ from ..helpers import eos_asset_to_string, eos_name_to_string if TYPE_CHECKING: from typing import Iterable + from trezor.messages import ( EosActionBuyRam, EosActionBuyRamBytes, @@ -254,6 +255,7 @@ async def confirm_action_unknown(action: EosActionCommon, checksum: bytes) -> No def authorization_fields(auth: EosAuthorization) -> list[PropertyType]: from trezor.wire import DataError + from ..helpers import public_key_to_wif fields: list[PropertyType] = [] diff --git a/core/src/apps/eos/get_public_key.py b/core/src/apps/eos/get_public_key.py index 5d09d39f30..e6eb93aa9f 100644 --- a/core/src/apps/eos/get_public_key.py +++ b/core/src/apps/eos/get_public_key.py @@ -4,6 +4,7 @@ from apps.common.keychain import auto_keychain if TYPE_CHECKING: from trezor.messages import EosGetPublicKey, EosPublicKey + from apps.common.keychain import Keychain @@ -11,7 +12,9 @@ if TYPE_CHECKING: async def get_public_key(msg: EosGetPublicKey, keychain: Keychain) -> EosPublicKey: from trezor.crypto.curve import secp256k1 from trezor.messages import EosPublicKey + from apps.common import paths + from .helpers import public_key_to_wif from .layout import require_get_public_key diff --git a/core/src/apps/eos/sign_tx.py b/core/src/apps/eos/sign_tx.py index 231a7297d2..11c66a8b0b 100644 --- a/core/src/apps/eos/sign_tx.py +++ b/core/src/apps/eos/sign_tx.py @@ -3,23 +3,26 @@ from typing import TYPE_CHECKING from apps.common.keychain import auto_keychain if TYPE_CHECKING: - from trezor.messages import EosSignTx, EosSignedTx + from trezor.messages import EosSignedTx, EosSignTx + from apps.common.keychain import Keychain @auto_keychain(__name__) async def sign_tx(msg: EosSignTx, keychain: Keychain) -> EosSignedTx: - from trezor.wire import DataError - from trezor.wire.context import call from trezor.crypto.curve import secp256k1 from trezor.crypto.hashlib import sha256 from trezor.messages import EosSignedTx, EosTxActionAck, EosTxActionRequest from trezor.utils import HashWriter + from trezor.wire import DataError + from trezor.wire.context import call + from apps.common import paths - from .writers import write_uvarint, write_header, write_bytes_fixed + from .actions import process_action from .helpers import base58_encode from .layout import require_sign_tx + from .writers import write_bytes_fixed, write_header, write_uvarint num_actions = msg.num_actions # local_cache_attribute diff --git a/core/src/apps/eos/writers.py b/core/src/apps/eos/writers.py index df0525b675..d96d5b13fc 100644 --- a/core/src/apps/eos/writers.py +++ b/core/src/apps/eos/writers.py @@ -18,12 +18,12 @@ if TYPE_CHECKING: EosActionDelegate, EosActionDeleteAuth, EosActionLinkAuth, - EosActionUnlinkAuth, EosActionNewAccount, EosActionRefund, EosActionSellRam, EosActionTransfer, EosActionUndelegate, + EosActionUnlinkAuth, EosActionUpdateAuth, EosActionVoteProducer, EosAsset, diff --git a/core/src/apps/ethereum/definitions.py b/core/src/apps/ethereum/definitions.py index 3ec34afee3..5bc567ed6e 100644 --- a/core/src/apps/ethereum/definitions.py +++ b/core/src/apps/ethereum/definitions.py @@ -5,6 +5,7 @@ from trezor.wire import DataError if TYPE_CHECKING: from typing import TypeVar + from typing_extensions import Self DefType = TypeVar("DefType", EthereumNetworkInfo, EthereumTokenInfo) @@ -18,6 +19,7 @@ def decode_definition(definition: bytes, expected_type: type[DefType]) -> DefTyp from trezor.utils import BufferReader from apps.common import readers + from . import definitions_constants as consts # check network definition @@ -142,7 +144,7 @@ class Definitions: return cls(network, tokens) def get_token(self, address: bytes) -> EthereumTokenInfo: - from .tokens import token_by_chain_address, UNKNOWN_TOKEN + from .tokens import UNKNOWN_TOKEN, token_by_chain_address # if we have a built-in definition, use it token = token_by_chain_address(self.network.chain_id, address) diff --git a/core/src/apps/ethereum/get_address.py b/core/src/apps/ethereum/get_address.py index e50a2fa4fe..6a8c12e2cc 100644 --- a/core/src/apps/ethereum/get_address.py +++ b/core/src/apps/ethereum/get_address.py @@ -3,9 +3,10 @@ from typing import TYPE_CHECKING from .keychain import PATTERNS_ADDRESS, with_keychain_from_path if TYPE_CHECKING: - from trezor.messages import EthereumGetAddress, EthereumAddress + from trezor.messages import EthereumAddress, EthereumGetAddress from apps.common.keychain import Keychain + from .definitions import Definitions @@ -17,7 +18,9 @@ async def get_address( ) -> EthereumAddress: from trezor.messages import EthereumAddress from trezor.ui.layouts import show_address + from apps.common import paths + from .helpers import address_from_bytes address_n = msg.address_n # local_cache_attribute diff --git a/core/src/apps/ethereum/get_public_key.py b/core/src/apps/ethereum/get_public_key.py index f7183502ab..c39061d3ed 100644 --- a/core/src/apps/ethereum/get_public_key.py +++ b/core/src/apps/ethereum/get_public_key.py @@ -6,8 +6,10 @@ if TYPE_CHECKING: async def get_public_key(msg: EthereumGetPublicKey) -> EthereumPublicKey: from ubinascii import hexlify + from trezor.messages import EthereumPublicKey, GetPublicKey from trezor.ui.layouts import show_pubkey + from apps.bitcoin import get_public_key as bitcoin_get_public_key # we use the Bitcoin format for Ethereum xpubs diff --git a/core/src/apps/ethereum/helpers.py b/core/src/apps/ethereum/helpers.py index a0bc1725b9..ad3c34a744 100644 --- a/core/src/apps/ethereum/helpers.py +++ b/core/src/apps/ethereum/helpers.py @@ -5,6 +5,7 @@ from . import networks if TYPE_CHECKING: from trezor.messages import EthereumFieldType + from .networks import EthereumNetworkInfo @@ -49,6 +50,7 @@ def address_from_bytes( def bytes_from_address(address: str) -> bytes: from ubinascii import unhexlify + from trezor import wire if len(address) == 40: diff --git a/core/src/apps/ethereum/keychain.py b/core/src/apps/ethereum/keychain.py index a9fcac2ef0..ce523c373e 100644 --- a/core/src/apps/ethereum/keychain.py +++ b/core/src/apps/ethereum/keychain.py @@ -10,8 +10,6 @@ from . import CURVE, definitions, networks if TYPE_CHECKING: from typing import Any, Awaitable, Callable, Iterable, TypeVar - from apps.common.keychain import Keychain - from trezor.messages import ( EthereumGetAddress, EthereumSignMessage, @@ -20,10 +18,7 @@ if TYPE_CHECKING: EthereumSignTypedData, ) - from apps.common.keychain import ( - MsgOut, - Handler, - ) + from apps.common.keychain import Handler, Keychain, MsgOut # messages for "with_keychain_and_network_from_path" decorator MsgInAddressN = TypeVar( diff --git a/core/src/apps/ethereum/layout.py b/core/src/apps/ethereum/layout.py index e3ddd63a11..cf470eac08 100644 --- a/core/src/apps/ethereum/layout.py +++ b/core/src/apps/ethereum/layout.py @@ -30,9 +30,10 @@ def require_confirm_tx( network: EthereumNetworkInfo, token: EthereumTokenInfo | None, ) -> Awaitable[None]: - from .helpers import address_from_bytes from trezor.ui.layouts import confirm_output + from .helpers import address_from_bytes + if to_bytes: to_str = address_from_bytes(to_bytes, network) else: @@ -92,6 +93,7 @@ async def require_confirm_eip1559_fee( def require_confirm_unknown_token(address_bytes: bytes) -> Awaitable[None]: from ubinascii import hexlify + from trezor.ui.layouts import confirm_address contract_address_hex = "0x" + hexlify(address_bytes).decode() @@ -106,6 +108,7 @@ def require_confirm_unknown_token(address_bytes: bytes) -> Awaitable[None]: def require_confirm_address(address_bytes: bytes) -> Awaitable[None]: from ubinascii import hexlify + from trezor.ui.layouts import confirm_address address_hex = "0x" + hexlify(address_bytes).decode() @@ -209,6 +212,7 @@ async def confirm_typed_value( array_index: int | None = None, ) -> None: from trezor.enums import EthereumDataType + from .helpers import get_type_name type_name = get_type_name(field) diff --git a/core/src/apps/ethereum/sign_message.py b/core/src/apps/ethereum/sign_message.py index cd69d0a687..f86b3915ff 100644 --- a/core/src/apps/ethereum/sign_message.py +++ b/core/src/apps/ethereum/sign_message.py @@ -3,12 +3,10 @@ from typing import TYPE_CHECKING from .keychain import PATTERNS_ADDRESS, with_keychain_from_path if TYPE_CHECKING: - from trezor.messages import ( - EthereumSignMessage, - EthereumMessageSignature, - ) + from trezor.messages import EthereumMessageSignature, EthereumSignMessage from apps.common.keychain import Keychain + from .definitions import Definitions diff --git a/core/src/apps/ethereum/sign_tx.py b/core/src/apps/ethereum/sign_tx.py index e782d1f914..bd10054b35 100644 --- a/core/src/apps/ethereum/sign_tx.py +++ b/core/src/apps/ethereum/sign_tx.py @@ -8,8 +8,9 @@ from .helpers import bytes_from_address from .keychain import with_keychain_from_chain_id if TYPE_CHECKING: + from trezor.messages import EthereumSignTx, EthereumTokenInfo, EthereumTxAck + from apps.common.keychain import Keychain - from trezor.messages import EthereumSignTx, EthereumTxAck, EthereumTokenInfo from .definitions import Definitions from .keychain import MsgInSignTx @@ -27,14 +28,12 @@ async def sign_tx( keychain: Keychain, defs: Definitions, ) -> EthereumTxRequest: - from trezor.utils import HashWriter from trezor.crypto.hashlib import sha3_256 + from trezor.utils import HashWriter + from apps.common import paths - from .layout import ( - require_confirm_data, - require_confirm_fee, - require_confirm_tx, - ) + + from .layout import require_confirm_data, require_confirm_fee, require_confirm_tx # check if msg.tx_type not in [1, 6, None]: @@ -103,8 +102,8 @@ async def handle_erc20( msg: MsgInSignTx, definitions: Definitions, ) -> tuple[EthereumTokenInfo | None, bytes, bytes, int]: - from .layout import require_confirm_unknown_token from . import tokens + from .layout import require_confirm_unknown_token data_initial_chunk = msg.data_initial_chunk # local_cache_attribute token = None diff --git a/core/src/apps/ethereum/sign_tx_eip1559.py b/core/src/apps/ethereum/sign_tx_eip1559.py index 1271807162..466b63e93b 100644 --- a/core/src/apps/ethereum/sign_tx_eip1559.py +++ b/core/src/apps/ethereum/sign_tx_eip1559.py @@ -8,11 +8,13 @@ from .keychain import with_keychain_from_chain_id if TYPE_CHECKING: from trezor.messages import ( - EthereumSignTxEIP1559, EthereumAccessList, + EthereumSignTxEIP1559, EthereumTxRequest, ) + from apps.common.keychain import Keychain + from .definitions import Definitions @@ -33,17 +35,19 @@ async def sign_tx_eip1559( keychain: Keychain, defs: Definitions, ) -> EthereumTxRequest: - from trezor.crypto.hashlib import sha3_256 - from trezor.utils import HashWriter from trezor import wire from trezor.crypto import rlp # local_cache_global + from trezor.crypto.hashlib import sha3_256 + from trezor.utils import HashWriter + from apps.common import paths + from .layout import ( require_confirm_data, require_confirm_eip1559_fee, require_confirm_tx, ) - from .sign_tx import handle_erc20, send_request_chunk, check_common_fields + from .sign_tx import check_common_fields, handle_erc20, send_request_chunk gas_limit = msg.gas_limit # local_cache_attribute @@ -156,8 +160,8 @@ def _get_total_length(msg: EthereumSignTxEIP1559, data_total: int) -> int: def _sign_digest( msg: EthereumSignTxEIP1559, keychain: Keychain, digest: bytes ) -> EthereumTxRequest: - from trezor.messages import EthereumTxRequest from trezor.crypto.curve import secp256k1 + from trezor.messages import EthereumTxRequest node = keychain.derive(msg.address_n) signature = secp256k1.sign( diff --git a/core/src/apps/ethereum/sign_typed_data.py b/core/src/apps/ethereum/sign_typed_data.py index 787fd2a436..e03f889d89 100644 --- a/core/src/apps/ethereum/sign_typed_data.py +++ b/core/src/apps/ethereum/sign_typed_data.py @@ -9,16 +9,17 @@ from .keychain import PATTERNS_ADDRESS, with_keychain_from_path from .layout import should_show_struct if TYPE_CHECKING: - from apps.common.keychain import Keychain - from trezor.utils import HashWriter - from .definitions import Definitions - from trezor.messages import ( - EthereumSignTypedData, EthereumFieldType, + EthereumSignTypedData, EthereumTypedDataSignature, EthereumTypedDataStructAck, ) + from trezor.utils import HashWriter + + from apps.common.keychain import Keychain + + from .definitions import Definitions @with_keychain_from_path(*PATTERNS_ADDRESS) @@ -28,10 +29,12 @@ async def sign_typed_data( defs: Definitions, ) -> EthereumTypedDataSignature: from trezor.crypto.curve import secp256k1 + from trezor.messages import EthereumTypedDataSignature + from apps.common import paths + from .helpers import address_from_bytes from .layout import require_confirm_address - from trezor.messages import EthereumTypedDataSignature await paths.validate_path(keychain, msg.address_n) @@ -143,8 +146,8 @@ class TypedDataEnvelope: async def _collect_types(self, type_name: str) -> None: """Recursively collect types from the client.""" from trezor.messages import ( - EthereumTypedDataStructRequest, EthereumTypedDataStructAck, + EthereumTypedDataStructRequest, ) req = EthereumTypedDataStructRequest(name=type_name) diff --git a/core/src/apps/ethereum/verify_message.py b/core/src/apps/ethereum/verify_message.py index abde59aaff..7887cf818b 100644 --- a/core/src/apps/ethereum/verify_message.py +++ b/core/src/apps/ethereum/verify_message.py @@ -5,11 +5,11 @@ if TYPE_CHECKING: async def verify_message(msg: EthereumVerifyMessage) -> Success: - from trezor.wire import DataError from trezor.crypto.curve import secp256k1 from trezor.crypto.hashlib import sha3_256 from trezor.messages import Success from trezor.ui.layouts import confirm_signverify, show_success + from trezor.wire import DataError from apps.common.signverify import decode_message diff --git a/core/src/apps/homescreen/__init__.py b/core/src/apps/homescreen/__init__.py index 3f138e8db7..c2a0a5876a 100644 --- a/core/src/apps/homescreen/__init__.py +++ b/core/src/apps/homescreen/__init__.py @@ -48,8 +48,8 @@ async def homescreen() -> None: async def lockscreen() -> None: - from apps.common.request_pin import can_lock_device from apps.base import unlock_device + from apps.common.request_pin import can_lock_device # Only show the lockscreen UI if the device can in fact be locked. if can_lock_device(): diff --git a/core/src/apps/management/apply_flags.py b/core/src/apps/management/apply_flags.py index e9875284fa..c33d95961c 100644 --- a/core/src/apps/management/apply_flags.py +++ b/core/src/apps/management/apply_flags.py @@ -1,15 +1,14 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.messages import Success - from trezor.messages import ApplyFlags + from trezor.messages import ApplyFlags, Success async def apply_flags(msg: ApplyFlags) -> Success: import storage.device from storage.device import set_flags - from trezor.wire import NotInitialized from trezor.messages import Success + from trezor.wire import NotInitialized if not storage.device.is_initialized(): raise NotInitialized("Device is not initialized") diff --git a/core/src/apps/management/apply_settings.py b/core/src/apps/management/apply_settings.py index 035fc3538d..1dd067afd1 100644 --- a/core/src/apps/management/apply_settings.py +++ b/core/src/apps/management/apply_settings.py @@ -1,15 +1,14 @@ from typing import TYPE_CHECKING +import trezorui2 from trezor import utils from trezor.enums import ButtonRequestType from trezor.ui.layouts import confirm_action, confirm_homescreen, confirm_single from trezor.wire import DataError -import trezorui2 - if TYPE_CHECKING: - from trezor.messages import ApplySettings, Success from trezor.enums import SafetyCheckLevel + from trezor.messages import ApplySettings, Success BRT_PROTECT_CALL = ButtonRequestType.ProtectCall # CACHE @@ -17,7 +16,7 @@ BRT_PROTECT_CALL = ButtonRequestType.ProtectCall # CACHE if utils.INTERNAL_MODEL in ("T1B1", "T2B1"): def _validate_homescreen_model_specific(homescreen: bytes) -> None: - from trezor.ui import WIDTH, HEIGHT + from trezor.ui import HEIGHT, WIDTH try: w, h, is_grayscale = trezorui2.toif_info(homescreen) @@ -31,7 +30,7 @@ if utils.INTERNAL_MODEL in ("T1B1", "T2B1"): else: def _validate_homescreen_model_specific(homescreen: bytes) -> None: - from trezor.ui import WIDTH, HEIGHT + from trezor.ui import HEIGHT, WIDTH try: w, h, mcu_height = trezorui2.jpeg_info(homescreen) @@ -63,10 +62,11 @@ def _validate_homescreen(homescreen: bytes) -> None: async def apply_settings(msg: ApplySettings) -> Success: import storage.device as storage_device - from apps.common import safety_checks from trezor.messages import Success - from trezor.wire import ProcessError, NotInitialized + from trezor.wire import NotInitialized, ProcessError + from apps.base import reload_settings_from_storage + from apps.common import safety_checks if not storage_device.is_initialized(): raise NotInitialized("Device is not initialized") diff --git a/core/src/apps/management/change_wipe_code.py b/core/src/apps/management/change_wipe_code.py index a79c2b5aeb..fb7318b503 100644 --- a/core/src/apps/management/change_wipe_code.py +++ b/core/src/apps/management/change_wipe_code.py @@ -8,14 +8,12 @@ if TYPE_CHECKING: async def change_wipe_code(msg: ChangeWipeCode) -> Success: from storage.device import is_initialized - from trezor.wire import NotInitialized - from trezor.ui.layouts import show_success - from trezor.messages import Success from trezor import config - from apps.common.request_pin import ( - error_pin_invalid, - request_pin_and_sd_salt, - ) + from trezor.messages import Success + from trezor.ui.layouts import show_success + from trezor.wire import NotInitialized + + from apps.common.request_pin import error_pin_invalid, request_pin_and_sd_salt if not is_initialized(): raise NotInitialized("Device is not initialized") @@ -59,8 +57,8 @@ async def change_wipe_code(msg: ChangeWipeCode) -> Success: def _require_confirm_action( msg: ChangeWipeCode, has_wipe_code: bool ) -> Awaitable[None]: - from trezor.wire import ProcessError from trezor.ui.layouts import confirm_action, confirm_set_new_pin + from trezor.wire import ProcessError title = "Wipe code settings" @@ -93,13 +91,14 @@ def _require_confirm_action( async def _request_wipe_code_confirm(pin: str) -> str: - from apps.common.request_pin import request_pin from trezor.ui.layouts import ( confirm_reenter_pin, pin_mismatch_popup, wipe_code_same_as_pin_popup, ) + from apps.common.request_pin import request_pin + while True: code1 = await request_pin("Enter new wipe code") if code1 == pin: diff --git a/core/src/apps/management/get_next_u2f_counter.py b/core/src/apps/management/get_next_u2f_counter.py index d0c51b2d26..4c79f8e871 100644 --- a/core/src/apps/management/get_next_u2f_counter.py +++ b/core/src/apps/management/get_next_u2f_counter.py @@ -6,10 +6,10 @@ if TYPE_CHECKING: async def get_next_u2f_counter(msg: GetNextU2FCounter) -> NextU2FCounter: import storage.device as storage_device - from trezor.wire import NotInitialized from trezor.enums import ButtonRequestType from trezor.messages import NextU2FCounter from trezor.ui.layouts import confirm_action + from trezor.wire import NotInitialized if not storage_device.is_initialized(): raise NotInitialized("Device is not initialized") diff --git a/core/src/apps/management/reboot_to_bootloader.py b/core/src/apps/management/reboot_to_bootloader.py index 191508b48e..c5f0e42636 100644 --- a/core/src/apps/management/reboot_to_bootloader.py +++ b/core/src/apps/management/reboot_to_bootloader.py @@ -1,9 +1,10 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.messages import RebootToBootloader from typing import NoReturn + from trezor.messages import RebootToBootloader + async def reboot_to_bootloader(msg: RebootToBootloader) -> NoReturn: from trezor import io, loop, utils diff --git a/core/src/apps/management/recovery_device/__init__.py b/core/src/apps/management/recovery_device/__init__.py index b38b3e2b84..d44c5f57ac 100644 --- a/core/src/apps/management/recovery_device/__init__.py +++ b/core/src/apps/management/recovery_device/__init__.py @@ -1,8 +1,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.messages import RecoveryDevice - from trezor.messages import Success + from trezor.messages import RecoveryDevice, Success # List of RecoveryDevice fields that can be set when doing dry-run recovery. # All except `dry_run` are allowed for T1 compatibility, but their values are ignored. @@ -23,11 +22,13 @@ async def recovery_device(msg: RecoveryDevice) -> Success: from trezor import config, wire, workflow from trezor.enums import ButtonRequestType from trezor.ui.layouts import confirm_action, confirm_reset_device + from apps.common.request_pin import ( error_pin_invalid, request_pin_and_sd_salt, request_pin_confirm, ) + from .homescreen import recovery_homescreen, recovery_process dry_run = msg.dry_run # local_cache_attribute diff --git a/core/src/apps/management/recovery_device/homescreen.py b/core/src/apps/management/recovery_device/homescreen.py index 1c5019ad34..ef44dfe592 100644 --- a/core/src/apps/management/recovery_device/homescreen.py +++ b/core/src/apps/management/recovery_device/homescreen.py @@ -15,6 +15,7 @@ if TYPE_CHECKING: async def recovery_homescreen() -> None: from trezor import workflow + from apps.homescreen import homescreen if not storage_recovery.is_in_progress(): @@ -25,8 +26,8 @@ async def recovery_homescreen() -> None: async def recovery_process() -> Success: - from trezor.enums import MessageType import storage + from trezor.enums import MessageType wire.AVOID_RESTARTING_FOR = (MessageType.Initialize, MessageType.GetFeatures) try: @@ -41,8 +42,8 @@ async def recovery_process() -> Success: async def _continue_recovery_process() -> Success: - from trezor.errors import MnemonicError from trezor import utils + from trezor.errors import MnemonicError # gather the current recovery state from storage dry_run = storage_recovery.is_dry_run() @@ -101,8 +102,9 @@ async def _continue_recovery_process() -> Success: async def _finish_recovery_dry_run(secret: bytes, backup_type: BackupType) -> Success: - from trezor.crypto.hashlib import sha256 from trezor import utils + from trezor.crypto.hashlib import sha256 + from apps.common import mnemonic if backup_type is None: @@ -136,8 +138,8 @@ async def _finish_recovery_dry_run(secret: bytes, backup_type: BackupType) -> Su async def _finish_recovery(secret: bytes, backup_type: BackupType) -> Success: - from trezor.ui.layouts import show_success from trezor.enums import BackupType + from trezor.ui.layouts import show_success if backup_type is None: raise RuntimeError diff --git a/core/src/apps/management/recovery_device/layout.py b/core/src/apps/management/recovery_device/layout.py index e34c7f1402..0bdf859c41 100644 --- a/core/src/apps/management/recovery_device/layout.py +++ b/core/src/apps/management/recovery_device/layout.py @@ -13,6 +13,7 @@ from .. import backup_types if TYPE_CHECKING: from typing import Callable + from trezor.enums import BackupType @@ -40,10 +41,11 @@ async def _confirm_abort(dry_run: bool = False) -> None: async def request_mnemonic( word_count: int, backup_type: BackupType | None ) -> str | None: - from . import word_validity from trezor.ui.layouts.common import button_request from trezor.ui.layouts.recovery import request_word + from . import word_validity + await button_request("mnemonic", code=ButtonRequestType.MnemonicInput) words: list[str] = [] @@ -123,10 +125,11 @@ async def homescreen_dialog( info_func: Callable | None = None, show_info: bool = False, ) -> None: - from .recover import RecoveryAborted import storage.recovery as storage_recovery - from trezor.wire import ActionCancelled from trezor.ui.layouts.recovery import continue_recovery + from trezor.wire import ActionCancelled + + from .recover import RecoveryAborted while True: dry_run = storage_recovery.is_dry_run() diff --git a/core/src/apps/management/recovery_device/word_validity.py b/core/src/apps/management/recovery_device/word_validity.py index cf5cb1030e..5989b045fa 100644 --- a/core/src/apps/management/recovery_device/word_validity.py +++ b/core/src/apps/management/recovery_device/word_validity.py @@ -22,6 +22,7 @@ class ThresholdReached(WordValidityResult): def check(backup_type: BackupType | None, partial_mnemonic: list[str]) -> None: from trezor.enums import BackupType + from . import recover # we can't perform any checks if the backup type was not yet decided diff --git a/core/src/apps/management/reset_device/__init__.py b/core/src/apps/management/reset_device/__init__.py index 41d16738d0..0c24fef3fc 100644 --- a/core/src/apps/management/reset_device/__init__.py +++ b/core/src/apps/management/reset_device/__init__.py @@ -12,8 +12,7 @@ if __debug__: import storage.debug if TYPE_CHECKING: - from trezor.messages import ResetDevice - from trezor.messages import Success + from trezor.messages import ResetDevice, Success BAK_T_BIP39 = BackupType.Bip39 # global_import_cache @@ -24,16 +23,14 @@ _DEFAULT_BACKUP_TYPE = BAK_T_BIP39 async def reset_device(msg: ResetDevice) -> Success: from trezor import config - from apps.common.request_pin import request_pin_confirm - from trezor.ui.layouts import ( - prompt_backup, - confirm_reset_device, - ) from trezor.crypto import bip39, random - from trezor.messages import Success, EntropyAck, EntropyRequest + from trezor.messages import EntropyAck, EntropyRequest, Success from trezor.pin import render_empty_loader + from trezor.ui.layouts import confirm_reset_device, prompt_backup from trezor.wire.context import call + from apps.common.request_pin import request_pin_confirm + backup_type = msg.backup_type # local_cache_attribute # validate parameters and device state @@ -177,9 +174,10 @@ async def _backup_slip39_advanced(encrypted_master_secret: bytes) -> None: def _validate_reset_device(msg: ResetDevice) -> None: - from .. import backup_types from trezor.wire import UnexpectedMessage + from .. import backup_types + backup_type = msg.backup_type or _DEFAULT_BACKUP_TYPE if backup_type not in ( BAK_T_BIP39, diff --git a/core/src/apps/management/sd_protect.py b/core/src/apps/management/sd_protect.py index 40493f7e95..73ba26b266 100644 --- a/core/src/apps/management/sd_protect.py +++ b/core/src/apps/management/sd_protect.py @@ -13,6 +13,7 @@ from apps.common.sdcard import ensure_sdcard if TYPE_CHECKING: from typing import Awaitable + from trezor.messages import SdProtect diff --git a/core/src/apps/management/wipe_device.py b/core/src/apps/management/wipe_device.py index 4ebf760427..5a2f3e6ad4 100644 --- a/core/src/apps/management/wipe_device.py +++ b/core/src/apps/management/wipe_device.py @@ -1,7 +1,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.messages import WipeDevice, Success + from trezor.messages import Success, WipeDevice async def wipe_device(msg: WipeDevice) -> Success: diff --git a/core/src/apps/misc/cipher_key_value.py b/core/src/apps/misc/cipher_key_value.py index b7e03e870d..3bf22aee35 100644 --- a/core/src/apps/misc/cipher_key_value.py +++ b/core/src/apps/misc/cipher_key_value.py @@ -1,19 +1,20 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.messages import CipherKeyValue, CipheredKeyValue + from trezor.messages import CipheredKeyValue, CipherKeyValue # This module implements the SLIP-0011 symmetric encryption of key-value pairs using a # deterministic hierarchy, see https://github.com/satoshilabs/slips/blob/master/slip-0011.md. async def cipher_key_value(msg: CipherKeyValue) -> CipheredKeyValue: - from trezor.wire import DataError - from trezor.messages import CipheredKeyValue from trezor.crypto import aes, hmac + from trezor.messages import CipheredKeyValue + from trezor.ui.layouts import confirm_action + from trezor.wire import DataError + from apps.common.keychain import get_keychain from apps.common.paths import AlwaysMatchingSchema - from trezor.ui.layouts import confirm_action keychain = await get_keychain("secp256k1", [AlwaysMatchingSchema]) diff --git a/core/src/apps/misc/cosi_commit.py b/core/src/apps/misc/cosi_commit.py index b4afdb9646..b682ff7ab2 100644 --- a/core/src/apps/misc/cosi_commit.py +++ b/core/src/apps/misc/cosi_commit.py @@ -60,6 +60,7 @@ async def cosi_commit(msg: CosiCommit) -> CosiSignature: from trezor.crypto.curve import ed25519 from trezor.ui.layouts import confirm_blob, confirm_text from trezor.wire.context import call + from apps.common import paths from apps.common.keychain import get_keychain diff --git a/core/src/apps/misc/get_ecdh_session_key.py b/core/src/apps/misc/get_ecdh_session_key.py index a978295b77..5308fe6b26 100644 --- a/core/src/apps/misc/get_ecdh_session_key.py +++ b/core/src/apps/misc/get_ecdh_session_key.py @@ -1,24 +1,26 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.messages import GetECDHSessionKey, ECDHSessionKey + from trezor.messages import ECDHSessionKey, GetECDHSessionKey # This module implements the SLIP-0017 Elliptic Curve Diffie-Hellman algorithm, using a # deterministic hierarchy, see https://github.com/satoshilabs/slips/blob/master/slip-0017.md. async def get_ecdh_session_key(msg: GetECDHSessionKey) -> ECDHSessionKey: - from trezor.ui.layouts import confirm_address - from .sign_identity import ( - get_identity_path, - serialize_identity_without_proto, - serialize_identity, - ) - from trezor.wire import DataError from trezor.messages import ECDHSessionKey + from trezor.ui.layouts import confirm_address + from trezor.wire import DataError + from apps.common.keychain import get_keychain from apps.common.paths import AlwaysMatchingSchema + from .sign_identity import ( + get_identity_path, + serialize_identity, + serialize_identity_without_proto, + ) + msg_identity = msg.identity # local_cache_attribute peer_public_key = msg.peer_public_key # local_cache_attribute curve_name = msg.ecdsa_curve_name or "secp256k1" diff --git a/core/src/apps/misc/get_entropy.py b/core/src/apps/misc/get_entropy.py index 01d37d27f6..75b56e7e92 100644 --- a/core/src/apps/misc/get_entropy.py +++ b/core/src/apps/misc/get_entropy.py @@ -1,7 +1,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.messages import GetEntropy, Entropy + from trezor.messages import Entropy, GetEntropy async def get_entropy(msg: GetEntropy) -> Entropy: diff --git a/core/src/apps/misc/get_firmware_hash.py b/core/src/apps/misc/get_firmware_hash.py index bdf3db5c56..9f40a15723 100644 --- a/core/src/apps/misc/get_firmware_hash.py +++ b/core/src/apps/misc/get_firmware_hash.py @@ -1,17 +1,17 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.messages import GetFirmwareHash, FirmwareHash + from trezor.messages import FirmwareHash, GetFirmwareHash from trezor.ui.layouts.common import ProgressLayout _progress_obj: ProgressLayout | None = None async def get_firmware_hash(msg: GetFirmwareHash) -> FirmwareHash: - from trezor.messages import FirmwareHash - from trezor.utils import firmware_hash - from trezor.ui.layouts.progress import progress from trezor import wire, workflow + from trezor.messages import FirmwareHash + from trezor.ui.layouts.progress import progress + from trezor.utils import firmware_hash workflow.close_others() global _progress_obj diff --git a/core/src/apps/misc/sign_identity.py b/core/src/apps/misc/sign_identity.py index b1ec968cc8..90863f7ef5 100644 --- a/core/src/apps/misc/sign_identity.py +++ b/core/src/apps/misc/sign_identity.py @@ -5,7 +5,8 @@ from trezor.crypto.hashlib import sha256 from apps.common import coininfo if TYPE_CHECKING: - from trezor.messages import IdentityType, SignIdentity, SignedIdentity + from trezor.messages import IdentityType, SignedIdentity, SignIdentity + from apps.common.paths import Bip32Path # This module implements the SLIP-0013 authentication using a deterministic hierarchy, see @@ -15,6 +16,7 @@ if TYPE_CHECKING: async def sign_identity(msg: SignIdentity) -> SignedIdentity: from trezor.messages import SignedIdentity from trezor.ui.layouts import confirm_sign_identity + from apps.common.keychain import get_keychain from apps.common.paths import AlwaysMatchingSchema @@ -89,6 +91,7 @@ def serialize_identity_without_proto(identity: IdentityType) -> str: def get_identity_path(identity: str, index: int, num: int) -> Bip32Path: from ustruct import pack, unpack + from apps.common.paths import HARDENED identity_hash = sha256(pack(" bytes: - from apps.common.signverify import message_digest from trezor.wire import DataError + from apps.common.signverify import message_digest + if sigtype == "gpg": data = challenge_hidden elif sigtype == "signify": diff --git a/core/src/apps/monero/get_address.py b/core/src/apps/monero/get_address.py index 454fd8ec6e..be7970f5a9 100644 --- a/core/src/apps/monero/get_address.py +++ b/core/src/apps/monero/get_address.py @@ -3,7 +3,7 @@ from typing import TYPE_CHECKING from apps.common.keychain import auto_keychain if TYPE_CHECKING: - from trezor.messages import MoneroGetAddress, MoneroAddress + from trezor.messages import MoneroAddress, MoneroGetAddress from apps.common.keychain import Keychain diff --git a/core/src/apps/monero/get_tx_keys.py b/core/src/apps/monero/get_tx_keys.py index f7a6d14eab..2ed6d21efa 100644 --- a/core/src/apps/monero/get_tx_keys.py +++ b/core/src/apps/monero/get_tx_keys.py @@ -22,7 +22,8 @@ from apps.common.keychain import auto_keychain _GET_TX_KEY_REASON_TX_DERIVATION = const(1) if TYPE_CHECKING: - from trezor.messages import MoneroGetTxKeyRequest, MoneroGetTxKeyAck + from trezor.messages import MoneroGetTxKeyAck, MoneroGetTxKeyRequest + from apps.common.keychain import Keychain diff --git a/core/src/apps/monero/get_watch_only.py b/core/src/apps/monero/get_watch_only.py index cb96360a48..322f05d05e 100644 --- a/core/src/apps/monero/get_watch_only.py +++ b/core/src/apps/monero/get_watch_only.py @@ -10,10 +10,11 @@ if TYPE_CHECKING: @auto_keychain(__name__) async def get_watch_only(msg: MoneroGetWatchKey, keychain: Keychain) -> MoneroWatchKey: + from trezor.messages import MoneroWatchKey + from apps.common import paths from apps.monero import layout, misc from apps.monero.xmr import crypto_helpers - from trezor.messages import MoneroWatchKey await paths.validate_path(keychain, msg.address_n) diff --git a/core/src/apps/monero/key_image_sync.py b/core/src/apps/monero/key_image_sync.py index 39b02311c6..b852b3f4b1 100644 --- a/core/src/apps/monero/key_image_sync.py +++ b/core/src/apps/monero/key_image_sync.py @@ -7,9 +7,9 @@ from apps.monero import layout if TYPE_CHECKING: from trezor.messages import ( + MoneroKeyImageExportInitAck, MoneroKeyImageExportInitRequest, MoneroKeyImageSyncFinalAck, - MoneroKeyImageExportInitAck, MoneroKeyImageSyncStepAck, MoneroKeyImageSyncStepRequest, ) @@ -25,6 +25,7 @@ async def key_image_sync( msg: MoneroKeyImageExportInitRequest, keychain: Keychain ) -> MoneroKeyImageSyncFinalAck: import gc + from trezor.messages import ( MoneroKeyImageSyncFinalAck, MoneroKeyImageSyncFinalRequest, @@ -69,11 +70,12 @@ async def _init_step( msg: MoneroKeyImageExportInitRequest, keychain: Keychain, ) -> MoneroKeyImageExportInitAck: - from trezor.messages import MoneroKeyImageExportInitAck from trezor.crypto import random + from trezor.messages import MoneroKeyImageExportInitAck + from apps.common import paths - from apps.monero.xmr import monero from apps.monero import misc + from apps.monero.xmr import monero await paths.validate_path(keychain, msg.address_n) @@ -99,10 +101,8 @@ def _sync_step( progress: ProgressLayout, ) -> MoneroKeyImageSyncStepAck: from trezor import log - from trezor.messages import ( - MoneroExportedKeyImage, - MoneroKeyImageSyncStepAck, - ) + from trezor.messages import MoneroExportedKeyImage, MoneroKeyImageSyncStepAck + from apps.monero.xmr import chacha_poly, crypto, key_image assert s.creds is not None diff --git a/core/src/apps/monero/layout.py b/core/src/apps/monero/layout.py index 249ab97d6e..31d0c20fff 100644 --- a/core/src/apps/monero/layout.py +++ b/core/src/apps/monero/layout.py @@ -13,10 +13,7 @@ DUMMY_PAYMENT_ID = b"\x00\x00\x00\x00\x00\x00\x00\x00" if TYPE_CHECKING: from trezor.enums import MoneroNetworkType - from trezor.messages import ( - MoneroTransactionData, - MoneroTransactionDestinationEntry, - ) + from trezor.messages import MoneroTransactionData, MoneroTransactionDestinationEntry from .signing.state import State @@ -150,9 +147,10 @@ async def _require_confirm_output( """ Single transaction destination confirmation """ + from trezor.ui.layouts import confirm_output + from apps.monero.xmr.addresses import encode_addr from apps.monero.xmr.networks import net_version - from trezor.ui.layouts import confirm_output version = net_version(network_type, dst.is_subaddress, payment_id is not None) addr = encode_addr( diff --git a/core/src/apps/monero/live_refresh.py b/core/src/apps/monero/live_refresh.py index 33d179356a..011b2e2837 100644 --- a/core/src/apps/monero/live_refresh.py +++ b/core/src/apps/monero/live_refresh.py @@ -5,13 +5,14 @@ from apps.monero import layout, misc if TYPE_CHECKING: from trezor.messages import ( - MoneroLiveRefreshStepAck, - MoneroLiveRefreshStepRequest, - MoneroLiveRefreshStartRequest, MoneroLiveRefreshFinalAck, MoneroLiveRefreshStartAck, + MoneroLiveRefreshStartRequest, + MoneroLiveRefreshStepAck, + MoneroLiveRefreshStepRequest, ) from trezor.ui.layouts.common import ProgressLayout + from apps.common.keychain import Keychain from .xmr.credentials import AccountCreds @@ -22,6 +23,7 @@ async def live_refresh( msg: MoneroLiveRefreshStartRequest, keychain: Keychain ) -> MoneroLiveRefreshFinalAck: import gc + from trezor.enums import MessageType from trezor.messages import MoneroLiveRefreshFinalAck, MoneroLiveRefreshStepRequest from trezor.wire.context import call_any @@ -56,9 +58,10 @@ async def _init_step( keychain: Keychain, ) -> MoneroLiveRefreshStartAck: import storage.cache as storage_cache - from apps.common import paths from trezor.messages import MoneroLiveRefreshStartAck + from apps.common import paths + await paths.validate_path(keychain, msg.address_n) if not storage_cache.get(storage_cache.APP_MONERO_LIVE_REFRESH): @@ -75,8 +78,9 @@ def _refresh_step( msg: MoneroLiveRefreshStepRequest, progress: ProgressLayout, ) -> MoneroLiveRefreshStepAck: - from trezor.messages import MoneroLiveRefreshStepAck from trezor import log + from trezor.messages import MoneroLiveRefreshStepAck + from apps.monero.xmr import chacha_poly, crypto, crypto_helpers, key_image, monero assert s.creds is not None diff --git a/core/src/apps/monero/misc.py b/core/src/apps/monero/misc.py index 83b8ce1ab2..d6af6cbc4b 100644 --- a/core/src/apps/monero/misc.py +++ b/core/src/apps/monero/misc.py @@ -1,13 +1,13 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: + from trezor.enums import MoneroNetworkType + from apps.common.keychain import Keychain from apps.common.paths import Bip32Path - from trezor.enums import MoneroNetworkType - - from .xmr.crypto import Scalar from .xmr.credentials import AccountCreds + from .xmr.crypto import Scalar def get_creds( @@ -45,6 +45,7 @@ def compute_enc_key_host( view_key_private: Scalar, tx_prefix_hash: bytes ) -> tuple[bytes, bytes]: from trezor.crypto import random + from apps.monero.xmr import crypto_helpers salt = random.bytes(32) diff --git a/core/src/apps/monero/sign_tx.py b/core/src/apps/monero/sign_tx.py index 92d044fbc9..842b7c589f 100644 --- a/core/src/apps/monero/sign_tx.py +++ b/core/src/apps/monero/sign_tx.py @@ -5,6 +5,7 @@ from apps.monero.layout import MoneroTransactionProgress if TYPE_CHECKING: from trezor.messages import MoneroTransactionFinalAck + from apps.common.keychain import Keychain from apps.monero.signing.state import State @@ -12,8 +13,10 @@ if TYPE_CHECKING: @auto_keychain(__name__) async def sign_tx(received_msg, keychain: Keychain) -> MoneroTransactionFinalAck: import gc + from trezor import log, utils from trezor.wire.context import get_context + from apps.monero.signing.state import State state = State() @@ -48,8 +51,8 @@ async def sign_tx(received_msg, keychain: Keychain) -> MoneroTransactionFinalAck async def _sign_tx_dispatch( state: State, msg, keychain: Keychain, progress: MoneroTransactionProgress ) -> tuple: - from trezor.enums import MessageType from trezor import wire + from trezor.enums import MessageType MESSAGE_WIRE_TYPE = msg.MESSAGE_WIRE_TYPE # local_cache_attribute diff --git a/core/src/apps/monero/signing/offloading_keys.py b/core/src/apps/monero/signing/offloading_keys.py index bbf91e1b18..252adf39e5 100644 --- a/core/src/apps/monero/signing/offloading_keys.py +++ b/core/src/apps/monero/signing/offloading_keys.py @@ -26,6 +26,7 @@ def _build_key( Creates an unique-purpose key """ from trezor import utils + from apps.monero.xmr import crypto_helpers key_buff = _BUILD_KEY_BUFFER @@ -115,6 +116,7 @@ def gen_hmac_vini( are uncheckable, decoy keys in step 9 are just random keys. """ from trezor import protobuf + from apps.monero.xmr.keccak_hasher import get_keccak_writer kwriter = get_keccak_writer() @@ -143,6 +145,7 @@ def gen_hmac_vouti( Generates HMAC for (TxDestinationEntry[i] || tx.vout[i]) """ from trezor import protobuf + from apps.monero.xmr.keccak_hasher import get_keccak_writer kwriter = get_keccak_writer() @@ -161,6 +164,7 @@ def gen_hmac_tsxdest( Generates HMAC for TxDestinationEntry[i] """ from trezor import protobuf + from apps.monero.xmr.keccak_hasher import get_keccak_writer kwriter = get_keccak_writer() diff --git a/core/src/apps/monero/signing/state.py b/core/src/apps/monero/signing/state.py index e6bfc6bbce..545cd485cb 100644 --- a/core/src/apps/monero/signing/state.py +++ b/core/src/apps/monero/signing/state.py @@ -1,10 +1,11 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from apps.monero.xmr.crypto import Point, Scalar - from apps.monero.xmr.credentials import AccountCreds from trezor.messages import MoneroTransactionDestinationEntry + from apps.monero.xmr.credentials import AccountCreds + from apps.monero.xmr.crypto import Point, Scalar + Subaddresses = dict[bytes, tuple[int, int]] @@ -19,9 +20,9 @@ class State: STEP_SIGN = 600 def __init__(self) -> None: + from apps.monero.xmr import crypto from apps.monero.xmr.keccak_hasher import KeccakXmrArchive from apps.monero.xmr.mlsag_hasher import PreMlsagHasher - from apps.monero.xmr import crypto # Account credentials # type: AccountCreds @@ -131,6 +132,7 @@ class State: def mem_trace(self, x=None, collect: bool = False) -> None: import gc + from trezor import log if __debug__: diff --git a/core/src/apps/monero/signing/step_01_init_transaction.py b/core/src/apps/monero/signing/step_01_init_transaction.py index adb455292b..f0a956ef40 100644 --- a/core/src/apps/monero/signing/step_01_init_transaction.py +++ b/core/src/apps/monero/signing/step_01_init_transaction.py @@ -30,9 +30,10 @@ async def init_transaction( progress: MoneroTransactionProgress, ) -> MoneroTransactionInitAck: import gc - from apps.monero.signing import offloading_keys + from apps.common import paths from apps.monero import layout, misc + from apps.monero.signing import offloading_keys mem_trace = state.mem_trace # local_cache_attribute outputs = tsx_data.outputs # local_cache_attribute @@ -125,10 +126,7 @@ async def init_transaction( mem_trace(6) - from trezor.messages import ( - MoneroTransactionInitAck, - MoneroTransactionRsigData, - ) + from trezor.messages import MoneroTransactionInitAck, MoneroTransactionRsigData rsig_data = MoneroTransactionRsigData(offload_type=int(state.rsig_offload)) @@ -293,6 +291,7 @@ def _compute_sec_keys(state: State, tsx_data: MoneroTransactionData) -> None: Generate master key H( H(TsxData || tx_priv) || rand ) """ from trezor import protobuf + from apps.monero.xmr.keccak_hasher import get_keccak_writer writer = get_keccak_writer() @@ -372,9 +371,10 @@ def _get_key_for_payment_id_encryption( payment id encryption. If no encrypted payment ID is chosen, dummy payment ID is set for better transaction uniformity if possible. """ - from apps.monero.xmr.addresses import addr_eq from trezor.messages import MoneroAccountPublicAddress + from apps.monero.xmr.addresses import addr_eq + addr = MoneroAccountPublicAddress( spend_public_key=crypto_helpers.NULL_KEY_ENC, view_public_key=crypto_helpers.NULL_KEY_ENC, diff --git a/core/src/apps/monero/signing/step_02_set_input.py b/core/src/apps/monero/signing/step_02_set_input.py index 55c01bce69..6fe5d6eee1 100644 --- a/core/src/apps/monero/signing/step_02_set_input.py +++ b/core/src/apps/monero/signing/step_02_set_input.py @@ -16,14 +16,16 @@ from typing import TYPE_CHECKING from apps.monero.xmr import crypto_helpers if TYPE_CHECKING: - from .state import State from trezor.messages import ( - MoneroTransactionSourceEntry, MoneroTransactionSetInputAck, + MoneroTransactionSourceEntry, ) + from apps.monero.layout import MoneroTransactionProgress from apps.monero.xmr import crypto + from .state import State + def set_input( state: State, @@ -31,9 +33,10 @@ def set_input( progress: MoneroTransactionProgress, ) -> MoneroTransactionSetInputAck: from trezor.messages import MoneroTransactionSetInputAck - from apps.monero.xmr.serialize_messages.tx_prefix import TxinToKey - from apps.monero.xmr import chacha_poly, monero, serialize + from apps.monero.signing import offloading_keys + from apps.monero.xmr import chacha_poly, monero, serialize + from apps.monero.xmr.serialize_messages.tx_prefix import TxinToKey state.current_input_index += 1 current_input_index = state.current_input_index # local_cache_attribute diff --git a/core/src/apps/monero/signing/step_04_input_vini.py b/core/src/apps/monero/signing/step_04_input_vini.py index 995f2b1dfa..b40a30724d 100644 --- a/core/src/apps/monero/signing/step_04_input_vini.py +++ b/core/src/apps/monero/signing/step_04_input_vini.py @@ -10,9 +10,11 @@ if TYPE_CHECKING: MoneroTransactionInputViniAck, MoneroTransactionSourceEntry, ) - from .state import State + from apps.monero.layout import MoneroTransactionProgress + from .state import State + def input_vini( state: State, @@ -22,11 +24,11 @@ def input_vini( orig_idx: int, progress: MoneroTransactionProgress, ) -> MoneroTransactionInputViniAck: + from trezor.messages import MoneroTransactionInputViniAck + from apps.monero.signing import offloading_keys from apps.monero.xmr import crypto - from trezor.messages import MoneroTransactionInputViniAck - STEP_VINI = state.STEP_VINI # local_cache_attribute progress.step(state, STEP_VINI, state.current_input_index + 1) diff --git a/core/src/apps/monero/signing/step_05_all_inputs_set.py b/core/src/apps/monero/signing/step_05_all_inputs_set.py index ca2890e998..66cef25996 100644 --- a/core/src/apps/monero/signing/step_05_all_inputs_set.py +++ b/core/src/apps/monero/signing/step_05_all_inputs_set.py @@ -7,16 +7,19 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from trezor.messages import MoneroTransactionAllInputsSetAck - from .state import State + from apps.monero.layout import MoneroTransactionProgress + from .state import State + def all_inputs_set( state: State, progress: MoneroTransactionProgress ) -> MoneroTransactionAllInputsSetAck: - from apps.monero.xmr import crypto from trezor.messages import MoneroTransactionAllInputsSetAck + from apps.monero.xmr import crypto + state.mem_trace(0) progress.step(state, state.STEP_ALL_IN) diff --git a/core/src/apps/monero/signing/step_06_set_output.py b/core/src/apps/monero/signing/step_06_set_output.py index b3661315c3..4987463019 100644 --- a/core/src/apps/monero/signing/step_06_set_output.py +++ b/core/src/apps/monero/signing/step_06_set_output.py @@ -10,14 +10,16 @@ from apps.monero.signing import offloading_keys from apps.monero.xmr import crypto, crypto_helpers if TYPE_CHECKING: - from apps.monero.xmr.serialize_messages.tx_ecdh import EcdhTuple - from apps.monero.xmr.serialize_messages.tx_rsig_bulletproof import BulletproofPlus - from apps.monero.layout import MoneroTransactionProgress from trezor.messages import ( MoneroTransactionDestinationEntry, - MoneroTransactionSetOutputAck, MoneroTransactionRsigData, + MoneroTransactionSetOutputAck, ) + + from apps.monero.layout import MoneroTransactionProgress + from apps.monero.xmr.serialize_messages.tx_ecdh import EcdhTuple + from apps.monero.xmr.serialize_messages.tx_rsig_bulletproof import BulletproofPlus + from .state import State @@ -337,9 +339,8 @@ def _rsig_bp(state: State) -> bytes: def _rsig_process_bp(state: State, rsig_data: MoneroTransactionRsigData): - from apps.monero.xmr import range_signatures + from apps.monero.xmr import range_signatures, serialize from apps.monero.xmr.serialize_messages.tx_rsig_bulletproof import BulletproofPlus - from apps.monero.xmr import serialize bp_obj = serialize.parse_msg(rsig_data.rsig, BulletproofPlus) rsig_data.rsig = None diff --git a/core/src/apps/monero/signing/step_07_all_outputs_set.py b/core/src/apps/monero/signing/step_07_all_outputs_set.py index 650f01f4d0..f2b8b2c94a 100644 --- a/core/src/apps/monero/signing/step_07_all_outputs_set.py +++ b/core/src/apps/monero/signing/step_07_all_outputs_set.py @@ -8,7 +8,9 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from trezor.messages import MoneroTransactionAllOutSetAck + from apps.monero.layout import MoneroTransactionProgress + from .state import State @@ -58,8 +60,7 @@ def all_outputs_set( # transaction prefix matches expected transaction prefix sent in the # init step. - from trezor.messages import MoneroRingCtSig - from trezor.messages import MoneroTransactionAllOutSetAck + from trezor.messages import MoneroRingCtSig, MoneroTransactionAllOutSetAck # Initializes RCTsig structure (fee, tx prefix hash, type) rv_pb = MoneroRingCtSig( @@ -125,6 +126,7 @@ def _set_tx_extra(state: State) -> bytes: Tag ordering: TX_EXTRA_TAG_PUBKEY, TX_EXTRA_TAG_ADDITIONAL_PUBKEYS, TX_EXTRA_NONCE """ from trezor import utils + from apps.monero.xmr import crypto from apps.monero.xmr.serialize import int_serialize diff --git a/core/src/apps/monero/signing/step_09_sign_input.py b/core/src/apps/monero/signing/step_09_sign_input.py index eba7619865..6003c96cd6 100644 --- a/core/src/apps/monero/signing/step_09_sign_input.py +++ b/core/src/apps/monero/signing/step_09_sign_input.py @@ -14,9 +14,13 @@ import gc from typing import TYPE_CHECKING if TYPE_CHECKING: + from trezor.messages import ( + MoneroTransactionSignInputAck, + MoneroTransactionSourceEntry, + ) + from apps.monero.layout import MoneroTransactionProgress - from trezor.messages import MoneroTransactionSourceEntry - from trezor.messages import MoneroTransactionSignInputAck + from .state import State @@ -46,8 +50,8 @@ def sign_input( :return: Generated signature MGs[i] """ from trezor import utils - from apps.monero.xmr import crypto_helpers - from apps.monero.xmr import crypto + + from apps.monero.xmr import crypto, crypto_helpers ensure = utils.ensure # local_cache_attribute mem_trace = state.mem_trace # local_cache_attribute @@ -216,8 +220,8 @@ def _protect_signature(state: State, mg_buffer: list[bytes]) -> list[bytes]: After protocol finishes without error, opening_key is sent to the host. """ - from trezor.crypto import random - from trezor.crypto import chacha20poly1305 + from trezor.crypto import chacha20poly1305, random + from apps.monero.signing import offloading_keys if state.last_step != state.STEP_SIGN: diff --git a/core/src/apps/monero/signing/step_10_sign_final.py b/core/src/apps/monero/signing/step_10_sign_final.py index 2bd6c713f1..312b537304 100644 --- a/core/src/apps/monero/signing/step_10_sign_final.py +++ b/core/src/apps/monero/signing/step_10_sign_final.py @@ -12,15 +12,16 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from trezor.messages import MoneroTransactionFinalAck + from .state import State def final_msg(state: State) -> MoneroTransactionFinalAck: - from trezor.messages import MoneroTransactionFinalAck - from apps.monero.xmr import chacha_poly from trezor.crypto import random + from trezor.messages import MoneroTransactionFinalAck + from apps.monero import misc - from apps.monero.xmr import crypto, crypto_helpers + from apps.monero.xmr import chacha_poly, crypto, crypto_helpers if state.last_step != state.STEP_SIGN: raise ValueError("Invalid state transition") diff --git a/core/src/apps/monero/xmr/addresses.py b/core/src/apps/monero/xmr/addresses.py index 87fc7f58cd..d7679b831b 100644 --- a/core/src/apps/monero/xmr/addresses.py +++ b/core/src/apps/monero/xmr/addresses.py @@ -1,8 +1,10 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.messages import MoneroAccountPublicAddress - from trezor.messages import MoneroTransactionDestinationEntry + from trezor.messages import ( + MoneroAccountPublicAddress, + MoneroTransactionDestinationEntry, + ) def encode_addr( diff --git a/core/src/apps/monero/xmr/bulletproof.py b/core/src/apps/monero/xmr/bulletproof.py index 7f356477e7..90a79b7b36 100644 --- a/core/src/apps/monero/xmr/bulletproof.py +++ b/core/src/apps/monero/xmr/bulletproof.py @@ -8,7 +8,7 @@ from apps.monero.xmr import crypto, crypto_helpers from apps.monero.xmr.serialize.int_serialize import dump_uvarint_b_into if TYPE_CHECKING: - from typing import Iterator, TypeVar, Generic + from typing import Generic, Iterator, TypeVar from .serialize_messages.tx_rsig_bulletproof import BulletproofPlus diff --git a/core/src/apps/monero/xmr/clsag.py b/core/src/apps/monero/xmr/clsag.py index 020bdf6234..c1b3e11707 100644 --- a/core/src/apps/monero/xmr/clsag.py +++ b/core/src/apps/monero/xmr/clsag.py @@ -48,10 +48,12 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Any, TypeGuard, TypeVar - from .serialize_messages.tx_ct_key import CtKey from trezor.messages import MoneroRctKeyPublic + from apps.monero.xmr import crypto + from .serialize_messages.tx_ct_key import CtKey + T = TypeVar("T") def _list_of_type(lst: list[Any], typ: type[T]) -> TypeGuard[list[T]]: diff --git a/core/src/apps/monero/xmr/credentials.py b/core/src/apps/monero/xmr/credentials.py index f85342d485..8064718a88 100644 --- a/core/src/apps/monero/xmr/credentials.py +++ b/core/src/apps/monero/xmr/credentials.py @@ -2,6 +2,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from trezor.enums import MoneroNetworkType + from apps.monero.xmr import crypto @@ -33,10 +34,11 @@ class AccountCreds: priv_spend_key: crypto.Scalar, network_type: MoneroNetworkType | None = None, ) -> "AccountCreds": + from trezor.enums import MoneroNetworkType + from apps.monero.xmr import crypto, crypto_helpers from apps.monero.xmr.addresses import encode_addr from apps.monero.xmr.networks import net_version - from trezor.enums import MoneroNetworkType if network_type is None: network_type = MoneroNetworkType.MAINNET diff --git a/core/src/apps/monero/xmr/keccak_hasher.py b/core/src/apps/monero/xmr/keccak_hasher.py index 4583f4c24f..93b156f725 100644 --- a/core/src/apps/monero/xmr/keccak_hasher.py +++ b/core/src/apps/monero/xmr/keccak_hasher.py @@ -25,6 +25,7 @@ class KeccakXmrArchive: def get_keccak_writer(ctx: HashContext | None = None) -> HashWriter: from trezor.utils import HashWriter + from apps.monero.xmr import crypto_helpers if ctx is None: diff --git a/core/src/apps/monero/xmr/key_image.py b/core/src/apps/monero/xmr/key_image.py index 22ac351e14..1bbddbd30d 100644 --- a/core/src/apps/monero/xmr/key_image.py +++ b/core/src/apps/monero/xmr/key_image.py @@ -3,9 +3,10 @@ from typing import TYPE_CHECKING from apps.monero.xmr import crypto_helpers, monero if TYPE_CHECKING: - from apps.monero.xmr.credentials import AccountCreds from trezor.messages import MoneroTransferDetails + from apps.monero.xmr import crypto + from apps.monero.xmr.credentials import AccountCreds Subaddresses = dict[bytes, tuple[int, int]] Sig = list[list[crypto.Scalar]] @@ -78,6 +79,7 @@ def generate_ring_signature( void crypto_ops::generate_ring_signature() """ from trezor.utils import memcpy + from apps.monero.xmr import crypto Scalar = crypto.Scalar # local_cache_attribute diff --git a/core/src/apps/monero/xmr/mlsag_hasher.py b/core/src/apps/monero/xmr/mlsag_hasher.py index 15a95ce3d6..1229d7c5c3 100644 --- a/core/src/apps/monero/xmr/mlsag_hasher.py +++ b/core/src/apps/monero/xmr/mlsag_hasher.py @@ -2,6 +2,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from trezor.utils import HashContext + from .serialize_messages.tx_rsig_bulletproof import BulletproofPlus diff --git a/core/src/apps/monero/xmr/range_signatures.py b/core/src/apps/monero/xmr/range_signatures.py index 79d87b7b4f..7c694d8dab 100644 --- a/core/src/apps/monero/xmr/range_signatures.py +++ b/core/src/apps/monero/xmr/range_signatures.py @@ -14,9 +14,7 @@ from typing import TYPE_CHECKING from apps.monero.xmr import crypto if TYPE_CHECKING: - from apps.monero.xmr.serialize_messages.tx_rsig_bulletproof import ( - BulletproofPlus, - ) + from apps.monero.xmr.serialize_messages.tx_rsig_bulletproof import BulletproofPlus def prove_range_bp_batch( diff --git a/core/src/apps/monero/xmr/serialize/message_types.py b/core/src/apps/monero/xmr/serialize/message_types.py index 7605b00c0d..69f9ac0901 100644 --- a/core/src/apps/monero/xmr/serialize/message_types.py +++ b/core/src/apps/monero/xmr/serialize/message_types.py @@ -5,9 +5,9 @@ from trezor.utils import obj_eq, obj_repr from apps.monero.xmr.serialize.int_serialize import dump_uvarint, load_uvarint if TYPE_CHECKING: - from typing import TypeVar, Generic + from typing import Generic, TypeVar - from .base_types import XmrType, XmrFspec, Reader, Writer + from .base_types import Reader, Writer, XmrFspec, XmrType T = TypeVar("T", bound=XmrType) MT = TypeVar("MT", bound="MessageType") diff --git a/core/src/apps/nem/get_address.py b/core/src/apps/nem/get_address.py index 28aef04083..4686cbd6cd 100644 --- a/core/src/apps/nem/get_address.py +++ b/core/src/apps/nem/get_address.py @@ -5,15 +5,18 @@ from apps.common.keychain import with_slip44_keychain from . import CURVE, PATTERNS, SLIP44_ID if TYPE_CHECKING: + from trezor.messages import NEMAddress, NEMGetAddress + from apps.common.keychain import Keychain - from trezor.messages import NEMGetAddress, NEMAddress @with_slip44_keychain(*PATTERNS, slip44_id=SLIP44_ID, curve=CURVE) async def get_address(msg: NEMGetAddress, keychain: Keychain) -> NEMAddress: from trezor.messages import NEMAddress from trezor.ui.layouts import show_address + from apps.common.paths import address_n_to_str, validate_path + from .helpers import check_path, get_network_str from .validators import validate_network diff --git a/core/src/apps/nem/helpers.py b/core/src/apps/nem/helpers.py index 7471ac1066..e752db1ef6 100644 --- a/core/src/apps/nem/helpers.py +++ b/core/src/apps/nem/helpers.py @@ -46,6 +46,7 @@ def get_network_str(network: int) -> str: def check_path(path: paths.Bip32Path, network: int) -> bool: """Validates that the appropriate coin_type is set for the given network.""" from apps.common import paths + from . import SLIP44_ID if len(path) < 2: diff --git a/core/src/apps/nem/mosaic/layout.py b/core/src/apps/nem/mosaic/layout.py index 50bd4ca474..20b7f240b1 100644 --- a/core/src/apps/nem/mosaic/layout.py +++ b/core/src/apps/nem/mosaic/layout.py @@ -31,6 +31,7 @@ async def ask_supply_change( common: NEMTransactionCommon, change: NEMMosaicSupplyChange ) -> None: from trezor.enums import NEMSupplyChangeType + from ..layout import require_confirm_text supply_message = [ diff --git a/core/src/apps/nem/multisig/layout.py b/core/src/apps/nem/multisig/layout.py index 6517fd3134..ef49387bb9 100644 --- a/core/src/apps/nem/multisig/layout.py +++ b/core/src/apps/nem/multisig/layout.py @@ -29,6 +29,7 @@ async def ask_aggregate_modification( multisig: bool, ) -> None: from trezor.enums import NEMModificationType + from ..layout import require_confirm_final, require_confirm_text if not multisig: diff --git a/core/src/apps/nem/multisig/serialize.py b/core/src/apps/nem/multisig/serialize.py index 1ce0c7c770..3c4e71d244 100644 --- a/core/src/apps/nem/multisig/serialize.py +++ b/core/src/apps/nem/multisig/serialize.py @@ -24,6 +24,7 @@ def serialize_multisig_signature( address_public_key: bytes, ) -> bytes: from trezor.crypto import hashlib, nem + from ..helpers import NEM_TRANSACTION_TYPE_MULTISIG_SIGNATURE w = serialize_tx_common(common, public_key, NEM_TRANSACTION_TYPE_MULTISIG_SIGNATURE) diff --git a/core/src/apps/nem/sign_tx.py b/core/src/apps/nem/sign_tx.py index ad19a680ea..4cb76c13b0 100644 --- a/core/src/apps/nem/sign_tx.py +++ b/core/src/apps/nem/sign_tx.py @@ -5,15 +5,16 @@ from apps.common.keychain import with_slip44_keychain from . import CURVE, PATTERNS, SLIP44_ID if TYPE_CHECKING: - from trezor.messages import NEMSignTx, NEMSignedTx + from trezor.messages import NEMSignedTx, NEMSignTx + from apps.common.keychain import Keychain @with_slip44_keychain(*PATTERNS, slip44_id=SLIP44_ID, curve=CURVE) async def sign_tx(msg: NEMSignTx, keychain: Keychain) -> NEMSignedTx: - from trezor.wire import DataError from trezor.crypto.curve import ed25519 from trezor.messages import NEMSignedTx + from trezor.wire import DataError from apps.common import seed from apps.common.paths import validate_path diff --git a/core/src/apps/nem/transfer/__init__.py b/core/src/apps/nem/transfer/__init__.py index ddbee1e1a1..2e576fce58 100644 --- a/core/src/apps/nem/transfer/__init__.py +++ b/core/src/apps/nem/transfer/__init__.py @@ -3,8 +3,8 @@ from typing import TYPE_CHECKING from . import layout, serialize if TYPE_CHECKING: - from trezor.messages import NEMImportanceTransfer, NEMTransactionCommon, NEMTransfer from trezor.crypto import bip32 + from trezor.messages import NEMImportanceTransfer, NEMTransactionCommon, NEMTransfer async def transfer( diff --git a/core/src/apps/nem/transfer/layout.py b/core/src/apps/nem/transfer/layout.py index e52d18da4d..5828e8cb38 100644 --- a/core/src/apps/nem/transfer/layout.py +++ b/core/src/apps/nem/transfer/layout.py @@ -22,6 +22,7 @@ async def ask_transfer( encrypted: bool, ) -> None: from trezor.ui.layouts import confirm_output, confirm_text + from ..helpers import NEM_MAX_DIVISIBILITY if transfer.payload: @@ -51,8 +52,9 @@ async def _ask_transfer_mosaic( ) -> None: from trezor.enums import NEMMosaicLevy from trezor.ui.layouts import confirm_action, confirm_properties - from ..mosaic.helpers import get_mosaic_definition + from ..helpers import NEM_LEVY_PERCENTILE_DIVISOR_ABSOLUTE + from ..mosaic.helpers import get_mosaic_definition if is_nem_xem_mosaic(mosaic): return @@ -128,6 +130,7 @@ async def ask_importance_transfer( common: NEMTransactionCommon, imp: NEMImportanceTransfer ) -> None: from trezor.enums import NEMImportanceTransferMode + from ..layout import require_confirm_text if imp.mode == NEMImportanceTransferMode.ImportanceTransfer_Activate: diff --git a/core/src/apps/nem/transfer/serialize.py b/core/src/apps/nem/transfer/serialize.py index 8943463313..b02d238f04 100644 --- a/core/src/apps/nem/transfer/serialize.py +++ b/core/src/apps/nem/transfer/serialize.py @@ -9,13 +9,13 @@ from ..writers import ( if TYPE_CHECKING: from trezor.crypto import bip32 - from trezor.utils import Writer from trezor.messages import ( NEMImportanceTransfer, NEMMosaic, NEMTransactionCommon, NEMTransfer, ) + from trezor.utils import Writer def serialize_transfer( @@ -86,10 +86,8 @@ def get_transfer_payload( transfer: NEMTransfer, node: bip32.HDNode ) -> tuple[bytes, bool]: from trezor.crypto import random - from ..helpers import ( - AES_BLOCK_SIZE, - NEM_SALT_SIZE, - ) + + from ..helpers import AES_BLOCK_SIZE, NEM_SALT_SIZE if transfer.public_key is not None: if not transfer.payload: diff --git a/core/src/apps/nem/validators.py b/core/src/apps/nem/validators.py index df486d4d2b..361af1f308 100644 --- a/core/src/apps/nem/validators.py +++ b/core/src/apps/nem/validators.py @@ -10,10 +10,11 @@ def validate(msg: NEMSignTx) -> None: from trezor.crypto import nem from trezor.enums import NEMModificationType from trezor.wire import ProcessError # local_cache_global + from .helpers import ( + NEM_MAX_DIVISIBILITY, NEM_MAX_ENCRYPTED_PAYLOAD_SIZE, NEM_MAX_PLAIN_PAYLOAD_SIZE, - NEM_MAX_DIVISIBILITY, NEM_MAX_SUPPLY, ) @@ -158,11 +159,7 @@ def validate(msg: NEMSignTx) -> None: def validate_network(network: int) -> None: - from .helpers import ( - NEM_NETWORK_MAINNET, - NEM_NETWORK_MIJIN, - NEM_NETWORK_TESTNET, - ) + from .helpers import NEM_NETWORK_MAINNET, NEM_NETWORK_MIJIN, NEM_NETWORK_TESTNET if network not in (NEM_NETWORK_MAINNET, NEM_NETWORK_TESTNET, NEM_NETWORK_MIJIN): raise ProcessError("Invalid NEM network") diff --git a/core/src/apps/ripple/get_address.py b/core/src/apps/ripple/get_address.py index 402a07ab2a..c0c96d1cd7 100644 --- a/core/src/apps/ripple/get_address.py +++ b/core/src/apps/ripple/get_address.py @@ -3,7 +3,8 @@ from typing import TYPE_CHECKING from apps.common.keychain import auto_keychain if TYPE_CHECKING: - from trezor.messages import RippleGetAddress, RippleAddress + from trezor.messages import RippleAddress, RippleGetAddress + from apps.common.keychain import Keychain @@ -12,7 +13,9 @@ async def get_address(msg: RippleGetAddress, keychain: Keychain) -> RippleAddres # NOTE: local imports here saves 20 bytes from trezor.messages import RippleAddress from trezor.ui.layouts import show_address + from apps.common import paths + from .helpers import address_from_public_key await paths.validate_path(keychain, msg.address_n) diff --git a/core/src/apps/ripple/sign_tx.py b/core/src/apps/ripple/sign_tx.py index f6ae3d7f57..f9de3eb8ae 100644 --- a/core/src/apps/ripple/sign_tx.py +++ b/core/src/apps/ripple/sign_tx.py @@ -3,7 +3,8 @@ from typing import TYPE_CHECKING from apps.common.keychain import auto_keychain if TYPE_CHECKING: - from trezor.messages import RippleSignTx, RippleSignedTx + from trezor.messages import RippleSignedTx, RippleSignTx + from apps.common.keychain import Keychain @@ -15,7 +16,9 @@ async def sign_tx(msg: RippleSignTx, keychain: Keychain) -> RippleSignedTx: from trezor.crypto.hashlib import sha512 from trezor.messages import RippleSignedTx from trezor.wire import ProcessError + from apps.common import paths + from . import helpers, layout from .serialize import serialize diff --git a/core/src/apps/stellar/consts.py b/core/src/apps/stellar/consts.py index bff62ac2b5..a492b049b2 100644 --- a/core/src/apps/stellar/consts.py +++ b/core/src/apps/stellar/consts.py @@ -5,7 +5,6 @@ from trezor.enums import MessageType if TYPE_CHECKING: from trezor import protobuf - from trezor.messages import ( StellarAccountMergeOp, StellarAllowTrustOp, @@ -13,8 +12,8 @@ if TYPE_CHECKING: StellarChangeTrustOp, StellarCreateAccountOp, StellarCreatePassiveSellOfferOp, - StellarManageDataOp, StellarManageBuyOfferOp, + StellarManageDataOp, StellarManageSellOfferOp, StellarPathPaymentStrictReceiveOp, StellarPathPaymentStrictSendOp, diff --git a/core/src/apps/stellar/get_address.py b/core/src/apps/stellar/get_address.py index d1fc38e98e..cc9fea05dd 100644 --- a/core/src/apps/stellar/get_address.py +++ b/core/src/apps/stellar/get_address.py @@ -3,15 +3,18 @@ from typing import TYPE_CHECKING from apps.common.keychain import auto_keychain if TYPE_CHECKING: - from trezor.messages import StellarGetAddress, StellarAddress + from trezor.messages import StellarAddress, StellarGetAddress + from apps.common.keychain import Keychain @auto_keychain(__name__) async def get_address(msg: StellarGetAddress, keychain: Keychain) -> StellarAddress: - from apps.common import paths, seed from trezor.messages import StellarAddress from trezor.ui.layouts import show_address + + from apps.common import paths, seed + from . import helpers await paths.validate_path(keychain, msg.address_n) diff --git a/core/src/apps/stellar/layout.py b/core/src/apps/stellar/layout.py index 6fe9dacc27..5ede1ff7e6 100644 --- a/core/src/apps/stellar/layout.py +++ b/core/src/apps/stellar/layout.py @@ -8,7 +8,6 @@ from . import consts if TYPE_CHECKING: from trezor.enums import StellarMemoType - from trezor.messages import StellarAsset diff --git a/core/src/apps/stellar/operations/__init__.py b/core/src/apps/stellar/operations/__init__.py index d3f6c371af..23472a3a77 100644 --- a/core/src/apps/stellar/operations/__init__.py +++ b/core/src/apps/stellar/operations/__init__.py @@ -1,8 +1,8 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.utils import Writer from consts import StellarMessageType + from trezor.utils import Writer async def process_operation(w: Writer, op: StellarMessageType) -> None: diff --git a/core/src/apps/stellar/operations/layout.py b/core/src/apps/stellar/operations/layout.py index f467581f97..78a830d37d 100644 --- a/core/src/apps/stellar/operations/layout.py +++ b/core/src/apps/stellar/operations/layout.py @@ -21,13 +21,13 @@ if TYPE_CHECKING: StellarChangeTrustOp, StellarCreateAccountOp, StellarCreatePassiveSellOfferOp, + StellarManageBuyOfferOp, StellarManageDataOp, StellarManageSellOfferOp, StellarPathPaymentStrictReceiveOp, StellarPathPaymentStrictSendOp, StellarPaymentOp, StellarSetOptionsOp, - StellarManageBuyOfferOp, ) @@ -122,6 +122,7 @@ async def _confirm_offer( | StellarManageBuyOfferOp, ) -> None: from trezor.messages import StellarManageBuyOfferOp + from ..layout import format_asset buying_asset = op.buying_asset # local_cache_attribute @@ -224,6 +225,7 @@ async def confirm_payment_op(op: StellarPaymentOp) -> None: async def confirm_set_options_op(op: StellarSetOptionsOp) -> None: from trezor.enums import StellarSignerType from trezor.ui.layouts import confirm_blob, confirm_text + from .. import helpers if op.inflation_destination_account: diff --git a/core/src/apps/stellar/operations/serialize.py b/core/src/apps/stellar/operations/serialize.py index 04b7c1de81..65b4c318fb 100644 --- a/core/src/apps/stellar/operations/serialize.py +++ b/core/src/apps/stellar/operations/serialize.py @@ -13,8 +13,6 @@ from ..writers import ( ) if TYPE_CHECKING: - from trezor.utils import Writer - from trezor.messages import ( StellarAccountMergeOp, StellarAllowTrustOp, @@ -31,6 +29,7 @@ if TYPE_CHECKING: StellarPaymentOp, StellarSetOptionsOp, ) + from trezor.utils import Writer def write_account_merge_op(w: Writer, msg: StellarAccountMergeOp) -> None: diff --git a/core/src/apps/stellar/sign_tx.py b/core/src/apps/stellar/sign_tx.py index 6707a22738..f151eaeaf1 100644 --- a/core/src/apps/stellar/sign_tx.py +++ b/core/src/apps/stellar/sign_tx.py @@ -3,7 +3,7 @@ from typing import TYPE_CHECKING from apps.common.keychain import auto_keychain if TYPE_CHECKING: - from trezor.messages import StellarSignTx, StellarSignedTx + from trezor.messages import StellarSignedTx, StellarSignTx from apps.common.keychain import Keychain @@ -11,17 +11,18 @@ if TYPE_CHECKING: @auto_keychain(__name__) async def sign_tx(msg: StellarSignTx, keychain: Keychain) -> StellarSignedTx: from ubinascii import hexlify - from trezor.messages import StellarSignedTx + from trezor.crypto.curve import ed25519 - from apps.common import paths, seed - from trezor.enums import StellarMemoType from trezor.crypto.hashlib import sha256 + from trezor.enums import StellarMemoType + from trezor.messages import StellarSignedTx, StellarTxOpRequest from trezor.wire import DataError, ProcessError from trezor.wire.context import call_any - from trezor.messages import StellarTxOpRequest + + from apps.common import paths, seed + + from . import consts, helpers, layout, writers from .operations import process_operation - from . import helpers - from . import consts, layout, writers await paths.validate_path(keychain, msg.address_n) diff --git a/core/src/apps/tezos/get_address.py b/core/src/apps/tezos/get_address.py index d0acc3b1ea..1ab6407873 100644 --- a/core/src/apps/tezos/get_address.py +++ b/core/src/apps/tezos/get_address.py @@ -5,7 +5,8 @@ from apps.common.keychain import with_slip44_keychain from . import CURVE, PATTERNS, SLIP44_ID if TYPE_CHECKING: - from trezor.messages import TezosGetAddress, TezosAddress + from trezor.messages import TezosAddress, TezosGetAddress + from apps.common.keychain import Keychain @@ -14,7 +15,9 @@ async def get_address(msg: TezosGetAddress, keychain: Keychain) -> TezosAddress: from trezor.crypto import hashlib from trezor.messages import TezosAddress from trezor.ui.layouts import show_address + from apps.common import paths, seed + from . import helpers await paths.validate_path(keychain, msg.address_n) diff --git a/core/src/apps/tezos/get_public_key.py b/core/src/apps/tezos/get_public_key.py index 35af44dea2..f70a8e5d19 100644 --- a/core/src/apps/tezos/get_public_key.py +++ b/core/src/apps/tezos/get_public_key.py @@ -6,6 +6,7 @@ from . import CURVE, PATTERNS, SLIP44_ID if TYPE_CHECKING: from trezor.messages import TezosGetPublicKey, TezosPublicKey + from apps.common.keychain import Keychain @@ -13,7 +14,9 @@ if TYPE_CHECKING: async def get_public_key(msg: TezosGetPublicKey, keychain: Keychain) -> TezosPublicKey: from trezor.messages import TezosPublicKey from trezor.ui.layouts import show_pubkey + from apps.common import paths, seed + from . import helpers await paths.validate_path(keychain, msg.address_n) diff --git a/core/src/apps/tezos/layout.py b/core/src/apps/tezos/layout.py index cfc09e04e8..1589581c9f 100644 --- a/core/src/apps/tezos/layout.py +++ b/core/src/apps/tezos/layout.py @@ -82,6 +82,7 @@ async def require_confirm_register_delegate(address: str, fee: int) -> None: def format_tezos_amount(value: int) -> str: from trezor.strings import format_amount + from .helpers import TEZOS_AMOUNT_DECIMALS formatted_value = format_amount(value, TEZOS_AMOUNT_DECIMALS) diff --git a/core/src/apps/tezos/sign_tx.py b/core/src/apps/tezos/sign_tx.py index 15c06a1505..c0d172c62b 100644 --- a/core/src/apps/tezos/sign_tx.py +++ b/core/src/apps/tezos/sign_tx.py @@ -16,26 +16,29 @@ from .helpers import ( # symbols used more than once ) if TYPE_CHECKING: - from apps.common.keychain import Keychain from trezor.messages import ( - TezosSignTx, TezosContractID, - TezosRevealOp, TezosDelegationOp, - TezosTransactionOp, TezosOriginationOp, + TezosRevealOp, TezosSignedTx, + TezosSignTx, + TezosTransactionOp, ) from trezor.utils import Writer + from apps.common.keychain import Keychain + @with_slip44_keychain(*PATTERNS, slip44_id=SLIP44_ID, curve=CURVE) async def sign_tx(msg: TezosSignTx, keychain: Keychain) -> TezosSignedTx: from trezor.crypto import hashlib from trezor.crypto.curve import ed25519 - from apps.common.paths import validate_path - from trezor.messages import TezosSignedTx from trezor.enums import TezosBallotType + from trezor.messages import TezosSignedTx + + from apps.common.paths import validate_path + from . import layout await validate_path(keychain, msg.address_n) @@ -176,6 +179,7 @@ def _get_address_from_contract(address: TezosContractID) -> str: def _get_operation_bytes(w: Writer, msg: TezosSignTx) -> None: from apps.common.writers import write_bytes_unchecked + from .helpers import PROPOSAL_HASH_SIZE reveal = msg.reveal # local_cache_attribute diff --git a/core/src/apps/webauthn/__init__.py b/core/src/apps/webauthn/__init__.py index b1c3637d05..6f45c1b522 100644 --- a/core/src/apps/webauthn/__init__.py +++ b/core/src/apps/webauthn/__init__.py @@ -1,6 +1,7 @@ def boot() -> None: - from trezor import loop import usb + from trezor import loop + from .fido2 import handle_reports loop.schedule(handle_reports(usb.iface_webauthn)) diff --git a/core/src/apps/webauthn/add_resident_credential.py b/core/src/apps/webauthn/add_resident_credential.py index 080c30a324..10d15340cf 100644 --- a/core/src/apps/webauthn/add_resident_credential.py +++ b/core/src/apps/webauthn/add_resident_credential.py @@ -1,15 +1,16 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.messages import WebAuthnAddResidentCredential, Success + from trezor.messages import Success, WebAuthnAddResidentCredential async def add_resident_credential(msg: WebAuthnAddResidentCredential) -> Success: import storage.device as storage_device from trezor import wire + from trezor.messages import Success from trezor.ui.layouts import show_error_and_raise from trezor.ui.layouts.fido import confirm_fido - from trezor.messages import Success + from .credential import Fido2Credential from .resident_credentials import store_resident_credential diff --git a/core/src/apps/webauthn/credential.py b/core/src/apps/webauthn/credential.py index 89b022ea6f..669fd587fb 100644 --- a/core/src/apps/webauthn/credential.py +++ b/core/src/apps/webauthn/credential.py @@ -15,6 +15,7 @@ from .common import COSE_ALG_EDDSA, COSE_ALG_ES256, COSE_CURVE_ED25519, COSE_CUR if TYPE_CHECKING: from typing import Iterable + from trezor.crypto import bip32 diff --git a/core/src/apps/webauthn/fido2.py b/core/src/apps/webauthn/fido2.py index 724636ea80..ad9cc555bf 100644 --- a/core/src/apps/webauthn/fido2.py +++ b/core/src/apps/webauthn/fido2.py @@ -18,6 +18,7 @@ from .credential import Credential, Fido2Credential if TYPE_CHECKING: from typing import Any, Awaitable, Callable, Coroutine, Iterable, Iterator + from .credential import U2fCredential HID = io.HID @@ -566,9 +567,10 @@ class KeepaliveCallback: async def verify_user(keepalive_callback: KeepaliveCallback) -> bool: - from trezor.wire import PinCancelled, PinInvalid - from apps.common.request_pin import verify_user_pin import trezor.pin + from trezor.wire import PinCancelled, PinInvalid + + from apps.common.request_pin import verify_user_pin try: trezor.pin.keepalive_callback = keepalive_callback @@ -584,6 +586,7 @@ async def verify_user(keepalive_callback: KeepaliveCallback) -> bool: def _confirm_fido_choose(title: str, credentials: list[Credential]) -> Awaitable[int]: from trezor.ui.layouts.fido import confirm_fido + from . import knownapps assert len(credentials) > 0 @@ -706,6 +709,7 @@ class U2fUnlock(State): async def confirm_dialog(self) -> bool: from trezor.wire import PinCancelled, PinInvalid + from apps.common.request_pin import verify_user_pin try: @@ -1793,8 +1797,7 @@ def _cbor_get_assertion_hmac_secret( cred: Credential, hmac_secret: dict ) -> bytes | None: from storage.fido2 import KEY_AGREEMENT_PRIVKEY - from trezor.crypto import aes - from trezor.crypto import hmac + from trezor.crypto import aes, hmac key_agreement = hmac_secret[1] # The public key of platform key agreement key. # NOTE: We should check the key_agreement[COSE_KEY_ALG] here, but to avoid compatibility issues we don't, diff --git a/core/src/apps/webauthn/list_resident_credentials.py b/core/src/apps/webauthn/list_resident_credentials.py index f7485bb057..d39fd14a84 100644 --- a/core/src/apps/webauthn/list_resident_credentials.py +++ b/core/src/apps/webauthn/list_resident_credentials.py @@ -1,7 +1,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.messages import WebAuthnListResidentCredentials, WebAuthnCredentials + from trezor.messages import WebAuthnCredentials, WebAuthnListResidentCredentials async def list_resident_credentials( diff --git a/core/src/apps/webauthn/remove_resident_credential.py b/core/src/apps/webauthn/remove_resident_credential.py index 2d5c0e080c..6c0655cbe4 100644 --- a/core/src/apps/webauthn/remove_resident_credential.py +++ b/core/src/apps/webauthn/remove_resident_credential.py @@ -1,7 +1,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.messages import WebAuthnRemoveResidentCredential, Success + from trezor.messages import Success, WebAuthnRemoveResidentCredential async def remove_resident_credential(msg: WebAuthnRemoveResidentCredential) -> Success: @@ -10,6 +10,7 @@ async def remove_resident_credential(msg: WebAuthnRemoveResidentCredential) -> S from trezor import wire from trezor.messages import Success from trezor.ui.layouts.fido import confirm_fido + from .resident_credentials import get_resident_credential if not storage.device.is_initialized(): diff --git a/core/src/apps/webauthn/resident_credentials.py b/core/src/apps/webauthn/resident_credentials.py index 386bf83d4e..791b19a9df 100644 --- a/core/src/apps/webauthn/resident_credentials.py +++ b/core/src/apps/webauthn/resident_credentials.py @@ -6,6 +6,7 @@ from storage.resident_credentials import MAX_RESIDENT_CREDENTIALS if TYPE_CHECKING: from typing import Iterator + from .credential import Fido2Credential diff --git a/core/src/apps/workflow_handlers.py b/core/src/apps/workflow_handlers.py index e13003ac50..a4951409f4 100644 --- a/core/src/apps/workflow_handlers.py +++ b/core/src/apps/workflow_handlers.py @@ -1,9 +1,10 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.wire import Handler, Msg from trezorio import WireInterface + from trezor.wire import Handler, Msg + workflow_handlers: dict[int, Handler] = {} @@ -23,8 +24,8 @@ def _find_message_handler_module(msg_type: int) -> str: - collecting everything as strings instead of importing directly means that we don't need to load any of the modules into memory until we actually need them """ - from trezor.enums import MessageType from trezor import utils + from trezor.enums import MessageType # debug if __debug__ and msg_type == MessageType.LoadDevice: diff --git a/core/src/apps/zcash/hasher.py b/core/src/apps/zcash/hasher.py index 22ad0a484f..350681f0e7 100644 --- a/core/src/apps/zcash/hasher.py +++ b/core/src/apps/zcash/hasher.py @@ -22,10 +22,12 @@ from apps.bitcoin.writers import ( if TYPE_CHECKING: from typing import Sequence - from trezor.messages import TxInput, TxOutput, SignTx, PrevTx - from trezor.utils import Writer, HashWriter - from apps.common.coininfo import CoinInfo + + from trezor.messages import PrevTx, SignTx, TxInput, TxOutput + from trezor.utils import HashWriter, Writer + from apps.bitcoin.common import SigHashType + from apps.common.coininfo import CoinInfo def write_hash(w: Writer, hash: bytes) -> None: diff --git a/core/src/apps/zcash/signer.py b/core/src/apps/zcash/signer.py index 252177d2b6..f97110e5c6 100644 --- a/core/src/apps/zcash/signer.py +++ b/core/src/apps/zcash/signer.py @@ -7,13 +7,16 @@ from apps.bitcoin.sign_tx.bitcoinlike import Bitcoinlike if TYPE_CHECKING: from typing import Sequence - from apps.common.coininfo import CoinInfo + + from trezor.messages import PrevTx, SignTx, TxInput, TxOutput + from trezor.utils import HashWriter + + from apps.bitcoin.keychain import Keychain + from apps.bitcoin.sign_tx.approvers import Approver from apps.bitcoin.sign_tx.tx_info import OriginalTxInfo, TxInfo from apps.bitcoin.writers import Writer - from apps.bitcoin.sign_tx.approvers import Approver - from trezor.utils import HashWriter - from trezor.messages import PrevTx, TxInput, TxOutput, SignTx - from apps.bitcoin.keychain import Keychain + from apps.common.coininfo import CoinInfo + from .hasher import ZcashHasher _OVERWINTERED = const(0x8000_0000) @@ -119,8 +122,10 @@ class Zcash(Bitcoinlike): write_compact_size(w, 0) # nActionsOrchard def output_derive_script(self, txo: TxOutput) -> bytes: - from apps.bitcoin import scripts from trezor.enums import OutputScriptType + + from apps.bitcoin import scripts + from .unified_addresses import Typecode, decode # unified addresses diff --git a/core/src/apps/zcash/unified_addresses.py b/core/src/apps/zcash/unified_addresses.py index be4abf8bf2..28c4a489e1 100644 --- a/core/src/apps/zcash/unified_addresses.py +++ b/core/src/apps/zcash/unified_addresses.py @@ -10,6 +10,7 @@ from trezor.crypto.bech32 import Encoding, convertbits if TYPE_CHECKING: from enum import IntEnum + from apps.common.coininfo import CoinInfo else: IntEnum = object @@ -48,9 +49,11 @@ def padding(hrp: str) -> bytes: def encode(receivers: dict[Typecode, bytes], coin: CoinInfo) -> str: from trezor.crypto.bech32 import bech32_encode from trezor.utils import empty_bytearray - from .f4jumble import f4jumble + from apps.common.writers import write_bytes_fixed, write_compact_size + from .f4jumble import f4jumble + # multiple transparent receivers forbidden assert not (Typecode.P2PKH in receivers and Typecode.P2SH in receivers) # at least one shielded address must be present @@ -84,7 +87,9 @@ def decode(addr_str: str, coin: CoinInfo) -> dict[int, bytes]: from trezor.crypto.bech32 import bech32_decode from trezor.utils import BufferReader from trezor.wire import DataError + from apps.common.readers import read_compact_size + from .f4jumble import f4unjumble try: diff --git a/core/src/session.py b/core/src/session.py index 2e5ab5dd91..4f161c36ce 100644 --- a/core/src/session.py +++ b/core/src/session.py @@ -1,3 +1,4 @@ +# isort: skip_file from trezor import log, loop, utils, wire, workflow import apps.base diff --git a/core/src/storage/__init__.py b/core/src/storage/__init__.py index 7e3bba5943..7998ca5c27 100644 --- a/core/src/storage/__init__.py +++ b/core/src/storage/__init__.py @@ -2,8 +2,8 @@ from storage import common, device def wipe() -> None: - from trezor import config from storage import cache + from trezor import config config.wipe() cache.clear_all() diff --git a/core/src/storage/cache.py b/core/src/storage/cache.py index 451e541f22..8e46b2defb 100644 --- a/core/src/storage/cache.py +++ b/core/src/storage/cache.py @@ -305,7 +305,7 @@ def delete(key: int) -> None: if TYPE_CHECKING: - from typing import Awaitable, Callable, TypeVar, ParamSpec + from typing import Awaitable, Callable, ParamSpec, TypeVar P = ParamSpec("P") ByteFunc = Callable[P, bytes] diff --git a/core/src/storage/device.py b/core/src/storage/device.py index 4ba36c4a82..cf6ba0e929 100644 --- a/core/src/storage/device.py +++ b/core/src/storage/device.py @@ -76,8 +76,8 @@ def is_initialized() -> bool: def get_device_id() -> str: - from ubinascii import hexlify from trezorcrypto import random # avoid pulling in trezor.crypto + from ubinascii import hexlify dev_id = common.get(_NAMESPACE, DEVICE_ID, public=True) if not dev_id: diff --git a/core/src/storage/sd_salt.py b/core/src/storage/sd_salt.py index 7fc3c43aef..2bc8b9b357 100644 --- a/core/src/storage/sd_salt.py +++ b/core/src/storage/sd_salt.py @@ -6,7 +6,7 @@ from trezor import io, utils from trezor.sdcard import with_filesystem if TYPE_CHECKING: - from typing import TypeVar, Callable + from typing import Callable, TypeVar T = TypeVar("T", bound=Callable) diff --git a/core/src/trezor/crypto/der.py b/core/src/trezor/crypto/der.py index 3d69f960fd..64719a200b 100644 --- a/core/src/trezor/crypto/der.py +++ b/core/src/trezor/crypto/der.py @@ -2,8 +2,7 @@ from micropython import const from typing import TYPE_CHECKING if TYPE_CHECKING: - from trezor.utils import Writer - from trezor.utils import BufferReader + from trezor.utils import BufferReader, Writer # Maximum length of a DER-encoded secp256k1 or secp256p1 signature. _MAX_DER_SIGNATURE_LENGTH = const(72) diff --git a/core/src/trezor/loop.py b/core/src/trezor/loop.py index 1595a5c44a..d631e54ae6 100644 --- a/core/src/trezor/loop.py +++ b/core/src/trezor/loop.py @@ -14,13 +14,7 @@ from typing import TYPE_CHECKING from trezor import io, log if TYPE_CHECKING: - from typing import ( - Any, - Awaitable, - Callable, - Coroutine, - Generator, - ) + from typing import Any, Awaitable, Callable, Coroutine, Generator Task = Coroutine | Generator AwaitableTask = Task | Awaitable diff --git a/core/src/trezor/pin.py b/core/src/trezor/pin.py index f3023ff1a7..6eaa73f393 100644 --- a/core/src/trezor/pin.py +++ b/core/src/trezor/pin.py @@ -2,6 +2,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Any + from trezor.ui.layouts.common import ProgressLayout _previous_seconds: int | None = None diff --git a/core/src/trezor/sdcard.py b/core/src/trezor/sdcard.py index e6582bbee7..3a72402330 100644 --- a/core/src/trezor/sdcard.py +++ b/core/src/trezor/sdcard.py @@ -19,6 +19,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Any, Callable, TypeVar + from typing_extensions import ParamSpec P = ParamSpec("P") diff --git a/core/src/trezor/ui/layouts/tr/__init__.py b/core/src/trezor/ui/layouts/tr/__init__.py index 3ccb5391c8..59dc992f5b 100644 --- a/core/src/trezor/ui/layouts/tr/__init__.py +++ b/core/src/trezor/ui/layouts/tr/__init__.py @@ -1,18 +1,17 @@ from typing import TYPE_CHECKING +import trezorui2 from trezor import io, loop, ui from trezor.enums import ButtonRequestType from trezor.wire import ActionCancelled from trezor.wire.context import wait as ctx_wait -import trezorui2 - from ..common import button_request, interact if TYPE_CHECKING: - from typing import Any, NoReturn, Awaitable, Iterable, Sequence, TypeVar + from typing import Any, Awaitable, Iterable, NoReturn, Sequence, TypeVar - from ..common import PropertyType, ExceptionType + from ..common import ExceptionType, PropertyType T = TypeVar("T") @@ -70,9 +69,10 @@ class RustLayout(ui.Layout): Waits for `result_signal` and carries it out. """ - from apps.debug import result_signal from storage import debug as debug_storage + from apps.debug import result_signal + while True: event_id, result = await result_signal() # Layout change will be notified in _first_paint of the next layout @@ -123,10 +123,11 @@ class RustLayout(ui.Layout): btn_to_press: DebugPhysicalButton, hold_ms: int | None, ) -> Any: - from trezor.enums import DebugPhysicalButton - from trezor import workflow - from apps.debug import notify_layout_change from storage import debug as debug_storage + from trezor import workflow + from trezor.enums import DebugPhysicalButton + + from apps.debug import notify_layout_change if btn_to_press == DebugPhysicalButton.LEFT_BTN: msg = await self._press_left(hold_ms) @@ -198,9 +199,10 @@ class RustLayout(ui.Layout): self._paint() if __debug__ and self.should_notify_layout_change: - from apps.debug import notify_layout_change from storage import debug as debug_storage + from apps.debug import notify_layout_change + # notify about change and do not notify again until next await. # (handle_rendering might be called multiple times in a single await, # because of the endless loop in __iter__) diff --git a/core/src/trezor/ui/layouts/tr/fido.py b/core/src/trezor/ui/layouts/tr/fido.py index ac3af87b42..17b66032b7 100644 --- a/core/src/trezor/ui/layouts/tr/fido.py +++ b/core/src/trezor/ui/layouts/tr/fido.py @@ -1,6 +1,5 @@ -from trezor.enums import ButtonRequestType - import trezorui2 +from trezor.enums import ButtonRequestType from ..common import interact from . import RustLayout diff --git a/core/src/trezor/ui/layouts/tr/homescreen.py b/core/src/trezor/ui/layouts/tr/homescreen.py index 455a8a21ea..d253dcccba 100644 --- a/core/src/trezor/ui/layouts/tr/homescreen.py +++ b/core/src/trezor/ui/layouts/tr/homescreen.py @@ -1,16 +1,16 @@ from typing import TYPE_CHECKING import storage.cache as storage_cache -from trezor import ui - import trezorui2 +from trezor import ui from . import RustLayout if TYPE_CHECKING: - from trezor import loop from typing import Any, Tuple + from trezor import loop + class HomescreenBase(RustLayout): RENDER_INDICATOR: object | None = None diff --git a/core/src/trezor/ui/layouts/tr/progress.py b/core/src/trezor/ui/layouts/tr/progress.py index e92801b1bf..20bc754479 100644 --- a/core/src/trezor/ui/layouts/tr/progress.py +++ b/core/src/trezor/ui/layouts/tr/progress.py @@ -1,8 +1,7 @@ from typing import TYPE_CHECKING -from trezor import ui - import trezorui2 +from trezor import ui if TYPE_CHECKING: from typing import Any diff --git a/core/src/trezor/ui/layouts/tr/recovery.py b/core/src/trezor/ui/layouts/tr/recovery.py index a0b097d596..a422807651 100644 --- a/core/src/trezor/ui/layouts/tr/recovery.py +++ b/core/src/trezor/ui/layouts/tr/recovery.py @@ -1,8 +1,7 @@ from typing import Callable, Iterable -from trezor.enums import ButtonRequestType - import trezorui2 +from trezor.enums import ButtonRequestType from ..common import interact from . import RustLayout, raise_if_not_confirmed, show_warning diff --git a/core/src/trezor/ui/layouts/tr/reset.py b/core/src/trezor/ui/layouts/tr/reset.py index 64052e7582..9835c5ce14 100644 --- a/core/src/trezor/ui/layouts/tr/reset.py +++ b/core/src/trezor/ui/layouts/tr/reset.py @@ -1,19 +1,19 @@ from typing import TYPE_CHECKING +import trezorui2 from trezor.enums import ButtonRequestType from trezor.wire import ActionCancelled -import trezorui2 - from ..common import interact from . import RustLayout, confirm_action, show_warning CONFIRMED = trezorui2.CONFIRMED # global_import_cache if TYPE_CHECKING: - from trezor.enums import BackupType from typing import Sequence + from trezor.enums import BackupType + async def show_share_words( share_words: Sequence[str], diff --git a/core/src/trezor/ui/layouts/tt_v2/__init__.py b/core/src/trezor/ui/layouts/tt_v2/__init__.py index 3604ccfe27..562442d513 100644 --- a/core/src/trezor/ui/layouts/tt_v2/__init__.py +++ b/core/src/trezor/ui/layouts/tt_v2/__init__.py @@ -1,18 +1,17 @@ from typing import TYPE_CHECKING +import trezorui2 from trezor import io, loop, ui from trezor.enums import ButtonRequestType from trezor.wire import ActionCancelled from trezor.wire.context import wait as ctx_wait -import trezorui2 - from ..common import button_request, interact if TYPE_CHECKING: from typing import Any, Awaitable, Iterable, NoReturn, Sequence, TypeVar - from ..common import PropertyType, ExceptionType + from ..common import ExceptionType, PropertyType T = TypeVar("T") @@ -69,9 +68,10 @@ class RustLayout(ui.Layout): Waits for `result_signal` and carries it out. """ - from apps.debug import result_signal from storage import debug as debug_storage + from apps.debug import result_signal + while True: event_id, result = await result_signal() debug_storage.new_layout_event_id = event_id @@ -88,9 +88,10 @@ class RustLayout(ui.Layout): self.layout.trace(callback) async def handle_swipe(self): - from apps.debug import notify_layout_change, swipe_signal from trezor.enums import DebugSwipeDirection + from apps.debug import notify_layout_change, swipe_signal + while True: event_id, direction = await swipe_signal() orig_x = orig_y = 120 @@ -120,9 +121,10 @@ class RustLayout(ui.Layout): y: int, hold_ms: int | None, ) -> Any: - from trezor import workflow - from apps.debug import notify_layout_change from storage import debug as debug_storage + from trezor import workflow + + from apps.debug import notify_layout_change self.layout.touch_event(io.TOUCH_START, x, y) self._paint() @@ -164,9 +166,10 @@ class RustLayout(ui.Layout): self._paint() if __debug__ and self.should_notify_layout_change: - from apps.debug import notify_layout_change from storage import debug as debug_storage + from apps.debug import notify_layout_change + # notify about change and do not notify again until next await. # (handle_rendering might be called multiple times in a single await, # because of the endless loop in __iter__) diff --git a/core/src/trezor/ui/layouts/tt_v2/fido.py b/core/src/trezor/ui/layouts/tt_v2/fido.py index 6c29fea3a3..5330a3cd71 100644 --- a/core/src/trezor/ui/layouts/tt_v2/fido.py +++ b/core/src/trezor/ui/layouts/tt_v2/fido.py @@ -1,8 +1,7 @@ from typing import TYPE_CHECKING -from trezor.enums import ButtonRequestType - import trezorui2 +from trezor.enums import ButtonRequestType from ..common import interact from . import RustLayout @@ -13,6 +12,7 @@ if TYPE_CHECKING: if __debug__: from trezor import io, ui + from ... import Result class _RustFidoLayoutImpl(RustLayout): diff --git a/core/src/trezor/ui/layouts/tt_v2/homescreen.py b/core/src/trezor/ui/layouts/tt_v2/homescreen.py index 829044f4b1..67c1e7f84c 100644 --- a/core/src/trezor/ui/layouts/tt_v2/homescreen.py +++ b/core/src/trezor/ui/layouts/tt_v2/homescreen.py @@ -1,16 +1,16 @@ from typing import TYPE_CHECKING import storage.cache as storage_cache -from trezor import ui - import trezorui2 +from trezor import ui from . import RustLayout if TYPE_CHECKING: - from trezor import loop from typing import Any, Tuple + from trezor import loop + class HomescreenBase(RustLayout): RENDER_INDICATOR: object | None = None diff --git a/core/src/trezor/ui/layouts/tt_v2/progress.py b/core/src/trezor/ui/layouts/tt_v2/progress.py index 22926dea39..2164571a3c 100644 --- a/core/src/trezor/ui/layouts/tt_v2/progress.py +++ b/core/src/trezor/ui/layouts/tt_v2/progress.py @@ -1,8 +1,7 @@ from typing import TYPE_CHECKING -from trezor import ui - import trezorui2 +from trezor import ui if TYPE_CHECKING: from typing import Any diff --git a/core/src/trezor/ui/layouts/tt_v2/recovery.py b/core/src/trezor/ui/layouts/tt_v2/recovery.py index ebc447c22c..60affed78e 100644 --- a/core/src/trezor/ui/layouts/tt_v2/recovery.py +++ b/core/src/trezor/ui/layouts/tt_v2/recovery.py @@ -1,10 +1,9 @@ from typing import Callable, Iterable +import trezorui2 from trezor.enums import ButtonRequestType from trezor.wire.context import wait as ctx_wait -import trezorui2 - from ..common import interact from . import RustLayout, raise_if_not_confirmed diff --git a/core/src/trezor/ui/layouts/tt_v2/reset.py b/core/src/trezor/ui/layouts/tt_v2/reset.py index f5b0209ce1..62b84526d0 100644 --- a/core/src/trezor/ui/layouts/tt_v2/reset.py +++ b/core/src/trezor/ui/layouts/tt_v2/reset.py @@ -1,16 +1,16 @@ from typing import TYPE_CHECKING +import trezorui2 from trezor.enums import ButtonRequestType from trezor.wire import ActionCancelled from trezor.wire.context import wait as ctx_wait -import trezorui2 - from ..common import interact from . import RustLayout, raise_if_not_confirmed if TYPE_CHECKING: from typing import Callable, Sequence + from trezor.enums import BackupType diff --git a/core/src/trezor/utils.py b/core/src/trezor/utils.py index d40cb16df5..74de2e7227 100644 --- a/core/src/trezor/utils.py +++ b/core/src/trezor/utils.py @@ -34,13 +34,7 @@ if __debug__: LOG_MEMORY = 0 if TYPE_CHECKING: - from typing import ( - Any, - Iterator, - Protocol, - TypeVar, - Sequence, - ) + from typing import Any, Iterator, Protocol, Sequence, TypeVar from trezor.protobuf import MessageType @@ -185,9 +179,10 @@ if False: # noqa self.data += hexlify(data).decode() + " " def digest(self) -> bytes: - from trezor import log from ubinascii import hexlify + from trezor import log + digest = self.ctx.digest() log.debug( __name__, diff --git a/core/src/trezor/wire/__init__.py b/core/src/trezor/wire/__init__.py index cabba16de0..e18755fe52 100644 --- a/core/src/trezor/wire/__init__.py +++ b/core/src/trezor/wire/__init__.py @@ -51,14 +51,8 @@ from trezor.wire.errors import * # isort:skip # noqa: F401,F403 if TYPE_CHECKING: - from typing import ( - Any, - Callable, - Container, - Coroutine, - TypeVar, - ) from trezorio import WireInterface + from typing import Any, Callable, Container, Coroutine, TypeVar Msg = TypeVar("Msg", bound=protobuf.MessageType) HandlerTask = Coroutine[Any, Any, protobuf.MessageType] diff --git a/core/src/trezor/wire/context.py b/core/src/trezor/wire/context.py index 8dda31629d..9df3473549 100644 --- a/core/src/trezor/wire/context.py +++ b/core/src/trezor/wire/context.py @@ -20,6 +20,7 @@ from trezor import log, loop, protobuf from . import codec_v1 if TYPE_CHECKING: + from trezorio import WireInterface from typing import ( Any, Awaitable, @@ -30,7 +31,6 @@ if TYPE_CHECKING: TypeVar, overload, ) - from trezorio import WireInterface Msg = TypeVar("Msg", bound=protobuf.MessageType) HandlerTask = Coroutine[Any, Any, protobuf.MessageType]