From ac711fb8ee9d6c178507072f0df046642bd29d89 Mon Sep 17 00:00:00 2001 From: Martin Milata Date: Thu, 18 Mar 2021 10:48:50 +0100 Subject: [PATCH] style(core): use more recent type annotation syntax https://www.python.org/dev/peps/pep-0585/ - Type Hinting Generics In Standard Collections https://www.python.org/dev/peps/pep-0604/ - Allow writing union types as X | Y --- .../extmod/modtrezorconfig/modtrezorconfig.c | 14 ++-- .../modtrezorcrypto/modtrezorcrypto-aes.h | 2 +- .../modtrezorcrypto/modtrezorcrypto-bip32.h | 6 +- .../modtrezorcrypto/modtrezorcrypto-bip39.h | 4 +- .../modtrezorcrypto-blake256.h | 2 +- .../modtrezorcrypto/modtrezorcrypto-blake2b.h | 6 +- .../modtrezorcrypto/modtrezorcrypto-blake2s.h | 6 +- .../modtrezorcrypto/modtrezorcrypto-ed25519.h | 4 +- .../modtrezorcrypto/modtrezorcrypto-groestl.h | 2 +- .../modtrezorcrypto/modtrezorcrypto-hmac.h | 2 +- .../modtrezorcrypto/modtrezorcrypto-monero.h | 78 +++++++++---------- .../modtrezorcrypto/modtrezorcrypto-pbkdf2.h | 2 +- .../modtrezorcrypto-ripemd160.h | 2 +- .../modtrezorcrypto-secp256k1.h | 2 +- .../modtrezorcrypto/modtrezorcrypto-sha1.h | 2 +- .../modtrezorcrypto/modtrezorcrypto-sha256.h | 2 +- .../modtrezorcrypto-sha3-256.h | 2 +- .../modtrezorcrypto-sha3-512.h | 2 +- .../modtrezorcrypto/modtrezorcrypto-sha512.h | 2 +- .../modtrezorcrypto/modtrezorcrypto-shamir.h | 2 +- .../extmod/modtrezorio/modtrezorio-fatfs.h | 14 ++-- .../extmod/modtrezorio/modtrezorio-poll.h | 2 +- .../extmod/modtrezorio/modtrezorio-usb.h | 2 +- .../extmod/modtrezorui/modtrezorui-display.h | 24 +++--- .../extmod/modtrezorutils/modtrezorutils.c | 6 +- core/mocks/generated/trezorconfig.pyi | 14 ++-- .../mocks/generated/trezorcrypto/__init__.pyi | 34 ++++---- core/mocks/generated/trezorcrypto/bip32.pyi | 6 +- core/mocks/generated/trezorcrypto/bip39.pyi | 4 +- core/mocks/generated/trezorcrypto/ed25519.pyi | 4 +- core/mocks/generated/trezorcrypto/monero.pyi | 78 +++++++++---------- .../generated/trezorcrypto/secp256k1.pyi | 2 +- core/mocks/generated/trezorcrypto/shamir.pyi | 2 +- core/mocks/generated/trezorio/__init__.pyi | 4 +- core/mocks/generated/trezorio/fatfs.pyi | 14 ++-- core/mocks/generated/trezorui.pyi | 24 +++--- core/mocks/generated/trezorutils.pyi | 6 +- core/src/apps/base.py | 4 +- core/src/apps/bitcoin/addresses.py | 9 +-- core/src/apps/bitcoin/common.py | 3 +- core/src/apps/bitcoin/get_address.py | 5 +- core/src/apps/bitcoin/get_ownership_proof.py | 3 +- core/src/apps/bitcoin/keychain.py | 20 ++--- core/src/apps/bitcoin/multisig.py | 5 +- core/src/apps/bitcoin/ownership.py | 9 +-- core/src/apps/bitcoin/scripts.py | 26 +++---- core/src/apps/bitcoin/scripts_decred.py | 4 +- core/src/apps/bitcoin/sign_tx/__init__.py | 12 +-- core/src/apps/bitcoin/sign_tx/approvers.py | 19 +++-- core/src/apps/bitcoin/sign_tx/bitcoin.py | 37 +++++---- core/src/apps/bitcoin/sign_tx/bitcoinlike.py | 9 +-- core/src/apps/bitcoin/sign_tx/decred.py | 18 ++--- core/src/apps/bitcoin/sign_tx/hash143.py | 10 +-- core/src/apps/bitcoin/sign_tx/helpers.py | 14 ++-- core/src/apps/bitcoin/sign_tx/layout.py | 4 +- core/src/apps/bitcoin/sign_tx/matchcheck.py | 10 +-- core/src/apps/bitcoin/sign_tx/tx_info.py | 12 +-- core/src/apps/bitcoin/sign_tx/zcash.py | 17 ++-- core/src/apps/bitcoin/verification.py | 9 +-- core/src/apps/bitcoin/writers.py | 8 +- core/src/apps/cardano/address.py | 21 +++-- core/src/apps/cardano/certificates.py | 20 +++-- core/src/apps/cardano/get_public_key.py | 3 +- .../apps/cardano/helpers/staking_use_cases.py | 3 +- core/src/apps/cardano/helpers/utils.py | 9 +-- core/src/apps/cardano/layout.py | 45 ++++++----- core/src/apps/cardano/sign_tx.py | 76 +++++++++--------- core/src/apps/common/cbor.py | 6 +- core/src/apps/common/coininfo.py | 18 ++--- core/src/apps/common/coininfo.py.mako | 18 ++--- core/src/apps/common/confirm.py | 6 +- core/src/apps/common/keychain.py | 15 ++-- core/src/apps/common/mnemonic.py | 5 +- core/src/apps/common/paths.py | 8 +- core/src/apps/common/request_pin.py | 6 +- core/src/apps/common/safety_checks.py | 7 +- core/src/apps/common/sdcard.py | 5 +- core/src/apps/common/seed.py | 6 +- core/src/apps/debug/__init__.py | 5 +- core/src/apps/eos/actions/layout.py | 7 +- core/src/apps/eos/get_public_key.py | 3 +- core/src/apps/ethereum/networks.py | 6 +- core/src/apps/ethereum/networks.py.mako | 6 +- core/src/apps/homescreen/homescreen.py | 5 +- core/src/apps/management/backup_types.py | 4 +- .../management/recovery_device/homescreen.py | 5 +- .../recovery_device/keyboard_bip39.py | 7 +- .../recovery_device/keyboard_slip39.py | 15 ++-- .../apps/management/recovery_device/layout.py | 22 +++--- .../management/recovery_device/recover.py | 8 +- .../recovery_device/word_validity.py | 9 +-- .../apps/management/reset_device/layout.py | 5 +- core/src/apps/management/sd_protect.py | 4 +- core/src/apps/misc/sign_identity.py | 8 +- core/src/apps/monero/layout/confirms.py | 3 +- core/src/apps/monero/misc.py | 3 +- core/src/apps/monero/signing/state.py | 31 ++++---- .../signing/step_01_init_transaction.py | 7 +- .../apps/monero/signing/step_02_set_input.py | 7 +- .../signing/step_03_inputs_permutation.py | 5 +- .../apps/monero/signing/step_06_set_output.py | 9 +-- .../apps/monero/signing/step_09_sign_input.py | 3 +- .../apps/monero/signing/step_10_sign_final.py | 3 +- core/src/apps/monero/xmr/addresses.py | 11 ++- core/src/apps/monero/xmr/credentials.py | 11 ++- core/src/apps/monero/xmr/crypto/__init__.py | 9 +-- core/src/apps/monero/xmr/key_image.py | 13 ++-- core/src/apps/monero/xmr/mlsag.py | 35 ++++----- core/src/apps/monero/xmr/mlsag_hasher.py | 3 +- core/src/apps/monero/xmr/monero.py | 23 +++--- core/src/apps/monero/xmr/range_signatures.py | 5 +- .../apps/webauthn/add_resident_credential.py | 5 +- core/src/apps/webauthn/confirm.py | 8 +- core/src/apps/webauthn/credential.py | 26 +++---- core/src/apps/webauthn/fido2.py | 64 +++++++-------- core/src/apps/webauthn/knownapps.py | 12 +-- core/src/apps/webauthn/knownapps.py.mako | 12 +-- .../webauthn/remove_resident_credential.py | 5 +- .../src/apps/webauthn/resident_credentials.py | 4 +- core/src/protobuf.py | 35 ++++----- core/src/storage/cache.py | 12 +-- core/src/storage/common.py | 9 +-- core/src/storage/device.py | 17 ++-- core/src/storage/recovery.py | 12 +-- core/src/storage/recovery_shares.py | 7 +- core/src/storage/resident_credentials.py | 6 +- core/src/storage/sd_salt.py | 6 +- core/src/trezor/crypto/bech32.py | 24 +++--- core/src/trezor/crypto/cashaddr.py | 18 ++--- core/src/trezor/crypto/der.py | 5 +- core/src/trezor/crypto/slip39.py | 22 +++--- core/src/trezor/loop.py | 37 ++++----- core/src/trezor/messages/__init__.py | 7 +- core/src/trezor/pin.py | 6 +- core/src/trezor/sdcard.py | 4 +- core/src/trezor/ui/__init__.py | 10 +-- .../trezor/ui/components/common/__init__.py | 5 +- .../trezor/ui/components/common/confirm.py | 10 +-- core/src/trezor/ui/components/common/text.py | 14 ++-- core/src/trezor/ui/components/tt/button.py | 10 +-- core/src/trezor/ui/components/tt/checklist.py | 4 +- core/src/trezor/ui/components/tt/confirm.py | 20 ++--- core/src/trezor/ui/components/tt/info.py | 3 +- .../src/trezor/ui/components/tt/passphrase.py | 14 ++-- core/src/trezor/ui/components/tt/pin.py | 8 +- core/src/trezor/ui/components/tt/scroll.py | 24 +++--- core/src/trezor/ui/components/tt/swipe.py | 4 +- core/src/trezor/ui/components/tt/text.py | 5 +- .../trezor/ui/components/tt/word_select.py | 3 +- core/src/trezor/ui/container.py | 5 +- core/src/trezor/ui/layouts/tt.py | 50 ++++++------ core/src/trezor/ui/loader.py | 17 ++-- core/src/trezor/ui/popup.py | 5 +- core/src/trezor/utils.py | 5 +- core/src/trezor/wire/__init__.py | 34 ++++---- core/src/trezor/workflow.py | 12 +-- setup.cfg | 3 +- 157 files changed, 843 insertions(+), 1013 deletions(-) diff --git a/core/embed/extmod/modtrezorconfig/modtrezorconfig.c b/core/embed/extmod/modtrezorconfig/modtrezorconfig.c index e56cb2ffa..7c2c43039 100644 --- a/core/embed/extmod/modtrezorconfig/modtrezorconfig.c +++ b/core/embed/extmod/modtrezorconfig/modtrezorconfig.c @@ -47,7 +47,7 @@ STATIC secbool wrapped_ui_wait_callback(uint32_t wait, uint32_t progress, } /// def init( -/// ui_wait_callback: Optional[Callable[[int, int, str], bool]] = None +/// ui_wait_callback: Callable[[int, int, str], bool] | None = None /// ) -> None: /// """ /// Initializes the storage. Must be called before any other method is @@ -66,7 +66,7 @@ STATIC mp_obj_t mod_trezorconfig_init(size_t n_args, const mp_obj_t *args) { STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorconfig_init_obj, 0, 1, mod_trezorconfig_init); -/// def unlock(pin: str, ext_salt: Optional[bytes]) -> bool: +/// def unlock(pin: str, ext_salt: bytes | None) -> bool: /// """ /// Attempts to unlock the storage with the given PIN and external salt. /// Returns True on success, False on failure. @@ -91,7 +91,7 @@ STATIC mp_obj_t mod_trezorconfig_unlock(mp_obj_t pin, mp_obj_t ext_salt) { STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorconfig_unlock_obj, mod_trezorconfig_unlock); -/// def check_pin(pin: str, ext_salt: Optional[bytes]) -> bool: +/// def check_pin(pin: str, ext_salt: bytes | None) -> bool: /// """ /// Check the given PIN with the given external salt. /// Returns True on success, False on failure. @@ -152,8 +152,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorconfig_get_pin_rem_obj, /// def change_pin( /// oldpin: str, /// newpin: str, -/// old_ext_salt: Optional[bytes], -/// new_ext_salt: Optional[bytes], +/// old_ext_salt: bytes | None, +/// new_ext_salt: bytes | None, /// ) -> bool: /// """ /// Change PIN and external salt. Returns True on success, False on failure. @@ -219,7 +219,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorconfig_has_wipe_code_obj, /// def change_wipe_code( /// pin: str, -/// ext_salt: Optional[bytes], +/// ext_salt: bytes | None, /// wipe_code: str, /// ) -> bool: /// """ @@ -252,7 +252,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorconfig_change_wipe_code_obj, 3, 3, mod_trezorconfig_change_wipe_code); -/// def get(app: int, key: int, public: bool = False) -> Optional[bytes]: +/// def get(app: int, key: int, public: bool = False) -> bytes | None: /// """ /// Gets the value of the given key for the given app (or None if not set). /// Raises a RuntimeError if decryption or authentication of the stored diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-aes.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-aes.h index 78af6a066..ab15d165a 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-aes.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-aes.h @@ -53,7 +53,7 @@ typedef struct _mp_obj_AES_t { /// self, /// mode: int, /// key: bytes, -/// iv: Optional[bytes] = None, +/// iv: bytes | None = None, /// ) -> None: /// """ /// Initialize AES context. diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-bip32.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-bip32.h index 8dd685ade..1d6cb574c 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-bip32.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-bip32.h @@ -49,9 +49,9 @@ STATIC const mp_obj_type_t mod_trezorcrypto_HDNode_type; /// fingerprint: int, /// child_num: int, /// chain_code: bytes, -/// private_key: Optional[bytes] = None, -/// public_key: Optional[bytes] = None, -/// curve_name: Optional[str] = None, +/// private_key: bytes | None = None, +/// public_key: bytes | None = None, +/// curve_name: str | None = None, /// ) -> None: /// """ /// """ diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-bip39.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-bip39.h index 3873a6660..41331adae 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-bip39.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-bip39.h @@ -25,7 +25,7 @@ /// package: trezorcrypto.bip39 -/// def complete_word(prefix: str) -> Optional[str]: +/// def complete_word(prefix: str) -> str | None: /// """ /// Return the first word from the wordlist starting with prefix. /// """ @@ -125,7 +125,7 @@ STATIC void wrapped_ui_wait_callback(uint32_t current, uint32_t total) { /// def seed( /// mnemonic: str, /// passphrase: str, -/// callback: Optional[Callable[[int, int], None]] = None, +/// callback: Callable[[int, int], None] | None = None, /// ) -> bytes: /// """ /// Generate seed from mnemonic and passphrase. diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-blake256.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-blake256.h index 54b8ec94f..e78665f46 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-blake256.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-blake256.h @@ -37,7 +37,7 @@ typedef struct _mp_obj_Blake256_t { STATIC mp_obj_t mod_trezorcrypto_Blake256_update(mp_obj_t self, mp_obj_t data); -/// def __init__(self, data: Optional[bytes] = None) -> None: +/// def __init__(self, data: bytes | None = None) -> None: /// """ /// Creates a hash context object. /// """ diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-blake2b.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-blake2b.h index 47d6acadf..2fa7529cb 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-blake2b.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-blake2b.h @@ -41,10 +41,10 @@ STATIC mp_obj_t mod_trezorcrypto_Blake2b_update(mp_obj_t self, mp_obj_t data); /// def __init__( /// self, -/// data: Optional[bytes] = None, +/// data: bytes | None = None, /// outlen: int = blake2b.digest_size, -/// key: Optional[bytes] = None, -/// personal: Optional[bytes] = None, +/// key: bytes | None = None, +/// personal: bytes | None = None, /// ) -> None: /// """ /// Creates a hash context object. diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-blake2s.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-blake2s.h index be99143ae..2e53a9e7a 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-blake2s.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-blake2s.h @@ -41,10 +41,10 @@ STATIC mp_obj_t mod_trezorcrypto_Blake2s_update(mp_obj_t self, mp_obj_t data); /// def __init__( /// self, -/// data: Optional[bytes] = None, +/// data: bytes | None = None, /// outlen: int = blake2s.digest_size, -/// key: Optional[bytes] = None, -/// personal: Optional[bytes] = None, +/// key: bytes | None = None, +/// personal: bytes | None = None, /// ) -> None: /// """ /// Creates a hash context object. diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h index b0309b43f..d893d6f67 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h @@ -174,7 +174,7 @@ STATIC mp_obj_t mod_trezorcrypto_ed25519_verify(mp_obj_t public_key, STATIC MP_DEFINE_CONST_FUN_OBJ_3(mod_trezorcrypto_ed25519_verify_obj, mod_trezorcrypto_ed25519_verify); -/// def cosi_combine_publickeys(public_keys: List[bytes]) -> bytes: +/// def cosi_combine_publickeys(public_keys: list[bytes]) -> bytes: /// """ /// Combines a list of public keys used in COSI cosigning scheme. /// """ @@ -209,7 +209,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1( mod_trezorcrypto_ed25519_cosi_combine_publickeys_obj, mod_trezorcrypto_ed25519_cosi_combine_publickeys); -/// def cosi_combine_signatures(R: bytes, signatures: List[bytes]) -> bytes: +/// def cosi_combine_signatures(R: bytes, signatures: list[bytes]) -> bytes: /// """ /// Combines a list of signatures used in COSI cosigning scheme. /// """ diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-groestl.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-groestl.h index 6cadb9559..6d79bf756 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-groestl.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-groestl.h @@ -41,7 +41,7 @@ typedef struct _mp_obj_Groestl512_t { STATIC mp_obj_t mod_trezorcrypto_Groestl512_update(mp_obj_t self, mp_obj_t data); -/// def __init__(self, data: Optional[bytes] = None) -> None: +/// def __init__(self, data: bytes | None = None) -> None: /// """ /// Creates a hash context object. /// """ diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-hmac.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-hmac.h index 0a4eac8f7..92acbebcc 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-hmac.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-hmac.h @@ -48,7 +48,7 @@ STATIC mp_obj_t mod_trezorcrypto_Hmac_update(mp_obj_t self, mp_obj_t data); /// self, /// hashtype: int, /// key: bytes, -/// message: Optional[bytes] = None, +/// message: bytes | None = None, /// ) -> None: /// """ /// Create a HMAC context. diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-monero.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-monero.h index 1e863d489..bda7e3de6 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-monero.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-monero.h @@ -180,7 +180,7 @@ STATIC void mp_unpack_scalar(bignum256modm r, const mp_obj_t arg, /// EC point on ED25519 /// """ /// -/// def __init__(self, x: Optional[Union[Ge25519, bytes]] = None): +/// def __init__(self, x: Ge25519 | bytes | None = None): /// """ /// Constructor /// """ @@ -218,7 +218,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_monero_ge25519___del___obj, /// EC scalar on SC25519 /// """ /// -/// def __init__(self, x: Optional[Union[Sc25519, bytes, int]] = None): +/// def __init__(self, x: Sc25519 | bytes | int | None = None): /// """ /// Constructor /// """ @@ -261,7 +261,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1( /// XMR hasher /// """ /// -/// def __init__(self, x: Optional[bytes] = None): +/// def __init__(self, x: bytes | None = None): /// """ /// Constructor /// """ @@ -314,7 +314,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_monero_hasher___del___obj, /// mock:global /// def init256_modm( -/// dst: Optional[Sc25519], val: Union[int, bytes, Sc25519] +/// dst: Sc25519 | None, val: int | bytes | Sc25519 /// ) -> Sc25519: /// """ /// Initializes Sc25519 scalar @@ -399,7 +399,7 @@ STATIC mp_obj_t mod_trezorcrypto_monero_get256_modm(const mp_obj_t arg) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_monero_get256_modm_obj, mod_trezorcrypto_monero_get256_modm); -/// def add256_modm(r: Optional[Sc25519], a: Sc25519, b: Sc25519) -> Sc25519: +/// def add256_modm(r: Sc25519 | None, a: Sc25519, b: Sc25519) -> Sc25519: /// """ /// Scalar addition /// """ @@ -419,7 +419,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_add256_modm_obj, 2, 3, mod_trezorcrypto_monero_add256_modm); -/// def sub256_modm(r: Optional[Sc25519], a: Sc25519, b: Sc25519) -> Sc25519: +/// def sub256_modm(r: Sc25519 | None, a: Sc25519, b: Sc25519) -> Sc25519: /// """ /// Scalar subtraction /// """ @@ -439,7 +439,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_sub256_modm_obj, 2, 3, mod_trezorcrypto_monero_sub256_modm); -/// def mul256_modm(r: Optional[Sc25519], a: Sc25519, b: Sc25519) -> Sc25519: +/// def mul256_modm(r: Sc25519 | None, a: Sc25519, b: Sc25519) -> Sc25519: /// """ /// Scalar multiplication /// """ @@ -460,7 +460,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_mul256_modm); /// def mulsub256_modm( -/// r: Optional[Sc25519], a: Sc25519, b: Sc25519, c: Sc25519 +/// r: Sc25519 | None, a: Sc25519, b: Sc25519, c: Sc25519 /// ) -> Sc25519: /// """ /// c - a*b @@ -484,7 +484,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_mulsub256_modm); /// def muladd256_modm( -/// r: Optional[Sc25519], a: Sc25519, b: Sc25519, c: Sc25519 +/// r: Sc25519 | None, a: Sc25519, b: Sc25519, c: Sc25519 /// ) -> Sc25519: /// """ /// c + a*b @@ -507,7 +507,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_muladd256_modm_obj, 3, 4, mod_trezorcrypto_monero_muladd256_modm); -/// def inv256_modm(r: Optional[Sc25519], a: Sc25519) -> Sc25519: +/// def inv256_modm(r: Sc25519 | None, a: Sc25519) -> Sc25519: /// """ /// Scalar modular inversion /// """ @@ -542,7 +542,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_inv256_modm); /// def pack256_modm( -/// r: Optional[bytes], a: Sc25519, offset: Optional[int] = 0 +/// r: bytes | None, a: Sc25519, offset: int | None = 0 /// ) -> bytes: /// """ /// Scalar compression @@ -572,7 +572,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_pack256_modm); /// def unpack256_modm( -/// r: Optional[Sc25519], a: bytes, offset: int = 0 +/// r: Sc25519 | None, a: bytes, offset: int = 0 /// ) -> Sc25519: /// """ /// Scalar decompression @@ -591,7 +591,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_unpack256_modm); /// def unpack256_modm_noreduce( -/// r: Optional[Sc25519], a: bytes, offset: int = 0 +/// r: Sc25519 | None, a: bytes, offset: int = 0 /// ) -> Sc25519: /// """ /// Scalar decompression, raw, without modular reduction @@ -620,7 +620,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( // GE25519 Defs // -/// def ge25519_set_neutral(r: Optional[Ge25519]) -> Ge25519: +/// def ge25519_set_neutral(r: Ge25519 | None) -> Ge25519: /// """ /// Sets neutral point /// """ @@ -634,7 +634,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_ge25519_set_neutral_obj, 0, 1, mod_trezorcrypto_monero_ge25519_set_neutral); -/// def ge25519_set_xmr_h(r: Optional[Ge25519]) -> Ge25519: +/// def ge25519_set_xmr_h(r: Ge25519 | None) -> Ge25519: /// """ /// Sets H point /// """ @@ -676,7 +676,7 @@ STATIC mp_obj_t mod_trezorcrypto_monero_ge25519_eq(const mp_obj_t a, STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_monero_ge25519_eq_obj, mod_trezorcrypto_monero_ge25519_eq); -/// def ge25519_add(r: Optional[Ge25519], a: Ge25519, b: Ge25519) -> Ge25519: +/// def ge25519_add(r: Ge25519 | None, a: Ge25519, b: Ge25519) -> Ge25519: /// """ /// Adds EC points /// """ @@ -696,7 +696,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_ge25519_add_obj, 2, 3, mod_trezorcrypto_monero_ge25519_add); -/// def ge25519_sub(r: Optional[Ge25519], a: Ge25519, b: Ge25519) -> Ge25519: +/// def ge25519_sub(r: Ge25519 | None, a: Ge25519, b: Ge25519) -> Ge25519: /// """ /// Subtracts EC points /// """ @@ -716,7 +716,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_ge25519_sub_obj, 2, 3, mod_trezorcrypto_monero_ge25519_sub); -/// def ge25519_double(r: Optional[Ge25519], p: Ge25519) -> Ge25519: +/// def ge25519_double(r: Ge25519 | None, p: Ge25519) -> Ge25519: /// """ /// EC point doubling /// """ @@ -733,7 +733,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_ge25519_double_obj, 1, 2, mod_trezorcrypto_monero_ge25519_double); -/// def ge25519_mul8(r: Optional[Ge25519], p: Ge25519) -> Ge25519: +/// def ge25519_mul8(r: Ge25519 | None, p: Ge25519) -> Ge25519: /// """ /// EC point * 8 /// """ @@ -751,7 +751,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_ge25519_mul8); /// def ge25519_double_scalarmult_vartime( -/// r: Optional[Ge25519], p1: Ge25519, s1: Sc25519, s2: Sc25519 +/// r: Ge25519 | None, p1: Ge25519, s1: Sc25519, s2: Sc25519 /// ) -> Ge25519: /// """ /// s1 * G + s2 * p1 @@ -775,7 +775,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_ge25519_double_scalarmult_vartime); /// def ge25519_double_scalarmult_vartime2( -/// r: Optional[Ge25519], +/// r: Ge25519 | None, /// p1: Ge25519, /// s1: Sc25519, /// p2: Ge25519, @@ -806,7 +806,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_ge25519_double_scalarmult_vartime2); /// def ge25519_scalarmult_base( -/// r: Optional[Ge25519], s: Union[Sc25519, int] +/// r: Ge25519 | None, s: Sc25519 | int /// ) -> Ge25519: /// """ /// s * G @@ -835,7 +835,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_ge25519_scalarmult_base); /// def ge25519_scalarmult( -/// r: Optional[Ge25519], p: Ge25519, s: Union[Sc25519, int] +/// r: Ge25519 | None, p: Ge25519, s: Sc25519 | int /// ) -> Ge25519: /// """ /// s * p @@ -894,7 +894,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_ge25519_pack); /// def ge25519_unpack_vartime( -/// r: Optional[Ge25519], buff: bytes, offset: int = 0 +/// r: Ge25519 | None, buff: bytes, offset: int = 0 /// ) -> Ge25519: /// """ /// Point decompression @@ -941,7 +941,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_base58_addr_encode_check_obj, 2, 2, mod_trezorcrypto_monero_xmr_base58_addr_encode_check); -/// def base58_addr_decode_check(buff: bytes) -> Tuple[bytes, int]: +/// def base58_addr_decode_check(buff: bytes) -> tuple[bytes, int]: /// """ /// Monero block base 58 decoding, returning (decoded, tag) or raising on /// error. @@ -972,7 +972,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_base58_addr_decode_check_obj, 1, 1, mod_trezorcrypto_monero_xmr_base58_addr_decode_check); -/// def xmr_random_scalar(r: Optional[Sc25519] = None) -> Sc25519: +/// def xmr_random_scalar(r: Sc25519 | None = None) -> Sc25519: /// """ /// Generates a random scalar /// """ @@ -987,7 +987,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_random_scalar); // clang-format off -/// def xmr_fast_hash(r: Optional[bytes], buff: bytes, length: int, offset: int) -> bytes: +/// def xmr_fast_hash(r: bytes | None, buff: bytes, length: int, offset: int) -> bytes: // clang-format on /// """ /// XMR fast hash @@ -1027,7 +1027,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_fast_hash); // clang-format off -/// def xmr_hash_to_ec(r: Optional[Ge25519], buff: bytes, length: int, offset: +/// def xmr_hash_to_ec(r: Ge25519 | None, buff: bytes, length: int, offset: /// int) -> Ge25519: // clang-format on /// """ @@ -1056,7 +1056,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_hash_to_ec); // clang-format off -/// def xmr_hash_to_scalar(r: Optional[Sc25519], buff: bytes, length: int, +/// def xmr_hash_to_scalar(r: Sc25519 | None, buff: bytes, length: int, /// offset: int) -> Sc25519: // clang-format on /// """ @@ -1085,7 +1085,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_hash_to_scalar); /// def xmr_derivation_to_scalar( -/// r: Optional[Sc25519], p: Ge25519, output_index: int +/// r: Sc25519 | None, p: Ge25519, output_index: int /// ) -> Sc25519: /// """ /// H_s(derivation || varint(output_index)) @@ -1105,7 +1105,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_derivation_to_scalar); /// def xmr_generate_key_derivation( -/// r: Optional[Ge25519], A: Ge25519, b: Sc25519 +/// r: Ge25519 | None, A: Ge25519, b: Sc25519 /// ) -> Ge25519: /// """ /// 8*(key2*key1) @@ -1127,7 +1127,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_generate_key_derivation); /// def xmr_derive_private_key( -/// r: Optional[Sc25519], deriv: Ge25519, idx: int, base: Sc25519 +/// r: Sc25519 | None, deriv: Ge25519, idx: int, base: Sc25519 /// ) -> Sc25519: /// """ /// base + H_s(derivation || varint(output_index)) @@ -1149,7 +1149,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_derive_private_key); /// def xmr_derive_public_key( -/// r: Optional[Ge25519], deriv: Ge25519, idx: int, base: Ge25519 +/// r: Ge25519 | None, deriv: Ge25519, idx: int, base: Ge25519 /// ) -> Ge25519: /// """ /// H_s(derivation || varint(output_index))G + base @@ -1171,7 +1171,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_derive_public_key); /// def xmr_add_keys2( -/// r: Optional[Ge25519], a: Sc25519, b: Sc25519, B: Ge25519 +/// r: Ge25519 | None, a: Sc25519, b: Sc25519, B: Ge25519 /// ) -> Ge25519: /// """ /// aG + bB, G is basepoint @@ -1193,7 +1193,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_add_keys2); /// def xmr_add_keys2_vartime( -/// r: Optional[Ge25519], a: Sc25519, b: Sc25519, B: Ge25519 +/// r: Ge25519 | None, a: Sc25519, b: Sc25519, B: Ge25519 /// ) -> Ge25519: /// """ /// aG + bB, G is basepoint @@ -1216,7 +1216,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_add_keys2_vartime); /// def xmr_add_keys3( -/// r: Optional[Ge25519], a: Sc25519, A: Ge25519, b: Sc25519, B: Ge25519 +/// r: Ge25519 | None, a: Sc25519, A: Ge25519, b: Sc25519, B: Ge25519 /// ) -> Ge25519: /// """ /// aA + bB @@ -1240,7 +1240,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_add_keys3); /// def xmr_add_keys3_vartime( -/// r: Optional[Ge25519], a: Sc25519, A: Ge25519, b: Sc25519, B: Ge25519 +/// r: Ge25519 | None, a: Sc25519, A: Ge25519, b: Sc25519, B: Ge25519 /// ) -> Ge25519: /// """ /// aA + bB @@ -1265,7 +1265,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_add_keys3_vartime); /// def xmr_get_subaddress_secret_key( -/// r: Optional[Sc25519], major: int, minor: int, m: Sc25519 +/// r: Sc25519 | None, major: int, minor: int, m: Sc25519 /// ) -> Sc25519: /// """ /// Hs(SubAddr || a || index_major || index_minor) @@ -1285,7 +1285,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezorcrypto_monero_xmr_get_subaddress_secret_key_obj, 3, 4, mod_trezorcrypto_monero_xmr_get_subaddress_secret_key); -/// def xmr_gen_c(r: Optional[Ge25519], a: Sc25519, amount: int) -> Ge25519: +/// def xmr_gen_c(r: Ge25519 | None, a: Sc25519, amount: int) -> Ge25519: /// """ /// aG + amount * H /// """ diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-pbkdf2.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-pbkdf2.h index dd493e943..7a4245f16 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-pbkdf2.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-pbkdf2.h @@ -49,7 +49,7 @@ STATIC mp_obj_t mod_trezorcrypto_Pbkdf2_update(mp_obj_t self, mp_obj_t data); /// prf: int, /// password: bytes, /// salt: bytes, -/// iterations: Optional[int] = None, +/// iterations: int | None = None, /// blocknr: int = 1, /// ) -> None: /// """ diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-ripemd160.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-ripemd160.h index f893e1924..2e45a6568 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-ripemd160.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-ripemd160.h @@ -37,7 +37,7 @@ typedef struct _mp_obj_Ripemd160_t { STATIC mp_obj_t mod_trezorcrypto_Ripemd160_update(mp_obj_t self, mp_obj_t data); -/// def __init__(self, data: Optional[bytes] = None) -> None: +/// def __init__(self, data: bytes | None = None) -> None: /// """ /// Creates a hash context object. /// """ diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-secp256k1.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-secp256k1.h index 5aba55a50..82377fcea 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-secp256k1.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-secp256k1.h @@ -113,7 +113,7 @@ enum { /// secret_key: bytes, /// digest: bytes, /// compressed: bool = True, -/// canonical: Optional[int] = None, +/// canonical: int | None = None, /// ) -> bytes: /// """ /// Uses secret key to produce the signature of the digest. diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha1.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha1.h index 841c2222b..f664e167d 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha1.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha1.h @@ -37,7 +37,7 @@ typedef struct _mp_obj_Sha1_t { STATIC mp_obj_t mod_trezorcrypto_Sha1_update(mp_obj_t self, mp_obj_t data); -/// def __init__(self, data: Optional[bytes] = None) -> None: +/// def __init__(self, data: bytes | None = None) -> None: /// """ /// Creates a hash context object. /// """ diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha256.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha256.h index a659eb529..960d27aaa 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha256.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha256.h @@ -37,7 +37,7 @@ typedef struct _mp_obj_Sha256_t { STATIC mp_obj_t mod_trezorcrypto_Sha256_update(mp_obj_t self, mp_obj_t data); -/// def __init__(self, data: Optional[bytes] = None) -> None: +/// def __init__(self, data: bytes | None = None) -> None: /// """ /// Creates a hash context object. /// """ diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha3-256.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha3-256.h index 62bd7e59d..b6c5ebcb2 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha3-256.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha3-256.h @@ -40,7 +40,7 @@ STATIC mp_obj_t mod_trezorcrypto_Sha3_256_update(mp_obj_t self, mp_obj_t data); /// def __init__( /// self, -/// data: Optional[bytes] = None, +/// data: bytes | None = None, /// keccak: bool = False, /// ) -> None: /// """ diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha3-512.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha3-512.h index 5514b8556..5ab89b308 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha3-512.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha3-512.h @@ -40,7 +40,7 @@ STATIC mp_obj_t mod_trezorcrypto_Sha3_512_update(mp_obj_t self, mp_obj_t data); /// def __init__( /// self, -/// data: Optional[bytes] = None, +/// data: bytes | None = None, /// keccak: bool = False, /// ) -> None: /// """ diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha512.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha512.h index e84501d28..eec67d1ce 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha512.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-sha512.h @@ -37,7 +37,7 @@ typedef struct _mp_obj_Sha512_t { STATIC mp_obj_t mod_trezorcrypto_Sha512_update(mp_obj_t self, mp_obj_t data); -/// def __init__(self, data: Optional[bytes] = None) -> None: +/// def __init__(self, data: bytes | None = None) -> None: /// """ /// Creates a hash context object. /// """ diff --git a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-shamir.h b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-shamir.h index 22336d20e..09d4b3f74 100644 --- a/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-shamir.h +++ b/core/embed/extmod/modtrezorcrypto/modtrezorcrypto-shamir.h @@ -27,7 +27,7 @@ /// package: trezorcrypto.shamir -/// def interpolate(shares: List[Tuple[int, bytes]], x: int) -> bytes: +/// def interpolate(shares: list[tuple[int, bytes]], x: int) -> bytes: /// """ /// Returns f(x) given the Shamir shares (x_1, f(x_1)), ... , (x_k, f(x_k)). /// :param shares: The Shamir shares. diff --git a/core/embed/extmod/modtrezorio/modtrezorio-fatfs.h b/core/embed/extmod/modtrezorio/modtrezorio-fatfs.h index a7ce142cf..7c5f0865c 100644 --- a/core/embed/extmod/modtrezorio/modtrezorio-fatfs.h +++ b/core/embed/extmod/modtrezorio/modtrezorio-fatfs.h @@ -170,9 +170,9 @@ typedef struct _mp_obj_FatFSFile_t { /// from types import TracebackType /// def __exit__( -/// self, type: Optional[Type[BaseException]], -/// value: Optional[BaseException], -/// traceback: Optional[TracebackType], +/// self, type: type[BaseException] | None, +/// value: BaseException | None, +/// traceback: TracebackType | None, /// ) -> None: /// """ /// Close an open file object @@ -223,7 +223,7 @@ STATIC mp_obj_t mod_trezorio_FatFSFile_read(mp_obj_t self, mp_obj_t data) { STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorio_FatFSFile_read_obj, mod_trezorio_FatFSFile_read); -/// def write(self, data: Union[bytes, bytearray]) -> int: +/// def write(self, data: bytes | bytearray) -> int: /// """ /// Write data to the file /// """ @@ -312,7 +312,7 @@ STATIC const mp_obj_type_t mod_trezorio_FatFSFile_type = { .locals_dict = (void *)&mod_trezorio_FatFSFile_locals_dict, }; -/// class FatFSDir(Iterator[Tuple[int, str, str]]): +/// class FatFSDir(Iterator[tuple[int, str, str]]): /// """ /// Class encapsulating directory /// """ @@ -321,7 +321,7 @@ typedef struct _mp_obj_FatFSDir_t { DIR dp; } mp_obj_FatFSDir_t; -/// def __next__(self) -> Tuple[int, str, str]: +/// def __next__(self) -> tuple[int, str, str]: /// """ /// Read an entry in the directory /// """ @@ -453,7 +453,7 @@ STATIC mp_obj_t mod_trezorio_fatfs_unlink(mp_obj_t path) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorio_fatfs_unlink_obj, mod_trezorio_fatfs_unlink); -/// def stat(path: str) -> Tuple[int, str, str]: +/// def stat(path: str) -> tuple[int, str, str]: /// """ /// Get file status /// """ diff --git a/core/embed/extmod/modtrezorio/modtrezorio-poll.h b/core/embed/extmod/modtrezorio/modtrezorio-poll.h index f771bd9bc..c52f7e8d3 100644 --- a/core/embed/extmod/modtrezorio/modtrezorio-poll.h +++ b/core/embed/extmod/modtrezorio/modtrezorio-poll.h @@ -28,7 +28,7 @@ /// package: trezorio.__init__ -/// def poll(ifaces: Iterable[int], list_ref: List, timeout_ms: int) -> bool: +/// def poll(ifaces: Iterable[int], list_ref: list, timeout_ms: int) -> bool: /// """ /// Wait until one of `ifaces` is ready to read or write (using masks // `io.POLL_READ` and `io.POLL_WRITE`) and assign the result into diff --git a/core/embed/extmod/modtrezorio/modtrezorio-usb.h b/core/embed/extmod/modtrezorio/modtrezorio-usb.h index 98bc40a96..57fb6aa31 100644 --- a/core/embed/extmod/modtrezorio/modtrezorio-usb.h +++ b/core/embed/extmod/modtrezorio/modtrezorio-usb.h @@ -158,7 +158,7 @@ STATIC mp_obj_t mod_trezorio_USB_make_new(const mp_obj_type_t *type, return MP_OBJ_FROM_PTR(o); } -/// def add(self, iface: Union[HID, VCP, WebUSB]) -> None: +/// def add(self, iface: HID | VCP | WebUSB) -> None: /// """ /// Registers passed interface into the USB stack. /// """ diff --git a/core/embed/extmod/modtrezorui/modtrezorui-display.h b/core/embed/extmod/modtrezorui/modtrezorui-display.h index b0d7aea47..966c9efc7 100644 --- a/core/embed/extmod/modtrezorui/modtrezorui-display.h +++ b/core/embed/extmod/modtrezorui/modtrezorui-display.h @@ -93,8 +93,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorui_Display_bar_obj, 6, 6, /// w: int, /// h: int, /// fgcolor: int, -/// bgcolor: Optional[int] = None, -/// radius: Optional[int] = None, +/// bgcolor: int | None = None, +/// radius: int | None = None, /// ) -> None: /// """ /// Renders a rounded bar at position (x,y = upper left corner) with width w @@ -117,7 +117,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorui_Display_bar_radius_obj, 8, 8, mod_trezorui_Display_bar_radius); -/// def toif_info(self, image: bytes) -> Tuple[int, int, bool]: +/// def toif_info(self, image: bytes) -> tuple[int, int, bool]: /// """ /// Returns tuple containing TOIF image dimensions: width, height, and /// whether it is grayscale. @@ -243,8 +243,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorui_Display_icon_obj, 6, 6, /// yoffset: int, /// fgcolor: int, /// bgcolor: int, -/// icon: Optional[bytes] = None, -/// iconfgcolor: Optional[int] = None, +/// icon: bytes | None = None, +/// iconfgcolor: int | None = None, /// ) -> None: /// """ /// Renders a rotating loader graphic. @@ -317,8 +317,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorui_Display_print_obj, /// font: int, /// fgcolor: int, /// bgcolor: int, -/// text_offset: Optional[int] = None, -/// text_len: Optional[int] = None, +/// text_offset: int | None = None, +/// text_len: int | None = None, /// ) -> None: /// """ /// Renders left-aligned text at position (x,y) where x is left position and @@ -421,8 +421,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorui_Display_text_right_obj, /// self, /// text: str, /// font: int, -/// text_offset: Optional[int] = None, -/// text_len: Optional[int] = None, +/// text_offset: int | None = None, +/// text_len: int | None = None, /// ) -> int: /// """ /// Returns a width of text in pixels. Font font is used for rendering. @@ -499,7 +499,7 @@ STATIC mp_obj_t mod_trezorui_Display_qrcode(size_t n_args, STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorui_Display_qrcode_obj, 5, 5, mod_trezorui_Display_qrcode); -/// def orientation(self, degrees: Optional[int] = None) -> int: +/// def orientation(self, degrees: int | None = None) -> int: /// """ /// Sets display orientation to 0, 90, 180 or 270 degrees. /// Everything needs to be redrawn again when this function is used. @@ -524,7 +524,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorui_Display_orientation_obj, 1, 2, mod_trezorui_Display_orientation); -/// def backlight(self, val: Optional[int] = None) -> int: +/// def backlight(self, val: int | None = None) -> int: /// """ /// Sets backlight intensity to the value specified in val. /// Call without the val parameter to just perform the read of the value. @@ -547,7 +547,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorui_Display_backlight_obj, 1, 2, mod_trezorui_Display_backlight); -/// def offset(self, xy: Optional[Tuple[int, int]] = None) -> Tuple[int, int]: +/// def offset(self, xy: tuple[int, int] | None = None) -> tuple[int, int]: /// """ /// Sets offset (x, y) for all subsequent drawing calls. /// Call without the xy parameter to just perform the read of the value. diff --git a/core/embed/extmod/modtrezorutils/modtrezorutils.c b/core/embed/extmod/modtrezorutils/modtrezorutils.c index c5bcadf2b..421e6ca73 100644 --- a/core/embed/extmod/modtrezorutils/modtrezorutils.c +++ b/core/embed/extmod/modtrezorutils/modtrezorutils.c @@ -58,11 +58,11 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorutils_consteq_obj, mod_trezorutils_consteq); /// def memcpy( -/// dst: Union[bytearray, memoryview], +/// dst: bytearray | memoryview, /// dst_ofs: int, /// src: bytes, /// src_ofs: int, -/// n: Optional[int] = None, +/// n: int | None = None, /// ) -> int: /// """ /// Copies at most `n` bytes from `src` at offset `src_ofs` to @@ -99,7 +99,7 @@ STATIC mp_obj_t mod_trezorutils_memcpy(size_t n_args, const mp_obj_t *args) { STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorutils_memcpy_obj, 4, 5, mod_trezorutils_memcpy); -/// def halt(msg: Optional[str] = None) -> None: +/// def halt(msg: str | None = None) -> None: /// """ /// Halts execution. /// """ diff --git a/core/mocks/generated/trezorconfig.pyi b/core/mocks/generated/trezorconfig.pyi index de53e202e..5b4291549 100644 --- a/core/mocks/generated/trezorconfig.pyi +++ b/core/mocks/generated/trezorconfig.pyi @@ -3,7 +3,7 @@ from typing import * # extmod/modtrezorconfig/modtrezorconfig.c def init( - ui_wait_callback: Optional[Callable[[int, int, str], bool]] = None + ui_wait_callback: Callable[[int, int, str], bool] | None = None ) -> None: """ Initializes the storage. Must be called before any other method is @@ -12,7 +12,7 @@ def init( # extmod/modtrezorconfig/modtrezorconfig.c -def unlock(pin: str, ext_salt: Optional[bytes]) -> bool: +def unlock(pin: str, ext_salt: bytes | None) -> bool: """ Attempts to unlock the storage with the given PIN and external salt. Returns True on success, False on failure. @@ -20,7 +20,7 @@ def unlock(pin: str, ext_salt: Optional[bytes]) -> bool: # extmod/modtrezorconfig/modtrezorconfig.c -def check_pin(pin: str, ext_salt: Optional[bytes]) -> bool: +def check_pin(pin: str, ext_salt: bytes | None) -> bool: """ Check the given PIN with the given external salt. Returns True on success, False on failure. @@ -59,8 +59,8 @@ def get_pin_rem() -> int: def change_pin( oldpin: str, newpin: str, - old_ext_salt: Optional[bytes], - new_ext_salt: Optional[bytes], + old_ext_salt: bytes | None, + new_ext_salt: bytes | None, ) -> bool: """ Change PIN and external salt. Returns True on success, False on failure. @@ -84,7 +84,7 @@ def has_wipe_code() -> bool: # extmod/modtrezorconfig/modtrezorconfig.c def change_wipe_code( pin: str, - ext_salt: Optional[bytes], + ext_salt: bytes | None, wipe_code: str, ) -> bool: """ @@ -93,7 +93,7 @@ def change_wipe_code( # extmod/modtrezorconfig/modtrezorconfig.c -def get(app: int, key: int, public: bool = False) -> Optional[bytes]: +def get(app: int, key: int, public: bool = False) -> bytes | None: """ Gets the value of the given key for the given app (or None if not set). Raises a RuntimeError if decryption or authentication of the stored diff --git a/core/mocks/generated/trezorcrypto/__init__.pyi b/core/mocks/generated/trezorcrypto/__init__.pyi index ff5f3c228..290d89e91 100644 --- a/core/mocks/generated/trezorcrypto/__init__.pyi +++ b/core/mocks/generated/trezorcrypto/__init__.pyi @@ -16,7 +16,7 @@ class aes: self, mode: int, key: bytes, - iv: Optional[bytes] = None, + iv: bytes | None = None, ) -> None: """ Initialize AES context. @@ -41,7 +41,7 @@ class blake256: block_size: int digest_size: int - def __init__(self, data: Optional[bytes] = None) -> None: + def __init__(self, data: bytes | None = None) -> None: """ Creates a hash context object. """ @@ -67,10 +67,10 @@ class blake2b: def __init__( self, - data: Optional[bytes] = None, + data: bytes | None = None, outlen: int = blake2b.digest_size, - key: Optional[bytes] = None, - personal: Optional[bytes] = None, + key: bytes | None = None, + personal: bytes | None = None, ) -> None: """ Creates a hash context object. @@ -97,10 +97,10 @@ class blake2s: def __init__( self, - data: Optional[bytes] = None, + data: bytes | None = None, outlen: int = blake2s.digest_size, - key: Optional[bytes] = None, - personal: Optional[bytes] = None, + key: bytes | None = None, + personal: bytes | None = None, ) -> None: """ Creates a hash context object. @@ -162,7 +162,7 @@ class groestl512: block_size: int digest_size: int - def __init__(self, data: Optional[bytes] = None) -> None: + def __init__(self, data: bytes | None = None) -> None: """ Creates a hash context object. """ @@ -190,7 +190,7 @@ class hmac: self, hashtype: int, key: bytes, - message: Optional[bytes] = None, + message: bytes | None = None, ) -> None: """ Create a HMAC context. @@ -220,7 +220,7 @@ class pbkdf2: prf: int, password: bytes, salt: bytes, - iterations: Optional[int] = None, + iterations: int | None = None, blocknr: int = 1, ) -> None: """ @@ -246,7 +246,7 @@ class ripemd160: block_size: int digest_size: int - def __init__(self, data: Optional[bytes] = None) -> None: + def __init__(self, data: bytes | None = None) -> None: """ Creates a hash context object. """ @@ -270,7 +270,7 @@ class sha1: block_size: int digest_size: int - def __init__(self, data: Optional[bytes] = None) -> None: + def __init__(self, data: bytes | None = None) -> None: """ Creates a hash context object. """ @@ -294,7 +294,7 @@ class sha256: block_size: int digest_size: int - def __init__(self, data: Optional[bytes] = None) -> None: + def __init__(self, data: bytes | None = None) -> None: """ Creates a hash context object. """ @@ -320,7 +320,7 @@ class sha3_256: def __init__( self, - data: Optional[bytes] = None, + data: bytes | None = None, keccak: bool = False, ) -> None: """ @@ -353,7 +353,7 @@ class sha3_512: def __init__( self, - data: Optional[bytes] = None, + data: bytes | None = None, keccak: bool = False, ) -> None: """ @@ -384,7 +384,7 @@ class sha512: block_size: int digest_size: int - def __init__(self, data: Optional[bytes] = None) -> None: + def __init__(self, data: bytes | None = None) -> None: """ Creates a hash context object. """ diff --git a/core/mocks/generated/trezorcrypto/bip32.pyi b/core/mocks/generated/trezorcrypto/bip32.pyi index a1d3b54c6..ce406884b 100644 --- a/core/mocks/generated/trezorcrypto/bip32.pyi +++ b/core/mocks/generated/trezorcrypto/bip32.pyi @@ -13,9 +13,9 @@ class HDNode: fingerprint: int, child_num: int, chain_code: bytes, - private_key: Optional[bytes] = None, - public_key: Optional[bytes] = None, - curve_name: Optional[str] = None, + private_key: bytes | None = None, + public_key: bytes | None = None, + curve_name: str | None = None, ) -> None: """ """ diff --git a/core/mocks/generated/trezorcrypto/bip39.pyi b/core/mocks/generated/trezorcrypto/bip39.pyi index 615697fd9..bc211c034 100644 --- a/core/mocks/generated/trezorcrypto/bip39.pyi +++ b/core/mocks/generated/trezorcrypto/bip39.pyi @@ -2,7 +2,7 @@ from typing import * # extmod/modtrezorcrypto/modtrezorcrypto-bip39.h -def complete_word(prefix: str) -> Optional[str]: +def complete_word(prefix: str) -> str | None: """ Return the first word from the wordlist starting with prefix. """ @@ -42,7 +42,7 @@ def check(mnemonic: str) -> bool: def seed( mnemonic: str, passphrase: str, - callback: Optional[Callable[[int, int], None]] = None, + callback: Callable[[int, int], None] | None = None, ) -> bytes: """ Generate seed from mnemonic and passphrase. diff --git a/core/mocks/generated/trezorcrypto/ed25519.pyi b/core/mocks/generated/trezorcrypto/ed25519.pyi index d55277824..54d527a1e 100644 --- a/core/mocks/generated/trezorcrypto/ed25519.pyi +++ b/core/mocks/generated/trezorcrypto/ed25519.pyi @@ -40,14 +40,14 @@ def verify(public_key: bytes, signature: bytes, message: bytes) -> bool: # extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h -def cosi_combine_publickeys(public_keys: List[bytes]) -> bytes: +def cosi_combine_publickeys(public_keys: list[bytes]) -> bytes: """ Combines a list of public keys used in COSI cosigning scheme. """ # extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h -def cosi_combine_signatures(R: bytes, signatures: List[bytes]) -> bytes: +def cosi_combine_signatures(R: bytes, signatures: list[bytes]) -> bytes: """ Combines a list of signatures used in COSI cosigning scheme. """ diff --git a/core/mocks/generated/trezorcrypto/monero.pyi b/core/mocks/generated/trezorcrypto/monero.pyi index a1bc84a39..9b9e3b6f5 100644 --- a/core/mocks/generated/trezorcrypto/monero.pyi +++ b/core/mocks/generated/trezorcrypto/monero.pyi @@ -6,7 +6,7 @@ class Ge25519: """ EC point on ED25519 """ - def __init__(self, x: Optional[Union[Ge25519, bytes]] = None): + def __init__(self, x: Ge25519 | bytes | None = None): """ Constructor """ @@ -17,7 +17,7 @@ class Sc25519: """ EC scalar on SC25519 """ - def __init__(self, x: Optional[Union[Sc25519, bytes, int]] = None): + def __init__(self, x: Sc25519 | bytes | int | None = None): """ Constructor """ @@ -28,7 +28,7 @@ class Hasher: """ XMR hasher """ - def __init__(self, x: Optional[bytes] = None): + def __init__(self, x: bytes | None = None): """ Constructor """ @@ -48,7 +48,7 @@ class Hasher: # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def init256_modm( - dst: Optional[Sc25519], val: Union[int, bytes, Sc25519] + dst: Sc25519 | None, val: int | bytes | Sc25519 ) -> Sc25519: """ Initializes Sc25519 scalar @@ -85,21 +85,21 @@ def get256_modm(a: Sc25519) -> int: # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def add256_modm(r: Optional[Sc25519], a: Sc25519, b: Sc25519) -> Sc25519: +def add256_modm(r: Sc25519 | None, a: Sc25519, b: Sc25519) -> Sc25519: """ Scalar addition """ # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def sub256_modm(r: Optional[Sc25519], a: Sc25519, b: Sc25519) -> Sc25519: +def sub256_modm(r: Sc25519 | None, a: Sc25519, b: Sc25519) -> Sc25519: """ Scalar subtraction """ # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def mul256_modm(r: Optional[Sc25519], a: Sc25519, b: Sc25519) -> Sc25519: +def mul256_modm(r: Sc25519 | None, a: Sc25519, b: Sc25519) -> Sc25519: """ Scalar multiplication """ @@ -107,7 +107,7 @@ def mul256_modm(r: Optional[Sc25519], a: Sc25519, b: Sc25519) -> Sc25519: # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def mulsub256_modm( - r: Optional[Sc25519], a: Sc25519, b: Sc25519, c: Sc25519 + r: Sc25519 | None, a: Sc25519, b: Sc25519, c: Sc25519 ) -> Sc25519: """ c - a*b @@ -116,7 +116,7 @@ def mulsub256_modm( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def muladd256_modm( - r: Optional[Sc25519], a: Sc25519, b: Sc25519, c: Sc25519 + r: Sc25519 | None, a: Sc25519, b: Sc25519, c: Sc25519 ) -> Sc25519: """ c + a*b @@ -124,7 +124,7 @@ def muladd256_modm( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def inv256_modm(r: Optional[Sc25519], a: Sc25519) -> Sc25519: +def inv256_modm(r: Sc25519 | None, a: Sc25519) -> Sc25519: """ Scalar modular inversion """ @@ -132,7 +132,7 @@ def inv256_modm(r: Optional[Sc25519], a: Sc25519) -> Sc25519: # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def pack256_modm( - r: Optional[bytes], a: Sc25519, offset: Optional[int] = 0 + r: bytes | None, a: Sc25519, offset: int | None = 0 ) -> bytes: """ Scalar compression @@ -141,7 +141,7 @@ def pack256_modm( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def unpack256_modm( - r: Optional[Sc25519], a: bytes, offset: int = 0 + r: Sc25519 | None, a: bytes, offset: int = 0 ) -> Sc25519: """ Scalar decompression @@ -150,7 +150,7 @@ def unpack256_modm( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def unpack256_modm_noreduce( - r: Optional[Sc25519], a: bytes, offset: int = 0 + r: Sc25519 | None, a: bytes, offset: int = 0 ) -> Sc25519: """ Scalar decompression, raw, without modular reduction @@ -158,14 +158,14 @@ def unpack256_modm_noreduce( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def ge25519_set_neutral(r: Optional[Ge25519]) -> Ge25519: +def ge25519_set_neutral(r: Ge25519 | None) -> Ge25519: """ Sets neutral point """ # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def ge25519_set_xmr_h(r: Optional[Ge25519]) -> Ge25519: +def ge25519_set_xmr_h(r: Ge25519 | None) -> Ge25519: """ Sets H point """ @@ -186,28 +186,28 @@ def ge25519_eq(a: Ge25519, b: Ge25519) -> bool: # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def ge25519_add(r: Optional[Ge25519], a: Ge25519, b: Ge25519) -> Ge25519: +def ge25519_add(r: Ge25519 | None, a: Ge25519, b: Ge25519) -> Ge25519: """ Adds EC points """ # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def ge25519_sub(r: Optional[Ge25519], a: Ge25519, b: Ge25519) -> Ge25519: +def ge25519_sub(r: Ge25519 | None, a: Ge25519, b: Ge25519) -> Ge25519: """ Subtracts EC points """ # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def ge25519_double(r: Optional[Ge25519], p: Ge25519) -> Ge25519: +def ge25519_double(r: Ge25519 | None, p: Ge25519) -> Ge25519: """ EC point doubling """ # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def ge25519_mul8(r: Optional[Ge25519], p: Ge25519) -> Ge25519: +def ge25519_mul8(r: Ge25519 | None, p: Ge25519) -> Ge25519: """ EC point * 8 """ @@ -215,7 +215,7 @@ def ge25519_mul8(r: Optional[Ge25519], p: Ge25519) -> Ge25519: # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def ge25519_double_scalarmult_vartime( - r: Optional[Ge25519], p1: Ge25519, s1: Sc25519, s2: Sc25519 + r: Ge25519 | None, p1: Ge25519, s1: Sc25519, s2: Sc25519 ) -> Ge25519: """ s1 * G + s2 * p1 @@ -224,7 +224,7 @@ def ge25519_double_scalarmult_vartime( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def ge25519_double_scalarmult_vartime2( - r: Optional[Ge25519], + r: Ge25519 | None, p1: Ge25519, s1: Sc25519, p2: Ge25519, @@ -237,7 +237,7 @@ def ge25519_double_scalarmult_vartime2( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def ge25519_scalarmult_base( - r: Optional[Ge25519], s: Union[Sc25519, int] + r: Ge25519 | None, s: Sc25519 | int ) -> Ge25519: """ s * G @@ -246,7 +246,7 @@ def ge25519_scalarmult_base( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def ge25519_scalarmult( - r: Optional[Ge25519], p: Ge25519, s: Union[Sc25519, int] + r: Ge25519 | None, p: Ge25519, s: Sc25519 | int ) -> Ge25519: """ s * p @@ -262,7 +262,7 @@ def ge25519_pack(r: bytes, p: Ge25519, offset: int = 0) -> bytes: # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def ge25519_unpack_vartime( - r: Optional[Ge25519], buff: bytes, offset: int = 0 + r: Ge25519 | None, buff: bytes, offset: int = 0 ) -> Ge25519: """ Point decompression @@ -277,7 +277,7 @@ def base58_addr_encode_check(tag: int, buff: bytes) -> bytes: # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def base58_addr_decode_check(buff: bytes) -> Tuple[bytes, int]: +def base58_addr_decode_check(buff: bytes) -> tuple[bytes, int]: """ Monero block base 58 decoding, returning (decoded, tag) or raising on error. @@ -285,21 +285,21 @@ def base58_addr_decode_check(buff: bytes) -> Tuple[bytes, int]: # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def xmr_random_scalar(r: Optional[Sc25519] = None) -> Sc25519: +def xmr_random_scalar(r: Sc25519 | None = None) -> Sc25519: """ Generates a random scalar """ # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def xmr_fast_hash(r: Optional[bytes], buff: bytes, length: int, offset: int) -> bytes: +def xmr_fast_hash(r: bytes | None, buff: bytes, length: int, offset: int) -> bytes: """ XMR fast hash """ # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def xmr_hash_to_ec(r: Optional[Ge25519], buff: bytes, length: int, offset: +def xmr_hash_to_ec(r: Ge25519 | None, buff: bytes, length: int, offset: int) -> Ge25519: """ XMR hashing to EC point @@ -307,7 +307,7 @@ int) -> Ge25519: # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def xmr_hash_to_scalar(r: Optional[Sc25519], buff: bytes, length: int, +def xmr_hash_to_scalar(r: Sc25519 | None, buff: bytes, length: int, offset: int) -> Sc25519: """ XMR hashing to EC scalar @@ -316,7 +316,7 @@ offset: int) -> Sc25519: # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def xmr_derivation_to_scalar( - r: Optional[Sc25519], p: Ge25519, output_index: int + r: Sc25519 | None, p: Ge25519, output_index: int ) -> Sc25519: """ H_s(derivation || varint(output_index)) @@ -325,7 +325,7 @@ def xmr_derivation_to_scalar( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def xmr_generate_key_derivation( - r: Optional[Ge25519], A: Ge25519, b: Sc25519 + r: Ge25519 | None, A: Ge25519, b: Sc25519 ) -> Ge25519: """ 8*(key2*key1) @@ -334,7 +334,7 @@ def xmr_generate_key_derivation( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def xmr_derive_private_key( - r: Optional[Sc25519], deriv: Ge25519, idx: int, base: Sc25519 + r: Sc25519 | None, deriv: Ge25519, idx: int, base: Sc25519 ) -> Sc25519: """ base + H_s(derivation || varint(output_index)) @@ -343,7 +343,7 @@ def xmr_derive_private_key( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def xmr_derive_public_key( - r: Optional[Ge25519], deriv: Ge25519, idx: int, base: Ge25519 + r: Ge25519 | None, deriv: Ge25519, idx: int, base: Ge25519 ) -> Ge25519: """ H_s(derivation || varint(output_index))G + base @@ -352,7 +352,7 @@ def xmr_derive_public_key( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def xmr_add_keys2( - r: Optional[Ge25519], a: Sc25519, b: Sc25519, B: Ge25519 + r: Ge25519 | None, a: Sc25519, b: Sc25519, B: Ge25519 ) -> Ge25519: """ aG + bB, G is basepoint @@ -361,7 +361,7 @@ def xmr_add_keys2( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def xmr_add_keys2_vartime( - r: Optional[Ge25519], a: Sc25519, b: Sc25519, B: Ge25519 + r: Ge25519 | None, a: Sc25519, b: Sc25519, B: Ge25519 ) -> Ge25519: """ aG + bB, G is basepoint @@ -370,7 +370,7 @@ def xmr_add_keys2_vartime( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def xmr_add_keys3( - r: Optional[Ge25519], a: Sc25519, A: Ge25519, b: Sc25519, B: Ge25519 + r: Ge25519 | None, a: Sc25519, A: Ge25519, b: Sc25519, B: Ge25519 ) -> Ge25519: """ aA + bB @@ -379,7 +379,7 @@ def xmr_add_keys3( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def xmr_add_keys3_vartime( - r: Optional[Ge25519], a: Sc25519, A: Ge25519, b: Sc25519, B: Ge25519 + r: Ge25519 | None, a: Sc25519, A: Ge25519, b: Sc25519, B: Ge25519 ) -> Ge25519: """ aA + bB @@ -388,7 +388,7 @@ def xmr_add_keys3_vartime( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h def xmr_get_subaddress_secret_key( - r: Optional[Sc25519], major: int, minor: int, m: Sc25519 + r: Sc25519 | None, major: int, minor: int, m: Sc25519 ) -> Sc25519: """ Hs(SubAddr || a || index_major || index_minor) @@ -396,7 +396,7 @@ def xmr_get_subaddress_secret_key( # extmod/modtrezorcrypto/modtrezorcrypto-monero.h -def xmr_gen_c(r: Optional[Ge25519], a: Sc25519, amount: int) -> Ge25519: +def xmr_gen_c(r: Ge25519 | None, a: Sc25519, amount: int) -> Ge25519: """ aG + amount * H """ diff --git a/core/mocks/generated/trezorcrypto/secp256k1.pyi b/core/mocks/generated/trezorcrypto/secp256k1.pyi index 1a86c6590..c562b625f 100644 --- a/core/mocks/generated/trezorcrypto/secp256k1.pyi +++ b/core/mocks/generated/trezorcrypto/secp256k1.pyi @@ -22,7 +22,7 @@ def sign( secret_key: bytes, digest: bytes, compressed: bool = True, - canonical: Optional[int] = None, + canonical: int | None = None, ) -> bytes: """ Uses secret key to produce the signature of the digest. diff --git a/core/mocks/generated/trezorcrypto/shamir.pyi b/core/mocks/generated/trezorcrypto/shamir.pyi index 6ab016f8d..883c84354 100644 --- a/core/mocks/generated/trezorcrypto/shamir.pyi +++ b/core/mocks/generated/trezorcrypto/shamir.pyi @@ -2,7 +2,7 @@ from typing import * # extmod/modtrezorcrypto/modtrezorcrypto-shamir.h -def interpolate(shares: List[Tuple[int, bytes]], x: int) -> bytes: +def interpolate(shares: list[tuple[int, bytes]], x: int) -> bytes: """ Returns f(x) given the Shamir shares (x_1, f(x_1)), ... , (x_k, f(x_k)). :param shares: The Shamir shares. diff --git a/core/mocks/generated/trezorio/__init__.pyi b/core/mocks/generated/trezorio/__init__.pyi index e9fa19038..6c7493b12 100644 --- a/core/mocks/generated/trezorio/__init__.pyi +++ b/core/mocks/generated/trezorio/__init__.pyi @@ -69,7 +69,7 @@ class HID: # extmod/modtrezorio/modtrezorio-poll.h -def poll(ifaces: Iterable[int], list_ref: List, timeout_ms: int) -> bool: +def poll(ifaces: Iterable[int], list_ref: list, timeout_ms: int) -> bool: """ Wait until one of `ifaces` is ready to read or write (using masks `list_ref`: @@ -120,7 +120,7 @@ class USB: """ """ - def add(self, iface: Union[HID, VCP, WebUSB]) -> None: + def add(self, iface: HID | VCP | WebUSB) -> None: """ Registers passed interface into the USB stack. """ diff --git a/core/mocks/generated/trezorio/fatfs.pyi b/core/mocks/generated/trezorio/fatfs.pyi index bd4138399..f845af409 100644 --- a/core/mocks/generated/trezorio/fatfs.pyi +++ b/core/mocks/generated/trezorio/fatfs.pyi @@ -51,9 +51,9 @@ class FatFSFile: from types import TracebackType def __exit__( - self, type: Optional[Type[BaseException]], - value: Optional[BaseException], - traceback: Optional[TracebackType], + self, type: type[BaseException] | None, + value: BaseException | None, + traceback: TracebackType | None, ) -> None: """ Close an open file object @@ -69,7 +69,7 @@ class FatFSFile: Read data from the file """ - def write(self, data: Union[bytes, bytearray]) -> int: + def write(self, data: bytes | bytearray) -> int: """ Write data to the file """ @@ -91,12 +91,12 @@ class FatFSFile: # extmod/modtrezorio/modtrezorio-fatfs.h -class FatFSDir(Iterator[Tuple[int, str, str]]): +class FatFSDir(Iterator[tuple[int, str, str]]): """ Class encapsulating directory """ - def __next__(self) -> Tuple[int, str, str]: + def __next__(self) -> tuple[int, str, str]: """ Read an entry in the directory """ @@ -131,7 +131,7 @@ def unlink(path: str) -> None: # extmod/modtrezorio/modtrezorio-fatfs.h -def stat(path: str) -> Tuple[int, str, str]: +def stat(path: str) -> tuple[int, str, str]: """ Get file status """ diff --git a/core/mocks/generated/trezorui.pyi b/core/mocks/generated/trezorui.pyi index e78703ce6..98c1a069e 100644 --- a/core/mocks/generated/trezorui.pyi +++ b/core/mocks/generated/trezorui.pyi @@ -40,8 +40,8 @@ class Display: w: int, h: int, fgcolor: int, - bgcolor: Optional[int] = None, - radius: Optional[int] = None, + bgcolor: int | None = None, + radius: int | None = None, ) -> None: """ Renders a rounded bar at position (x,y = upper left corner) with width w @@ -49,7 +49,7 @@ class Display: are drawn with radius radius. """ - def toif_info(self, image: bytes) -> Tuple[int, int, bool]: + def toif_info(self, image: bytes) -> tuple[int, int, bool]: """ Returns tuple containing TOIF image dimensions: width, height, and whether it is grayscale. @@ -89,8 +89,8 @@ class Display: yoffset: int, fgcolor: int, bgcolor: int, - icon: Optional[bytes] = None, - iconfgcolor: Optional[int] = None, + icon: bytes | None = None, + iconfgcolor: int | None = None, ) -> None: """ Renders a rotating loader graphic. @@ -114,8 +114,8 @@ class Display: font: int, fgcolor: int, bgcolor: int, - text_offset: Optional[int] = None, - text_len: Optional[int] = None, + text_offset: int | None = None, + text_len: int | None = None, ) -> None: """ Renders left-aligned text at position (x,y) where x is left position and @@ -159,8 +159,8 @@ class Display: self, text: str, font: int, - text_offset: Optional[int] = None, - text_len: Optional[int] = None, + text_offset: int | None = None, + text_len: int | None = None, ) -> int: """ Returns a width of text in pixels. Font font is used for rendering. @@ -181,7 +181,7 @@ class Display: Scale determines a zoom factor. """ - def orientation(self, degrees: Optional[int] = None) -> int: + def orientation(self, degrees: int | None = None) -> int: """ Sets display orientation to 0, 90, 180 or 270 degrees. Everything needs to be redrawn again when this function is used. @@ -189,13 +189,13 @@ class Display: value. """ - def backlight(self, val: Optional[int] = None) -> int: + def backlight(self, val: int | None = None) -> int: """ Sets backlight intensity to the value specified in val. Call without the val parameter to just perform the read of the value. """ - def offset(self, xy: Optional[Tuple[int, int]] = None) -> Tuple[int, int]: + def offset(self, xy: tuple[int, int] | None = None) -> tuple[int, int]: """ Sets offset (x, y) for all subsequent drawing calls. Call without the xy parameter to just perform the read of the value. diff --git a/core/mocks/generated/trezorutils.pyi b/core/mocks/generated/trezorutils.pyi index cde11f30f..820508f13 100644 --- a/core/mocks/generated/trezorutils.pyi +++ b/core/mocks/generated/trezorutils.pyi @@ -13,11 +13,11 @@ def consteq(sec: bytes, pub: bytes) -> bool: # extmod/modtrezorutils/modtrezorutils.c def memcpy( - dst: Union[bytearray, memoryview], + dst: bytearray | memoryview, dst_ofs: int, src: bytes, src_ofs: int, - n: Optional[int] = None, + n: int | None = None, ) -> int: """ Copies at most `n` bytes from `src` at offset `src_ofs` to @@ -28,7 +28,7 @@ def memcpy( # extmod/modtrezorutils/modtrezorutils.c -def halt(msg: Optional[str] = None) -> None: +def halt(msg: str | None = None) -> None: """ Halts execution. """ diff --git a/core/src/apps/base.py b/core/src/apps/base.py index 42bd36023..5f85ba15d 100644 --- a/core/src/apps/base.py +++ b/core/src/apps/base.py @@ -14,7 +14,7 @@ from apps.common.request_pin import verify_user_pin if False: import protobuf - from typing import Iterable, NoReturn, Optional, Protocol + from typing import Iterable, NoReturn, Protocol from trezor.messages.Initialize import Initialize from trezor.messages.EndSession import EndSession from trezor.messages.GetFeatures import GetFeatures @@ -235,7 +235,7 @@ async def unlock_device(ctx: wire.GenericContext = wire.DUMMY_CONTEXT) -> None: def get_pinlocked_handler( iface: wire.WireInterface, msg_type: int -) -> Optional[wire.Handler[wire.Msg]]: +) -> wire.Handler[wire.Msg] | None: orig_handler = wire.find_registered_workflow_handler(iface, msg_type) if orig_handler is None: return None diff --git a/core/src/apps/bitcoin/addresses.py b/core/src/apps/bitcoin/addresses.py index 364d7bb7e..166f51675 100644 --- a/core/src/apps/bitcoin/addresses.py +++ b/core/src/apps/bitcoin/addresses.py @@ -12,7 +12,6 @@ from .multisig import multisig_get_pubkeys, multisig_pubkey_index from .scripts import output_script_multisig, output_script_native_p2wpkh_or_p2wsh if False: - from typing import List, Optional from trezor.crypto import bip32 from trezor.messages.TxInputType import EnumTypeInputScriptType @@ -21,7 +20,7 @@ def get_address( script_type: EnumTypeInputScriptType, coin: CoinInfo, node: bip32.HDNode, - multisig: Optional[MultisigRedeemScriptType] = None, + multisig: MultisigRedeemScriptType | None = None, ) -> str: if multisig: # Ensure that our public key is included in the multisig. @@ -74,7 +73,7 @@ def get_address( raise wire.ProcessError("Invalid script type") -def address_multisig_p2sh(pubkeys: List[bytes], m: int, coin: CoinInfo) -> str: +def address_multisig_p2sh(pubkeys: list[bytes], m: int, coin: CoinInfo) -> str: if coin.address_type_p2sh is None: raise wire.ProcessError("Multisig not enabled on this coin") redeem_script = output_script_multisig(pubkeys, m) @@ -82,7 +81,7 @@ def address_multisig_p2sh(pubkeys: List[bytes], m: int, coin: CoinInfo) -> str: return address_p2sh(redeem_script_hash, coin) -def address_multisig_p2wsh_in_p2sh(pubkeys: List[bytes], m: int, coin: CoinInfo) -> str: +def address_multisig_p2wsh_in_p2sh(pubkeys: list[bytes], m: int, coin: CoinInfo) -> str: if coin.address_type_p2sh is None: raise wire.ProcessError("Multisig not enabled on this coin") witness_script = output_script_multisig(pubkeys, m) @@ -90,7 +89,7 @@ def address_multisig_p2wsh_in_p2sh(pubkeys: List[bytes], m: int, coin: CoinInfo) return address_p2wsh_in_p2sh(witness_script_hash, coin) -def address_multisig_p2wsh(pubkeys: List[bytes], m: int, hrp: str) -> str: +def address_multisig_p2wsh(pubkeys: list[bytes], m: int, hrp: str) -> str: if not hrp: raise wire.ProcessError("Multisig not enabled on this coin") witness_script = output_script_multisig(pubkeys, m) diff --git a/core/src/apps/bitcoin/common.py b/core/src/apps/bitcoin/common.py index 834635560..2a989bc22 100644 --- a/core/src/apps/bitcoin/common.py +++ b/core/src/apps/bitcoin/common.py @@ -8,7 +8,6 @@ from trezor.utils import ensure if False: from apps.common.coininfo import CoinInfo - from typing import Dict from trezor.messages.TxInput import EnumTypeInputScriptType, TxInput from trezor.messages.TxOutput import EnumTypeOutputScriptType @@ -35,7 +34,7 @@ MULTISIG_OUTPUT_SCRIPT_TYPES = ( OutputScriptType.PAYTOWITNESS, ) -CHANGE_OUTPUT_TO_INPUT_SCRIPT_TYPES: Dict[ +CHANGE_OUTPUT_TO_INPUT_SCRIPT_TYPES: dict[ EnumTypeOutputScriptType, EnumTypeInputScriptType ] = { OutputScriptType.PAYTOADDRESS: InputScriptType.SPENDADDRESS, diff --git a/core/src/apps/bitcoin/get_address.py b/core/src/apps/bitcoin/get_address.py index 8eceb5cc0..9dfd5b86e 100644 --- a/core/src/apps/bitcoin/get_address.py +++ b/core/src/apps/bitcoin/get_address.py @@ -11,7 +11,6 @@ from .keychain import validate_path_against_script_type, with_keychain from .multisig import multisig_pubkey_index if False: - from typing import List from trezor.messages.GetAddress import GetAddress from trezor.messages.HDNodeType import HDNodeType from trezor import wire @@ -20,8 +19,8 @@ if False: def _get_xpubs( - coin: CoinInfo, xpub_magic: int, pubnodes: List[HDNodeType] -) -> List[str]: + coin: CoinInfo, xpub_magic: int, pubnodes: list[HDNodeType] +) -> list[str]: result = [] for pubnode in pubnodes: node = bip32.HDNode( diff --git a/core/src/apps/bitcoin/get_ownership_proof.py b/core/src/apps/bitcoin/get_ownership_proof.py index 54b72c7b2..06b12451b 100644 --- a/core/src/apps/bitcoin/get_ownership_proof.py +++ b/core/src/apps/bitcoin/get_ownership_proof.py @@ -12,7 +12,6 @@ from .keychain import validate_path_against_script_type, with_keychain from .ownership import generate_proof, get_identifier if False: - from typing import Optional from apps.common.coininfo import CoinInfo from apps.common.keychain import Keychain from .authorization import CoinJoinAuthorization @@ -27,7 +26,7 @@ async def get_ownership_proof( msg: GetOwnershipProof, keychain: Keychain, coin: CoinInfo, - authorization: Optional[CoinJoinAuthorization] = None, + authorization: CoinJoinAuthorization | None = None, ) -> OwnershipProof: if authorization: if not authorization.check_get_ownership_proof(msg): diff --git a/core/src/apps/bitcoin/keychain.py b/core/src/apps/bitcoin/keychain.py index 2b9a1006b..3b454fe95 100644 --- a/core/src/apps/bitcoin/keychain.py +++ b/core/src/apps/bitcoin/keychain.py @@ -8,7 +8,7 @@ from apps.common.paths import PATTERN_BIP44, PathSchema from .common import BITCOIN_NAMES if False: - from typing import Awaitable, Callable, Iterable, List, Optional, Tuple, TypeVar + from typing import Awaitable, Callable, Iterable, TypeVar from typing_extensions import Protocol from trezor.messages.TxInputType import EnumTypeInputScriptType @@ -23,8 +23,8 @@ if False: class MsgWithAddressScriptType(Protocol): # XXX should be Bip32Path but that fails - address_n = ... # type: List[int] - script_type = ... # type: EnumTypeInputScriptType + address_n: list[int] = ... + script_type: EnumTypeInputScriptType = ... MsgIn = TypeVar("MsgIn", bound=MsgWithCoinName) HandlerWithCoinInfo = Callable[..., Awaitable[MsgOut]] @@ -63,9 +63,9 @@ PATTERN_UNCHAINED_DEPRECATED = "m/45'/coin_type'/account'/[0-1000000]/address_in def validate_path_against_script_type( coin: coininfo.CoinInfo, - msg: Optional[MsgWithAddressScriptType] = None, - address_n: Optional[Bip32Path] = None, - script_type: Optional[EnumTypeInputScriptType] = None, + msg: MsgWithAddressScriptType | None = None, + address_n: Bip32Path | None = None, + script_type: EnumTypeInputScriptType | None = None, multisig: bool = False, ) -> bool: patterns = [] @@ -162,7 +162,7 @@ def get_schemas_for_coin(coin: coininfo.CoinInfo) -> Iterable[PathSchema]: return schemas -def get_coin_by_name(coin_name: Optional[str]) -> coininfo.CoinInfo: +def get_coin_by_name(coin_name: str | None) -> coininfo.CoinInfo: if coin_name is None: coin_name = "Bitcoin" @@ -173,8 +173,8 @@ def get_coin_by_name(coin_name: Optional[str]) -> coininfo.CoinInfo: async def get_keychain_for_coin( - ctx: wire.Context, coin_name: Optional[str] -) -> Tuple[Keychain, coininfo.CoinInfo]: + ctx: wire.Context, coin_name: str | None +) -> tuple[Keychain, coininfo.CoinInfo]: coin = get_coin_by_name(coin_name) schemas = get_schemas_for_coin(coin) slip21_namespaces = [[b"SLIP-0019"]] @@ -186,7 +186,7 @@ def with_keychain(func: HandlerWithCoinInfo[MsgOut]) -> Handler[MsgIn, MsgOut]: async def wrapper( ctx: wire.Context, msg: MsgIn, - authorization: Optional[CoinJoinAuthorization] = None, + authorization: CoinJoinAuthorization | None = None, ) -> MsgOut: if authorization: keychain = authorization.keychain diff --git a/core/src/apps/bitcoin/multisig.py b/core/src/apps/bitcoin/multisig.py index 42e711759..59cb80363 100644 --- a/core/src/apps/bitcoin/multisig.py +++ b/core/src/apps/bitcoin/multisig.py @@ -9,9 +9,6 @@ from apps.common import paths from .writers import write_bytes_fixed, write_uint32 -if False: - from typing import List - def multisig_fingerprint(multisig: MultisigRedeemScriptType) -> bytes: if multisig.nodes: @@ -78,7 +75,7 @@ def multisig_get_pubkey(n: HDNodeType, p: paths.Bip32Path) -> bytes: return node.public_key() -def multisig_get_pubkeys(multisig: MultisigRedeemScriptType) -> List[bytes]: +def multisig_get_pubkeys(multisig: MultisigRedeemScriptType) -> list[bytes]: validate_multisig(multisig) if multisig.nodes: return [multisig_get_pubkey(hd, multisig.address_n) for hd in multisig.nodes] diff --git a/core/src/apps/bitcoin/ownership.py b/core/src/apps/bitcoin/ownership.py index 587bbfa22..e056eb017 100644 --- a/core/src/apps/bitcoin/ownership.py +++ b/core/src/apps/bitcoin/ownership.py @@ -15,7 +15,6 @@ from .scripts import read_bip322_signature_proof, write_bip322_signature_proof from .verification import SignatureVerifier if False: - from typing import List, Optional, Tuple from trezor.messages.MultisigRedeemScriptType import MultisigRedeemScriptType from trezor.messages.TxInputType import EnumTypeInputScriptType from apps.common.coininfo import CoinInfo @@ -33,13 +32,13 @@ _OWNERSHIP_ID_KEY_PATH = [b"SLIP-0019", b"Ownership identification key"] def generate_proof( node: bip32.HDNode, script_type: EnumTypeInputScriptType, - multisig: Optional[MultisigRedeemScriptType], + multisig: MultisigRedeemScriptType | None, coin: CoinInfo, user_confirmed: bool, - ownership_ids: List[bytes], + ownership_ids: list[bytes], script_pubkey: bytes, commitment_data: bytes, -) -> Tuple[bytes, bytes]: +) -> tuple[bytes, bytes]: flags = 0 if user_confirmed: flags |= _FLAG_USER_CONFIRMED @@ -67,7 +66,7 @@ def generate_proof( def verify_nonownership( proof: bytes, script_pubkey: bytes, - commitment_data: Optional[bytes], + commitment_data: bytes | None, keychain: Keychain, coin: CoinInfo, ) -> bool: diff --git a/core/src/apps/bitcoin/scripts.py b/core/src/apps/bitcoin/scripts.py index 2bce70120..b9affa545 100644 --- a/core/src/apps/bitcoin/scripts.py +++ b/core/src/apps/bitcoin/scripts.py @@ -22,8 +22,6 @@ from .writers import ( ) if False: - from typing import List, Optional, Tuple - from trezor.messages.MultisigRedeemScriptType import MultisigRedeemScriptType from trezor.messages.TxInput import TxInput from trezor.messages.TxInput import EnumTypeInputScriptType @@ -35,7 +33,7 @@ if False: def input_derive_script( script_type: EnumTypeInputScriptType, - multisig: Optional[MultisigRedeemScriptType], + multisig: MultisigRedeemScriptType | None, coin: CoinInfo, hash_type: int, pubkey: bytes, @@ -115,7 +113,7 @@ def output_derive_script(address: str, coin: CoinInfo) -> bytes: # see https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki#specification # item 5 for details def bip143_derive_script_code( - txi: TxInput, public_keys: List[bytes], threshold: int, coin: CoinInfo + txi: TxInput, public_keys: list[bytes], threshold: int, coin: CoinInfo ) -> bytearray: if len(public_keys) > 1: return output_script_multisig(public_keys, threshold) @@ -149,7 +147,7 @@ def input_script_p2pkh_or_p2sh( return w -def parse_input_script_p2pkh(script_sig: bytes) -> Tuple[bytes, bytes, int]: +def parse_input_script_p2pkh(script_sig: bytes) -> tuple[bytes, bytes, int]: try: r = utils.BufferReader(script_sig) n = read_op_push(r) @@ -276,7 +274,7 @@ def witness_p2wpkh(signature: bytes, pubkey: bytes, hash_type: int) -> bytearray return w -def parse_witness_p2wpkh(witness: bytes) -> Tuple[bytes, bytes, int]: +def parse_witness_p2wpkh(witness: bytes) -> tuple[bytes, bytes, int]: try: r = utils.BufferReader(witness) @@ -346,7 +344,7 @@ def witness_multisig( return w -def parse_witness_multisig(witness: bytes) -> Tuple[bytes, List[Tuple[bytes, int]]]: +def parse_witness_multisig(witness: bytes) -> tuple[bytes, list[tuple[bytes, int]]]: try: r = utils.BufferReader(witness) @@ -421,7 +419,7 @@ def input_script_multisig( def parse_input_script_multisig( script_sig: bytes, -) -> Tuple[bytes, List[Tuple[bytes, int]]]: +) -> tuple[bytes, list[tuple[bytes, int]]]: try: r = utils.BufferReader(script_sig) @@ -446,13 +444,13 @@ def parse_input_script_multisig( return script, signatures -def output_script_multisig(pubkeys: List[bytes], m: int) -> bytearray: +def output_script_multisig(pubkeys: list[bytes], m: int) -> bytearray: w = empty_bytearray(output_script_multisig_length(pubkeys, m)) write_output_script_multisig(w, pubkeys, m) return w -def write_output_script_multisig(w: Writer, pubkeys: List[bytes], m: int) -> None: +def write_output_script_multisig(w: Writer, pubkeys: list[bytes], m: int) -> None: n = len(pubkeys) if n < 1 or n > 15 or m < 1 or m > 15 or m > n: raise wire.DataError("Invalid multisig parameters") @@ -467,11 +465,11 @@ def write_output_script_multisig(w: Writer, pubkeys: List[bytes], m: int) -> Non w.append(0xAE) # OP_CHECKMULTISIG -def output_script_multisig_length(pubkeys: List[bytes], m: int) -> int: +def output_script_multisig_length(pubkeys: list[bytes], m: int) -> int: return 1 + len(pubkeys) * (1 + 33) + 1 + 1 # see output_script_multisig -def parse_output_script_multisig(script: bytes) -> Tuple[List[bytes], int]: +def parse_output_script_multisig(script: bytes) -> tuple[list[bytes], int]: try: r = utils.BufferReader(script) @@ -524,7 +522,7 @@ def output_script_paytoopreturn(data: bytes) -> bytearray: def write_bip322_signature_proof( w: Writer, script_type: EnumTypeInputScriptType, - multisig: Optional[MultisigRedeemScriptType], + multisig: MultisigRedeemScriptType | None, coin: CoinInfo, public_key: bytes, signature: bytes, @@ -549,7 +547,7 @@ def write_bip322_signature_proof( w.extend(witness) -def read_bip322_signature_proof(r: utils.BufferReader) -> Tuple[bytes, bytes]: +def read_bip322_signature_proof(r: utils.BufferReader) -> tuple[bytes, bytes]: script_sig = read_bytes_prefixed(r) witness = r.read() return script_sig, witness diff --git a/core/src/apps/bitcoin/scripts_decred.py b/core/src/apps/bitcoin/scripts_decred.py index a160071d4..17cc79f42 100644 --- a/core/src/apps/bitcoin/scripts_decred.py +++ b/core/src/apps/bitcoin/scripts_decred.py @@ -15,8 +15,6 @@ from .scripts import ( # noqa: F401 from .writers import write_op_push if False: - from typing import Optional - from trezor.messages.MultisigRedeemScriptType import MultisigRedeemScriptType from trezor.messages.TxInput import EnumTypeInputScriptType @@ -25,7 +23,7 @@ if False: def input_derive_script( script_type: EnumTypeInputScriptType, - multisig: Optional[MultisigRedeemScriptType], + multisig: MultisigRedeemScriptType | None, coin: CoinInfo, hash_type: int, pubkey: bytes, diff --git a/core/src/apps/bitcoin/sign_tx/__init__.py b/core/src/apps/bitcoin/sign_tx/__init__.py index 34c98f163..7400e2085 100644 --- a/core/src/apps/bitcoin/sign_tx/__init__.py +++ b/core/src/apps/bitcoin/sign_tx/__init__.py @@ -10,7 +10,7 @@ if not utils.BITCOIN_ONLY: from . import bitcoinlike, decred, zcash if False: - from typing import Protocol, Optional, Type, Union + from typing import Protocol, Union from protobuf import FieldCache @@ -42,7 +42,7 @@ if False: tx: SignTx, keychain: Keychain, coin: CoinInfo, - approver: Optional[approvers.Approver], + approver: approvers.Approver | None, ) -> None: ... @@ -56,14 +56,14 @@ async def sign_tx( msg: SignTx, keychain: Keychain, coin: CoinInfo, - authorization: Optional[CoinJoinAuthorization] = None, + authorization: CoinJoinAuthorization | None = None, ) -> TxRequest: - approver: Optional[approvers.Approver] = None + approver: approvers.Approver | None = None if authorization: approver = approvers.CoinJoinApprover(msg, coin, authorization) if utils.BITCOIN_ONLY or coin.coin_name in BITCOIN_NAMES: - signer_class: Type[SignerClass] = bitcoin.Bitcoin + signer_class: type[SignerClass] = bitcoin.Bitcoin else: if coin.decred: signer_class = decred.Decred @@ -74,7 +74,7 @@ async def sign_tx( signer = signer_class(msg, keychain, coin, approver).signer() - res: Union[TxAckType, bool, None] = None + res: TxAckType | bool | None = None field_cache: FieldCache = {} while True: req = signer.send(res) diff --git a/core/src/apps/bitcoin/sign_tx/approvers.py b/core/src/apps/bitcoin/sign_tx/approvers.py index 07d742175..f8410bef4 100644 --- a/core/src/apps/bitcoin/sign_tx/approvers.py +++ b/core/src/apps/bitcoin/sign_tx/approvers.py @@ -11,7 +11,6 @@ from . import helpers, tx_weight from .tx_info import OriginalTxInfo, TxInfo if False: - from typing import List, Optional from trezor.messages.SignTx import SignTx from trezor.messages.TxInput import TxInput from trezor.messages.TxOutput import TxOutput @@ -77,7 +76,7 @@ class Approver: self, txo: TxOutput, script_pubkey: bytes, - orig_txo: Optional[TxOutput] = None, + orig_txo: TxOutput | None = None, ) -> None: self.weight.add_output(script_pubkey) self.total_out += txo.amount @@ -86,11 +85,11 @@ class Approver: self.orig_total_out += txo.amount async def approve_orig_txids( - self, tx_info: TxInfo, orig_txs: List[OriginalTxInfo] + self, tx_info: TxInfo, orig_txs: list[OriginalTxInfo] ) -> None: raise NotImplementedError - async def approve_tx(self, tx_info: TxInfo, orig_txs: List[OriginalTxInfo]) -> None: + async def approve_tx(self, tx_info: TxInfo, orig_txs: list[OriginalTxInfo]) -> None: raise NotImplementedError @@ -116,7 +115,7 @@ class BasicApprover(Approver): self, txo: TxOutput, script_pubkey: bytes, - orig_txo: Optional[TxOutput] = None, + orig_txo: TxOutput | None = None, ) -> None: await super().add_external_output(txo, script_pubkey, orig_txo) @@ -154,7 +153,7 @@ class BasicApprover(Approver): await helpers.confirm_output(txo, self.coin, self.amount_unit) async def approve_orig_txids( - self, tx_info: TxInfo, orig_txs: List[OriginalTxInfo] + self, tx_info: TxInfo, orig_txs: list[OriginalTxInfo] ) -> None: if not orig_txs: return @@ -173,7 +172,7 @@ class BasicApprover(Approver): for orig in orig_txs: await helpers.confirm_replacement(description, orig.orig_hash) - async def approve_tx(self, tx_info: TxInfo, orig_txs: List[OriginalTxInfo]) -> None: + async def approve_tx(self, tx_info: TxInfo, orig_txs: list[OriginalTxInfo]) -> None: fee = self.total_in - self.total_out # some coins require negative fees for reward TX @@ -301,17 +300,17 @@ class CoinJoinApprover(Approver): self, txo: TxOutput, script_pubkey: bytes, - orig_txo: Optional[TxOutput] = None, + orig_txo: TxOutput | None = None, ) -> None: await super().add_external_output(txo, script_pubkey, orig_txo) self._add_output(txo, script_pubkey) async def approve_orig_txids( - self, tx_info: TxInfo, orig_txs: List[OriginalTxInfo] + self, tx_info: TxInfo, orig_txs: list[OriginalTxInfo] ) -> None: pass - async def approve_tx(self, tx_info: TxInfo, orig_txs: List[OriginalTxInfo]) -> None: + async def approve_tx(self, tx_info: TxInfo, orig_txs: list[OriginalTxInfo]) -> None: # The mining fee of the transaction as a whole. mining_fee = self.total_in - self.total_out diff --git a/core/src/apps/bitcoin/sign_tx/bitcoin.py b/core/src/apps/bitcoin/sign_tx/bitcoin.py index 39d337908..542ccdfa0 100644 --- a/core/src/apps/bitcoin/sign_tx/bitcoin.py +++ b/core/src/apps/bitcoin/sign_tx/bitcoin.py @@ -19,7 +19,6 @@ from .hash143 import Bip143Hash from .tx_info import OriginalTxInfo, TxInfo if False: - from typing import List, Optional, Set, Tuple, Union from trezor.crypto import bip32 from trezor.messages.SignTx import SignTx @@ -76,7 +75,7 @@ class Bitcoin: tx: SignTx, keychain: Keychain, coin: CoinInfo, - approver: Optional[approvers.Approver], + approver: approvers.Approver | None, ) -> None: self.tx_info = TxInfo(self, helpers.sanitize_sign_tx(tx, coin)) self.keychain = keychain @@ -88,10 +87,10 @@ class Bitcoin: self.approver = approvers.BasicApprover(tx, coin) # set of indices of inputs which are segwit - self.segwit: Set[int] = set() + self.segwit: set[int] = set() # set of indices of inputs which are external - self.external: Set[int] = set() + self.external: set[int] = set() # transaction and signature serialization self.serialized_tx = writers.empty_bytearray(_MAX_SERIALIZED_CHUNK_SIZE) @@ -104,12 +103,12 @@ class Bitcoin: # Note: A List is better than a Dict of TXID -> OriginalTxInfo. Dict ordering is # undefined so we would need to convert to a sorted list in several places to ensure # stable device tests. - self.orig_txs = [] # type: List[OriginalTxInfo] + self.orig_txs: list[OriginalTxInfo] = [] # h_inputs is a digest of the inputs streamed for approval in Step 1, which # is used to ensure that the inputs streamed for verification in Step 3 are # the same as those in Step 1. - self.h_inputs: Optional[bytes] = None + self.h_inputs: bytes | None = None progress.init(tx.inputs_count, tx.outputs_count) @@ -152,7 +151,7 @@ class Bitcoin: # STAGE_REQUEST_2_OUTPUT in legacy txo = await helpers.request_tx_output(self.tx_req, i, self.coin) script_pubkey = self.output_derive_script(txo) - orig_txo = None # type: Optional[TxOutput] + orig_txo: TxOutput | None = None if txo.orig_hash: orig_txo = await self.get_original_output(txo, script_pubkey) await self.approve_output(txo, script_pubkey, orig_txo) @@ -378,7 +377,7 @@ class Bitcoin: self, txo: TxOutput, script_pubkey: bytes, - orig_txo: Optional[TxOutput], + orig_txo: TxOutput | None, ) -> None: if self.tx_info.output_is_change(txo): # Output is change and does not need approval. @@ -392,8 +391,8 @@ class Bitcoin: self, i: int, txi: TxInput, - tx_info: Union[TxInfo, OriginalTxInfo], - public_keys: List[bytes], + tx_info: TxInfo | OriginalTxInfo, + public_keys: list[bytes], threshold: int, script_pubkey: bytes, ) -> bytes: @@ -459,7 +458,7 @@ class Bitcoin: script_sig = self.input_derive_script(txi, key_sign_pub, b"") self.write_tx_input(self.serialized_tx, txi, script_sig) - def sign_bip143_input(self, txi: TxInput) -> Tuple[bytes, bytes]: + def sign_bip143_input(self, txi: TxInput) -> tuple[bytes, bytes]: self.tx_info.check_input(txi) node = self.keychain.derive(txi.address_n) @@ -510,9 +509,9 @@ class Bitcoin: async def get_legacy_tx_digest( self, index: int, - tx_info: Union[TxInfo, OriginalTxInfo], - script_pubkey: Optional[bytes] = None, - ) -> Tuple[bytes, TxInput, Optional[bip32.HDNode]]: + tx_info: TxInfo | OriginalTxInfo, + script_pubkey: bytes | None = None, + ) -> tuple[bytes, TxInput, bip32.HDNode | None]: tx_hash = tx_info.orig_hash if isinstance(tx_info, OriginalTxInfo) else None # the transaction digest which gets signed for this input @@ -594,7 +593,7 @@ class Bitcoin: async def get_prevtx_output( self, prev_hash: bytes, prev_index: int - ) -> Tuple[int, bytes]: + ) -> tuple[int, bytes]: amount_out = 0 # output amount # STAGE_REQUEST_3_PREV_META in legacy @@ -659,7 +658,7 @@ class Bitcoin: @staticmethod def write_tx_input( w: writers.Writer, - txi: Union[TxInput, PrevInput], + txi: TxInput | PrevInput, script: bytes, ) -> None: writers.write_tx_input(w, txi, script) @@ -667,7 +666,7 @@ class Bitcoin: @staticmethod def write_tx_output( w: writers.Writer, - txo: Union[TxOutput, PrevOutput], + txo: TxOutput | PrevOutput, script_pubkey: bytes, ) -> None: writers.write_tx_output(w, txo, script_pubkey) @@ -675,7 +674,7 @@ class Bitcoin: def write_tx_header( self, w: writers.Writer, - tx: Union[SignTx, PrevTx], + tx: SignTx | PrevTx, witness_marker: bool, ) -> None: writers.write_uint32(w, tx.version) # nVersion @@ -683,7 +682,7 @@ class Bitcoin: write_bitcoin_varint(w, 0x00) # segwit witness marker write_bitcoin_varint(w, 0x01) # segwit witness flag - def write_tx_footer(self, w: writers.Writer, tx: Union[SignTx, PrevTx]) -> None: + def write_tx_footer(self, w: writers.Writer, tx: SignTx | PrevTx) -> None: writers.write_uint32(w, tx.lock_time) async def write_prev_tx_footer( diff --git a/core/src/apps/bitcoin/sign_tx/bitcoinlike.py b/core/src/apps/bitcoin/sign_tx/bitcoinlike.py index a394ccb5d..1f25a39a5 100644 --- a/core/src/apps/bitcoin/sign_tx/bitcoinlike.py +++ b/core/src/apps/bitcoin/sign_tx/bitcoinlike.py @@ -13,7 +13,6 @@ from . import helpers from .bitcoin import Bitcoin if False: - from typing import List, Optional, Union from .tx_info import OriginalTxInfo, TxInfo _SIGHASH_FORKID = const(0x40) @@ -46,11 +45,11 @@ class Bitcoinlike(Bitcoin): self, i: int, txi: TxInput, - tx_info: Union[TxInfo, OriginalTxInfo], - public_keys: List[bytes], + tx_info: TxInfo | OriginalTxInfo, + public_keys: list[bytes], threshold: int, script_pubkey: bytes, - tx_hash: Optional[bytes] = None, + tx_hash: bytes | None = None, ) -> bytes: if self.coin.force_bip143: return tx_info.hash143.preimage_hash( @@ -75,7 +74,7 @@ class Bitcoinlike(Bitcoin): def write_tx_header( self, w: writers.Writer, - tx: Union[SignTx, PrevTx], + tx: SignTx | PrevTx, witness_marker: bool, ) -> None: writers.write_uint32(w, tx.version) # nVersion diff --git a/core/src/apps/bitcoin/sign_tx/decred.py b/core/src/apps/bitcoin/sign_tx/decred.py index c27d15b12..d13b50813 100644 --- a/core/src/apps/bitcoin/sign_tx/decred.py +++ b/core/src/apps/bitcoin/sign_tx/decred.py @@ -24,8 +24,6 @@ OUTPUT_SCRIPT_NULL_SSTXCHANGE = ( ) if False: - from typing import Optional, Union, List - from trezor.messages.SignTx import SignTx from trezor.messages.TxInput import TxInput from trezor.messages.TxOutput import TxOutput @@ -61,9 +59,9 @@ class DecredHash: def preimage_hash( self, txi: TxInput, - public_keys: List[bytes], + public_keys: list[bytes], threshold: int, - tx: Union[SignTx, PrevTx], + tx: SignTx | PrevTx, coin: CoinInfo, sighash_type: int, ) -> bytes: @@ -76,7 +74,7 @@ class Decred(Bitcoin): tx: SignTx, keychain: Keychain, coin: CoinInfo, - approver: Optional[approvers.Approver], + approver: approvers.Approver | None, ) -> None: ensure(coin.decred) self.h_prefix = HashWriter(blake256()) @@ -127,7 +125,7 @@ class Decred(Bitcoin): self, txo: TxOutput, script_pubkey: bytes, - orig_txo: Optional[TxOutput], + orig_txo: TxOutput | None, ) -> None: await super().approve_output(txo, script_pubkey, orig_txo) self.write_tx_output(self.serialized_tx, txo, script_pubkey) @@ -213,7 +211,7 @@ class Decred(Bitcoin): @staticmethod def write_tx_input( w: writers.Writer, - txi: Union[TxInput, PrevInput], + txi: TxInput | PrevInput, script: bytes, ) -> None: writers.write_bytes_reversed(w, txi.prev_hash, writers.TX_HASH_SIZE) @@ -224,7 +222,7 @@ class Decred(Bitcoin): @staticmethod def write_tx_output( w: writers.Writer, - txo: Union[TxOutput, PrevOutput], + txo: TxOutput | PrevOutput, script_pubkey: bytes, ) -> None: writers.write_uint64(w, txo.amount) @@ -288,7 +286,7 @@ class Decred(Bitcoin): def write_tx_header( self, w: writers.Writer, - tx: Union[SignTx, PrevTx], + tx: SignTx | PrevTx, witness_marker: bool, ) -> None: # The upper 16 bits of the transaction version specify the serialization @@ -300,7 +298,7 @@ class Decred(Bitcoin): writers.write_uint32(w, version) - def write_tx_footer(self, w: writers.Writer, tx: Union[SignTx, PrevTx]) -> None: + def write_tx_footer(self, w: writers.Writer, tx: SignTx | PrevTx) -> None: assert tx.expiry is not None # checked in sanitize_* writers.write_uint32(w, tx.lock_time) writers.write_uint32(w, tx.expiry) diff --git a/core/src/apps/bitcoin/sign_tx/hash143.py b/core/src/apps/bitcoin/sign_tx/hash143.py index 02ca66e54..5ea4338a9 100644 --- a/core/src/apps/bitcoin/sign_tx/hash143.py +++ b/core/src/apps/bitcoin/sign_tx/hash143.py @@ -10,7 +10,7 @@ from apps.common import coininfo from .. import scripts, writers if False: - from typing import List, Union, Protocol + from typing import Protocol class Hash143(Protocol): def add_input(self, txi: TxInput) -> None: @@ -22,9 +22,9 @@ if False: def preimage_hash( self, txi: TxInput, - public_keys: List[bytes], + public_keys: list[bytes], threshold: int, - tx: Union[SignTx, PrevTx], + tx: SignTx | PrevTx, coin: coininfo.CoinInfo, sighash_type: int, ) -> bytes: @@ -51,9 +51,9 @@ class Bip143Hash: def preimage_hash( self, txi: TxInput, - public_keys: List[bytes], + public_keys: list[bytes], threshold: int, - tx: Union[SignTx, PrevTx], + tx: SignTx | PrevTx, coin: coininfo.CoinInfo, sighash_type: int, ) -> bytes: diff --git a/core/src/apps/bitcoin/sign_tx/helpers.py b/core/src/apps/bitcoin/sign_tx/helpers.py index 0dbd1a05e..667975a11 100644 --- a/core/src/apps/bitcoin/sign_tx/helpers.py +++ b/core/src/apps/bitcoin/sign_tx/helpers.py @@ -31,7 +31,7 @@ from ..writers import TX_HASH_SIZE from . import layout if False: - from typing import Any, Awaitable, Optional + from typing import Any, Awaitable from trezor.messages.SignTx import EnumTypeAmountUnit @@ -252,7 +252,7 @@ def confirm_nondefault_locktime(lock_time: int, lock_time_disabled: bool) -> Awa return (yield UiConfirmNonDefaultLocktime(lock_time, lock_time_disabled)) -def request_tx_meta(tx_req: TxRequest, coin: CoinInfo, tx_hash: Optional[bytes] = None) -> Awaitable[PrevTx]: # type: ignore +def request_tx_meta(tx_req: TxRequest, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[PrevTx]: # type: ignore assert tx_req.details is not None tx_req.request_type = TXMETA tx_req.details.tx_hash = tx_hash @@ -262,7 +262,7 @@ def request_tx_meta(tx_req: TxRequest, coin: CoinInfo, tx_hash: Optional[bytes] def request_tx_extra_data( # type: ignore - tx_req: TxRequest, offset: int, size: int, tx_hash: Optional[bytes] = None + tx_req: TxRequest, offset: int, size: int, tx_hash: bytes | None = None ) -> Awaitable[bytearray]: assert tx_req.details is not None tx_req.request_type = TXEXTRADATA @@ -274,7 +274,7 @@ def request_tx_extra_data( # type: ignore return ack.tx.extra_data_chunk -def request_tx_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Optional[bytes] = None) -> Awaitable[TxInput]: # type: ignore +def request_tx_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[TxInput]: # type: ignore assert tx_req.details is not None if tx_hash: tx_req.request_type = TXORIGINPUT @@ -287,7 +287,7 @@ def request_tx_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Optiona return sanitize_tx_input(ack.tx.input, coin) -def request_tx_prev_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Optional[bytes] = None) -> Awaitable[PrevInput]: # type: ignore +def request_tx_prev_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[PrevInput]: # type: ignore assert tx_req.details is not None tx_req.request_type = TXINPUT tx_req.details.request_index = i @@ -297,7 +297,7 @@ def request_tx_prev_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Op return sanitize_tx_prev_input(ack.tx.input, coin) -def request_tx_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Optional[bytes] = None) -> Awaitable[TxOutput]: # type: ignore +def request_tx_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[TxOutput]: # type: ignore assert tx_req.details is not None if tx_hash: tx_req.request_type = TXORIGOUTPUT @@ -310,7 +310,7 @@ def request_tx_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Option return sanitize_tx_output(ack.tx.output, coin) -def request_tx_prev_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Optional[bytes] = None) -> Awaitable[PrevOutput]: # type: ignore +def request_tx_prev_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[PrevOutput]: # type: ignore assert tx_req.details is not None tx_req.request_type = TXOUTPUT tx_req.details.request_index = i diff --git a/core/src/apps/bitcoin/sign_tx/layout.py b/core/src/apps/bitcoin/sign_tx/layout.py index 2d1be1957..fdb3caae7 100644 --- a/core/src/apps/bitcoin/sign_tx/layout.py +++ b/core/src/apps/bitcoin/sign_tx/layout.py @@ -9,8 +9,6 @@ from .. import addresses from . import omni if False: - from typing import Optional - from trezor import wire from trezor.messages.SignTx import EnumTypeAmountUnit from trezor.messages.TxOutput import TxOutput @@ -186,7 +184,7 @@ async def confirm_nondefault_locktime( if lock_time_disabled: title = "Warning" text = "Locktime is set but will\nhave no effect.\n" - param: Optional[str] = None + param: str | None = None elif lock_time < _LOCKTIME_TIMESTAMP_MIN_VALUE: title = "Confirm locktime" text = "Locktime for this\ntransaction is set to\nblockheight:\n{}" diff --git a/core/src/apps/bitcoin/sign_tx/matchcheck.py b/core/src/apps/bitcoin/sign_tx/matchcheck.py index db287258d..128982a79 100644 --- a/core/src/apps/bitcoin/sign_tx/matchcheck.py +++ b/core/src/apps/bitcoin/sign_tx/matchcheck.py @@ -5,7 +5,7 @@ from .. import multisig from ..common import BIP32_WALLET_DEPTH if False: - from typing import Any, Union, Generic, TypeVar + from typing import Any, Generic, TypeVar from trezor.messages.TxInput import TxInput from trezor.messages.TxOutput import TxOutput @@ -43,10 +43,10 @@ class MatchChecker(Generic[T]): UNDEFINED = object() def __init__(self) -> None: - self.attribute: Union[object, T] = self.UNDEFINED + self.attribute: object | T = self.UNDEFINED self.read_only = False # Failsafe to ensure that add_input() is not accidentally called after output_matches(). - def attribute_from_tx(self, txio: Union[TxInput, TxOutput]) -> T: + def attribute_from_tx(self, txio: TxInput | TxOutput) -> T: # Return the attribute from the txio, which is to be used for matching. # If the txio is invalid for matching, then return an object which # evaluates as a boolean False. @@ -85,14 +85,14 @@ class MatchChecker(Generic[T]): class WalletPathChecker(MatchChecker): - def attribute_from_tx(self, txio: Union[TxInput, TxOutput]) -> Any: + def attribute_from_tx(self, txio: TxInput | TxOutput) -> Any: if len(txio.address_n) < BIP32_WALLET_DEPTH: return None return txio.address_n[:-BIP32_WALLET_DEPTH] class MultisigFingerprintChecker(MatchChecker): - def attribute_from_tx(self, txio: Union[TxInput, TxOutput]) -> Any: + def attribute_from_tx(self, txio: TxInput | TxOutput) -> Any: if not txio.multisig: return None return multisig.multisig_fingerprint(txio.multisig) diff --git a/core/src/apps/bitcoin/sign_tx/tx_info.py b/core/src/apps/bitcoin/sign_tx/tx_info.py index 553e018c9..a071c809f 100644 --- a/core/src/apps/bitcoin/sign_tx/tx_info.py +++ b/core/src/apps/bitcoin/sign_tx/tx_info.py @@ -9,7 +9,7 @@ from ..common import BIP32_WALLET_DEPTH, input_is_external from .matchcheck import MultisigFingerprintChecker, WalletPathChecker if False: - from typing import Optional, Protocol, Union + from typing import Protocol from trezor.messages.SignTx import SignTx from trezor.messages.PrevTx import PrevTx from trezor.messages.TxInput import TxInput @@ -32,7 +32,7 @@ if False: def write_tx_header( self, w: writers.Writer, - tx: Union[SignTx, PrevTx], + tx: SignTx | PrevTx, witness_marker: bool, ) -> None: ... @@ -40,7 +40,7 @@ if False: @staticmethod def write_tx_input( w: writers.Writer, - txi: Union[TxInput, PrevInput], + txi: TxInput | PrevInput, script: bytes, ) -> None: ... @@ -48,7 +48,7 @@ if False: @staticmethod def write_tx_output( w: writers.Writer, - txo: Union[TxOutput, PrevOutput], + txo: TxOutput | PrevOutput, script_pubkey: bytes, ) -> None: ... @@ -160,8 +160,8 @@ class OriginalTxInfo(TxInfoBase): writers.write_bitcoin_varint(self.h_tx, tx.inputs_count) # The input which will be used for verification and its index in the original transaction. - self.verification_input = None # type: Optional[TxInput] - self.verification_index = None # type: Optional[int] + self.verification_input: TxInput | None = None + self.verification_index: int | None = None def add_input(self, txi: TxInput) -> None: super().add_input(txi) diff --git a/core/src/apps/bitcoin/sign_tx/zcash.py b/core/src/apps/bitcoin/sign_tx/zcash.py index 6f0767407..e86071b06 100644 --- a/core/src/apps/bitcoin/sign_tx/zcash.py +++ b/core/src/apps/bitcoin/sign_tx/zcash.py @@ -31,7 +31,6 @@ from .bitcoinlike import Bitcoinlike if False: from apps.common import coininfo - from typing import List, Optional, Union from .hash143 import Hash143 from .tx_info import OriginalTxInfo, TxInfo from ..writers import Writer @@ -56,9 +55,9 @@ class Zip243Hash: def preimage_hash( self, txi: TxInput, - public_keys: List[bytes], + public_keys: list[bytes], threshold: int, - tx: Union[SignTx, PrevTx], + tx: SignTx | PrevTx, coin: coininfo.CoinInfo, sighash_type: int, ) -> bytes: @@ -145,11 +144,11 @@ class Zcashlike(Bitcoinlike): self, i: int, txi: TxInput, - tx_info: Union[TxInfo, OriginalTxInfo], - public_keys: List[bytes], + tx_info: TxInfo | OriginalTxInfo, + public_keys: list[bytes], threshold: int, script_pubkey: bytes, - tx_hash: Optional[bytes] = None, + tx_hash: bytes | None = None, ) -> bytes: return tx_info.hash143.preimage_hash( txi, @@ -161,7 +160,7 @@ class Zcashlike(Bitcoinlike): ) def write_tx_header( - self, w: Writer, tx: Union[SignTx, PrevTx], witness_marker: bool + self, w: Writer, tx: SignTx | PrevTx, witness_marker: bool ) -> None: if tx.version < 3: # pre-overwinter @@ -173,7 +172,7 @@ class Zcashlike(Bitcoinlike): write_uint32(w, tx.version | OVERWINTERED) write_uint32(w, tx.version_group_id) # nVersionGroupId - def write_tx_footer(self, w: Writer, tx: Union[SignTx, PrevTx]) -> None: + def write_tx_footer(self, w: Writer, tx: SignTx | PrevTx) -> None: assert tx.expiry is not None # checked in sanitize_* write_uint32(w, tx.lock_time) if tx.version >= 3: @@ -181,7 +180,7 @@ class Zcashlike(Bitcoinlike): def derive_script_code( - txi: TxInput, public_keys: List[bytes], threshold: int, coin: CoinInfo + txi: TxInput, public_keys: list[bytes], threshold: int, coin: CoinInfo ) -> bytearray: if len(public_keys) > 1: return output_script_multisig(public_keys, threshold) diff --git a/core/src/apps/bitcoin/verification.py b/core/src/apps/bitcoin/verification.py index d0205166c..856e79077 100644 --- a/core/src/apps/bitcoin/verification.py +++ b/core/src/apps/bitcoin/verification.py @@ -18,7 +18,6 @@ from .scripts import ( ) if False: - from typing import List, Optional, Tuple from apps.common.coininfo import CoinInfo @@ -26,13 +25,13 @@ class SignatureVerifier: def __init__( self, script_pubkey: bytes, - script_sig: Optional[bytes], - witness: Optional[bytes], + script_sig: bytes | None, + witness: bytes | None, coin: CoinInfo, ): self.threshold = 1 - self.public_keys: List[bytes] = [] - self.signatures: List[Tuple[bytes, int]] = [] + self.public_keys: list[bytes] = [] + self.signatures: list[tuple[bytes, int]] = [] if not script_sig: if not witness: diff --git a/core/src/apps/bitcoin/writers.py b/core/src/apps/bitcoin/writers.py index cb681efd1..8eadfceb1 100644 --- a/core/src/apps/bitcoin/writers.py +++ b/core/src/apps/bitcoin/writers.py @@ -16,8 +16,6 @@ from apps.common.writers import ( # noqa: F401 ) if False: - from typing import Union - from trezor.messages.TxInput import TxInput from trezor.messages.TxOutput import TxOutput from trezor.messages.PrevInput import PrevInput @@ -38,7 +36,7 @@ def write_bytes_prefixed(w: Writer, b: bytes) -> None: write_bytes_unchecked(w, b) -def write_tx_input(w: Writer, i: Union[TxInput, PrevInput], script: bytes) -> None: +def write_tx_input(w: Writer, i: TxInput | PrevInput, script: bytes) -> None: write_bytes_reversed(w, i.prev_hash, TX_HASH_SIZE) write_uint32(w, i.prev_index) write_bytes_prefixed(w, script) @@ -56,9 +54,7 @@ def write_tx_input_check(w: Writer, i: TxInput) -> None: write_uint64(w, i.amount or 0) -def write_tx_output( - w: Writer, o: Union[TxOutput, PrevOutput], script_pubkey: bytes -) -> None: +def write_tx_output(w: Writer, o: TxOutput | PrevOutput, script_pubkey: bytes) -> None: write_uint64(w, o.amount) write_bytes_prefixed(w, script_pubkey) diff --git a/core/src/apps/cardano/address.py b/core/src/apps/cardano/address.py index 5cfc9cd90..8eae722a6 100644 --- a/core/src/apps/cardano/address.py +++ b/core/src/apps/cardano/address.py @@ -11,7 +11,6 @@ from .helpers.utils import variable_length_encode from .seed import is_byron_path, is_shelley_path if False: - from typing import List, Optional from trezor.messages.CardanoBlockchainPointerType import ( CardanoBlockchainPointerType, ) @@ -146,7 +145,7 @@ def _get_address_network_id(address: bytes) -> int: return address[0] & 0x0F -def get_public_key_hash(keychain: seed.Keychain, path: List[int]) -> bytes: +def get_public_key_hash(keychain: seed.Keychain, path: list[int]) -> bytes: node = keychain.derive(path) public_key = remove_ed25519_prefix(node.public_key()) return hashlib.blake2b(data=public_key, outlen=28).digest() @@ -195,7 +194,7 @@ def derive_address_bytes( def _derive_byron_address( - keychain: seed.Keychain, path: List[int], protocol_magic: int + keychain: seed.Keychain, path: list[int], protocol_magic: int ) -> bytes: if not is_byron_path(path): raise wire.DataError("Invalid path for byron address!") @@ -248,9 +247,9 @@ def _create_address_header( def _derive_base_address( keychain: seed.Keychain, - path: List[int], - staking_path: List[int], - staking_key_hash: Optional[bytes], + path: list[int], + staking_path: list[int], + staking_key_hash: bytes | None, network_id: int, ) -> bytes: header = _create_address_header(CardanoAddressType.BASE, network_id) @@ -265,8 +264,8 @@ def _derive_base_address( def _validate_base_address_staking_info( - staking_path: List[int], - staking_key_hash: Optional[bytes], + staking_path: list[int], + staking_key_hash: bytes | None, ) -> None: if (staking_key_hash is None) == (not staking_path): raise wire.DataError( @@ -279,7 +278,7 @@ def _validate_base_address_staking_info( def _derive_pointer_address( keychain: seed.Keychain, - path: List[int], + path: list[int], pointer: CardanoBlockchainPointerType, network_id: int, ) -> bytes: @@ -300,7 +299,7 @@ def _encode_certificate_pointer(pointer: CardanoBlockchainPointerType) -> bytes: def _derive_enterprise_address( keychain: seed.Keychain, - path: List[int], + path: list[int], network_id: int, ) -> bytes: header = _create_address_header(CardanoAddressType.ENTERPRISE, network_id) @@ -311,7 +310,7 @@ def _derive_enterprise_address( def _derive_reward_address( keychain: seed.Keychain, - path: List[int], + path: list[int], network_id: int, ) -> bytes: if not SCHEMA_STAKING_ANY_ACCOUNT.match(path): diff --git a/core/src/apps/cardano/certificates.py b/core/src/apps/cardano/certificates.py index 8f40805c8..212c96db7 100644 --- a/core/src/apps/cardano/certificates.py +++ b/core/src/apps/cardano/certificates.py @@ -11,8 +11,6 @@ from .helpers import INVALID_CERTIFICATE, LOVELACE_MAX_SUPPLY from .helpers.paths import SCHEMA_STAKING_ANY_ACCOUNT if False: - from typing import List, Optional - from trezor.messages.CardanoTxCertificateType import CardanoTxCertificateType from trezor.messages.CardanoPoolParametersType import CardanoPoolParametersType from trezor.messages.CardanoPoolRelayParametersType import ( @@ -135,7 +133,7 @@ def _validate_pool_parameters( _validate_pool_metadata(pool_parameters.metadata) -def _validate_pool_owners(owners: List[CardanoPoolOwnerType]) -> None: +def _validate_pool_owners(owners: list[CardanoPoolOwnerType]) -> None: owners_as_path_count = 0 for owner in owners: assert_certificate_cond( @@ -190,8 +188,8 @@ def _validate_pool_metadata(pool_metadata: CardanoPoolMetadataType) -> None: def _cborize_pool_owners( - keychain: seed.Keychain, pool_owners: List[CardanoPoolOwnerType] -) -> List[bytes]: + keychain: seed.Keychain, pool_owners: list[CardanoPoolOwnerType] +) -> list[bytes]: result = [] for pool_owner in pool_owners: @@ -205,7 +203,7 @@ def _cborize_pool_owners( return result -def _cborize_ipv6_address(ipv6_address: Optional[bytes]) -> Optional[bytes]: +def _cborize_ipv6_address(ipv6_address: bytes | None) -> bytes | None: if ipv6_address is None: return None @@ -220,9 +218,9 @@ def _cborize_ipv6_address(ipv6_address: Optional[bytes]) -> Optional[bytes]: def _cborize_pool_relays( - pool_relays: List[CardanoPoolRelayParametersType], -) -> List[CborSequence]: - result: List[CborSequence] = [] + pool_relays: list[CardanoPoolRelayParametersType], +) -> list[CborSequence]: + result: list[CborSequence] = [] for pool_relay in pool_relays: if pool_relay.type == CardanoPoolRelayType.SINGLE_HOST_IP: @@ -254,8 +252,8 @@ def _cborize_pool_relays( def _cborize_pool_metadata( - pool_metadata: Optional[CardanoPoolMetadataType], -) -> Optional[CborSequence]: + pool_metadata: CardanoPoolMetadataType | None, +) -> CborSequence | None: if not pool_metadata: return None diff --git a/core/src/apps/cardano/get_public_key.py b/core/src/apps/cardano/get_public_key.py index 42ba051ce..0d6434458 100644 --- a/core/src/apps/cardano/get_public_key.py +++ b/core/src/apps/cardano/get_public_key.py @@ -12,7 +12,6 @@ from . import seed from .helpers.paths import SCHEMA_PUBKEY if False: - from typing import List from trezor.messages.CardanoGetPublicKey import CardanoGetPublicKey @@ -41,7 +40,7 @@ async def get_public_key( def _get_public_key( - keychain: seed.Keychain, derivation_path: List[int] + keychain: seed.Keychain, derivation_path: list[int] ) -> CardanoPublicKey: node = keychain.derive(derivation_path) diff --git a/core/src/apps/cardano/helpers/staking_use_cases.py b/core/src/apps/cardano/helpers/staking_use_cases.py index e4f8ec2bc..66774df4c 100644 --- a/core/src/apps/cardano/helpers/staking_use_cases.py +++ b/core/src/apps/cardano/helpers/staking_use_cases.py @@ -5,7 +5,6 @@ from ..seed import is_shelley_path from .utils import to_account_path if False: - from typing import List from trezor.messages.CardanoAddressParametersType import ( CardanoAddressParametersType, ) @@ -53,5 +52,5 @@ def get(keychain: Keychain, address_parameters: CardanoAddressParametersType) -> return NO_STAKING -def _path_to_staking_path(path: List[int]) -> List[int]: +def _path_to_staking_path(path: list[int]) -> list[int]: return to_account_path(path) + [2, 0] diff --git a/core/src/apps/cardano/helpers/utils.py b/core/src/apps/cardano/helpers/utils.py index b00ae3b1d..cd9da4e71 100644 --- a/core/src/apps/cardano/helpers/utils.py +++ b/core/src/apps/cardano/helpers/utils.py @@ -4,9 +4,6 @@ from apps.cardano.helpers.paths import ACCOUNT_PATH_INDEX, unharden from . import bech32 -if False: - from typing import List, Optional - def variable_length_encode(number: int) -> bytes: """ @@ -30,18 +27,18 @@ def variable_length_encode(number: int) -> bytes: return bytes(encoded) -def to_account_path(path: List[int]) -> List[int]: +def to_account_path(path: list[int]) -> list[int]: return path[: ACCOUNT_PATH_INDEX + 1] -def format_account_number(path: List[int]) -> str: +def format_account_number(path: list[int]) -> str: if len(path) <= ACCOUNT_PATH_INDEX: raise ValueError("Path is too short.") return "#%d" % (unharden(path[ACCOUNT_PATH_INDEX]) + 1) -def format_optional_int(number: Optional[int]) -> str: +def format_optional_int(number: int | None) -> str: if number is None: return "n/a" diff --git a/core/src/apps/cardano/layout.py b/core/src/apps/cardano/layout.py index dba1a698b..6106244b3 100644 --- a/core/src/apps/cardano/layout.py +++ b/core/src/apps/cardano/layout.py @@ -32,7 +32,6 @@ from .helpers.utils import ( ) if False: - from typing import List, Optional from trezor import wire from trezor.messages.CardanoBlockchainPointerType import ( CardanoBlockchainPointerType, @@ -76,7 +75,7 @@ def is_printable_ascii_bytestring(bytestr: bytes) -> bool: async def confirm_sending( ctx: wire.Context, ada_amount: int, - token_bundle: List[CardanoAssetGroupType], + token_bundle: list[CardanoAssetGroupType], to: str, ) -> None: await confirm_sending_token_bundle(ctx, token_bundle) @@ -96,7 +95,7 @@ async def confirm_sending( async def confirm_sending_token_bundle( - ctx: wire.Context, token_bundle: List[CardanoAssetGroupType] + ctx: wire.Context, token_bundle: list[CardanoAssetGroupType] ) -> None: for token_group in token_bundle: for token in token_group.tokens: @@ -125,7 +124,7 @@ async def show_warning_tx_output_contains_tokens(ctx: wire.Context) -> None: await require_confirm(ctx, page1) -async def show_warning_path(ctx: wire.Context, path: List[int], title: str) -> None: +async def show_warning_path(ctx: wire.Context, path: list[int], title: str) -> None: page1 = Text("Confirm path", ui.ICON_WRONG, ui.RED) page1.normal(title) page1.bold(address_n_to_str(path)) @@ -171,7 +170,7 @@ async def show_warning_tx_pointer_address( async def show_warning_tx_different_staking_account( ctx: wire.Context, - staking_account_path: List[int], + staking_account_path: list[int], amount: int, ) -> None: page1 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN) @@ -214,12 +213,12 @@ async def confirm_transaction( amount: int, fee: int, protocol_magic: int, - ttl: Optional[int], - validity_interval_start: Optional[int], + ttl: int | None, + validity_interval_start: int | None, has_metadata: bool, is_network_id_verifiable: bool, ) -> None: - pages: List[ui.Component] = [] + pages: list[ui.Component] = [] page1 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN) page1.normal("Transaction amount:") @@ -252,7 +251,7 @@ async def confirm_certificate( # in this call assert certificate.type != CardanoCertificateType.STAKE_POOL_REGISTRATION - pages: List[ui.Component] = [] + pages: list[ui.Component] = [] page1 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN) page1.normal("Confirm:") @@ -301,10 +300,10 @@ async def confirm_stake_pool_parameters( async def confirm_stake_pool_owners( ctx: wire.Context, keychain: seed.Keychain, - owners: List[CardanoPoolOwnerType], + owners: list[CardanoPoolOwnerType], network_id: int, ) -> None: - pages: List[ui.Component] = [] + pages: list[ui.Component] = [] for index, owner in enumerate(owners, 1): page = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN) page.normal("Pool owner #%d:" % (index)) @@ -334,7 +333,7 @@ async def confirm_stake_pool_owners( async def confirm_stake_pool_metadata( ctx: wire.Context, - metadata: Optional[CardanoPoolMetadataType], + metadata: CardanoPoolMetadataType | None, ) -> None: if metadata is None: @@ -359,8 +358,8 @@ async def confirm_stake_pool_metadata( async def confirm_transaction_network_ttl( ctx: wire.Context, protocol_magic: int, - ttl: Optional[int], - validity_interval_start: Optional[int], + ttl: int | None, + validity_interval_start: int | None, ) -> None: page1 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN) page1.normal("Network:") @@ -398,8 +397,8 @@ async def show_address( ctx: wire.Context, address: str, address_type: EnumTypeCardanoAddressType, - path: List[int], - network: Optional[str] = None, + path: list[int], + network: str | None = None, ) -> bool: """ Custom show_address function is needed because cardano addresses don't @@ -428,7 +427,7 @@ async def show_address( for address_line in address_lines[: lines_per_page - lines_used_on_first_page]: page1.bold(address_line) - pages: List[ui.Component] = [] + pages: list[ui.Component] = [] pages.append(page1) # append remaining pages containing the rest of the address pages.extend( @@ -451,9 +450,9 @@ async def show_address( def _paginate_lines( - lines: List[str], offset: int, desc: str, icon: str, lines_per_page: int = 4 -) -> List[ui.Component]: - pages: List[ui.Component] = [] + lines: list[str], offset: int, desc: str, icon: str, lines_per_page: int = 4 +) -> list[ui.Component]: + pages: list[ui.Component] = [] if len(lines) > offset: to_pages = list(chunks(lines[offset:], lines_per_page)) for page in to_pages: @@ -467,9 +466,9 @@ def _paginate_lines( async def show_warning_address_foreign_staking_key( ctx: wire.Context, - account_path: List[int], - staking_account_path: List[int], - staking_key_hash: Optional[bytes], + account_path: list[int], + staking_account_path: list[int], + staking_key_hash: bytes | None, ) -> None: page1 = Text("Warning", ui.ICON_WRONG, ui.RED) page1.normal("Stake rights associated") diff --git a/core/src/apps/cardano/sign_tx.py b/core/src/apps/cardano/sign_tx.py index f5c948fb6..ba58ee0e0 100644 --- a/core/src/apps/cardano/sign_tx.py +++ b/core/src/apps/cardano/sign_tx.py @@ -66,7 +66,7 @@ from .layout import ( from .seed import is_byron_path, is_shelley_path if False: - from typing import Any, Dict, List, Optional, Tuple, Union + from typing import Any, Optional, Union from trezor.messages.CardanoSignTx import CardanoSignTx from trezor.messages.CardanoTxCertificateType import CardanoTxCertificateType @@ -78,9 +78,9 @@ if False: from apps.common.cbor import CborSequence from apps.common.paths import PathSchema - CborizedTokenBundle = Dict[bytes, Dict[bytes, int]] - CborizedTxOutput = Tuple[bytes, Union[int, Tuple[int, CborizedTokenBundle]]] - CborizedSignedTx = Tuple[Dict, Dict, Optional[cbor.Raw]] + CborizedTokenBundle = dict[bytes, dict[bytes, int]] + CborizedTxOutput = tuple[bytes, Union[int, tuple[int, CborizedTokenBundle]]] + CborizedSignedTx = tuple[dict, dict, Optional[cbor.Raw]] TxHash = bytes METADATA_HASH_SIZE = 32 @@ -123,7 +123,7 @@ async def sign_tx( async def _sign_ordinary_tx( ctx: wire.Context, msg: CardanoSignTx, keychain: seed.Keychain -) -> Tuple[CborizedSignedTx, TxHash]: +) -> tuple[CborizedSignedTx, TxHash]: for i in msg.inputs: await validate_path( ctx, keychain, i.address_n, SCHEMA_ADDRESS.match(i.address_n) @@ -142,7 +142,7 @@ async def _sign_ordinary_tx( async def _sign_stake_pool_registration_tx( ctx: wire.Context, msg: CardanoSignTx, keychain: seed.Keychain -) -> Tuple[CborizedSignedTx, TxHash]: +) -> tuple[CborizedSignedTx, TxHash]: """ We have a separate tx signing flow for stake pool registration because it's a transaction where the witnessable entries (i.e. inputs, withdrawals, etc.) @@ -200,7 +200,7 @@ def _validate_stake_pool_registration_tx_structure(msg: CardanoSignTx) -> None: def _validate_outputs( keychain: seed.Keychain, - outputs: List[CardanoTxOutputType], + outputs: list[CardanoTxOutputType], protocol_magic: int, network_id: int, ) -> None: @@ -225,7 +225,7 @@ def _validate_outputs( raise wire.ProcessError("Total transaction amount is out of range!") -def _validate_token_bundle(token_bundle: List[CardanoAssetGroupType]) -> None: +def _validate_token_bundle(token_bundle: list[CardanoAssetGroupType]) -> None: seen_policy_ids = set() for token_group in token_bundle: policy_id = bytes(token_group.policy_id) @@ -253,19 +253,19 @@ def _validate_token_bundle(token_bundle: List[CardanoAssetGroupType]) -> None: seen_asset_name_bytes.add(asset_name_bytes) -def _ensure_no_signing_inputs(inputs: List[CardanoTxInputType]) -> None: +def _ensure_no_signing_inputs(inputs: list[CardanoTxInputType]) -> None: if any(i.address_n for i in inputs): raise INVALID_STAKEPOOL_REGISTRATION_TX_INPUTS def _validate_certificates( - certificates: List[CardanoTxCertificateType], protocol_magic: int, network_id: int + certificates: list[CardanoTxCertificateType], protocol_magic: int, network_id: int ) -> None: for certificate in certificates: validate_certificate(certificate, protocol_magic, network_id) -def _validate_withdrawals(withdrawals: List[CardanoTxWithdrawalType]) -> None: +def _validate_withdrawals(withdrawals: list[CardanoTxWithdrawalType]) -> None: for withdrawal in withdrawals: if not SCHEMA_STAKING_ANY_ACCOUNT.match(withdrawal.path): raise INVALID_WITHDRAWAL @@ -274,7 +274,7 @@ def _validate_withdrawals(withdrawals: List[CardanoTxWithdrawalType]) -> None: raise INVALID_WITHDRAWAL -def _validate_metadata(metadata: Optional[bytes]) -> None: +def _validate_metadata(metadata: bytes | None) -> None: if not metadata: return @@ -293,7 +293,7 @@ def _validate_metadata(metadata: Optional[bytes]) -> None: def _cborize_signed_tx( keychain: seed.Keychain, msg: CardanoSignTx -) -> Tuple[CborizedSignedTx, TxHash]: +) -> tuple[CborizedSignedTx, TxHash]: tx_body = _cborize_tx_body(keychain, msg) tx_hash = _hash_tx_body(tx_body) @@ -313,7 +313,7 @@ def _cborize_signed_tx( return (tx_body, witnesses, metadata), tx_hash -def _cborize_tx_body(keychain: seed.Keychain, msg: CardanoSignTx) -> Dict: +def _cborize_tx_body(keychain: seed.Keychain, msg: CardanoSignTx) -> dict: inputs_for_cbor = _cborize_inputs(msg.inputs) outputs_for_cbor = _cborize_outputs( keychain, msg.outputs, msg.protocol_magic, msg.network_id @@ -349,16 +349,16 @@ def _cborize_tx_body(keychain: seed.Keychain, msg: CardanoSignTx) -> Dict: return tx_body -def _cborize_inputs(inputs: List[CardanoTxInputType]) -> List[Tuple[bytes, int]]: +def _cborize_inputs(inputs: list[CardanoTxInputType]) -> list[tuple[bytes, int]]: return [(tx_input.prev_hash, tx_input.prev_index) for tx_input in inputs] def _cborize_outputs( keychain: seed.Keychain, - outputs: List[CardanoTxOutputType], + outputs: list[CardanoTxOutputType], protocol_magic: int, network_id: int, -) -> List[CborizedTxOutput]: +) -> list[CborizedTxOutput]: return [ _cborize_output(keychain, output, protocol_magic, network_id) for output in outputs @@ -387,7 +387,7 @@ def _cborize_output( def _cborize_token_bundle( - token_bundle: List[CardanoAssetGroupType], + token_bundle: list[CardanoAssetGroupType], ) -> CborizedTokenBundle: result: CborizedTokenBundle = {} @@ -404,17 +404,17 @@ def _cborize_token_bundle( def _cborize_certificates( keychain: seed.Keychain, - certificates: List[CardanoTxCertificateType], -) -> List[CborSequence]: + certificates: list[CardanoTxCertificateType], +) -> list[CborSequence]: return [cborize_certificate(keychain, cert) for cert in certificates] def _cborize_withdrawals( keychain: seed.Keychain, - withdrawals: List[CardanoTxWithdrawalType], + withdrawals: list[CardanoTxWithdrawalType], protocol_magic: int, network_id: int, -) -> Dict[bytes, int]: +) -> dict[bytes, int]: result = {} for withdrawal in withdrawals: reward_address = derive_address_bytes( @@ -436,7 +436,7 @@ def _hash_metadata(metadata: bytes) -> bytes: return hashlib.blake2b(data=metadata, outlen=METADATA_HASH_SIZE).digest() -def _hash_tx_body(tx_body: Dict) -> bytes: +def _hash_tx_body(tx_body: dict) -> bytes: tx_body_cbor_chunks = cbor.encode_streamed(tx_body) hashfn = hashlib.blake2b(outlen=32) @@ -448,12 +448,12 @@ def _hash_tx_body(tx_body: Dict) -> bytes: def _cborize_witnesses( keychain: seed.Keychain, - inputs: List[CardanoTxInputType], - certificates: List[CardanoTxCertificateType], - withdrawals: List[CardanoTxWithdrawalType], + inputs: list[CardanoTxInputType], + certificates: list[CardanoTxCertificateType], + withdrawals: list[CardanoTxWithdrawalType], tx_body_hash: bytes, protocol_magic: int, -) -> Dict: +) -> dict: shelley_witnesses = _cborize_shelley_witnesses( keychain, inputs, certificates, withdrawals, tx_body_hash ) @@ -463,7 +463,7 @@ def _cborize_witnesses( # use key 0 for shelley witnesses and key 2 for byron witnesses # according to the spec in shelley.cddl in cardano-ledger-specs - witnesses: Dict[Any, Any] = {} + witnesses: dict[Any, Any] = {} if shelley_witnesses: witnesses[0] = shelley_witnesses if byron_witnesses: @@ -474,11 +474,11 @@ def _cborize_witnesses( def _cborize_shelley_witnesses( keychain: seed.Keychain, - inputs: List[CardanoTxInputType], - certificates: List[CardanoTxCertificateType], - withdrawals: List[CardanoTxWithdrawalType], + inputs: list[CardanoTxInputType], + certificates: list[CardanoTxCertificateType], + withdrawals: list[CardanoTxWithdrawalType], tx_body_hash: bytes, -) -> List[Tuple[bytes, bytes]]: +) -> list[tuple[bytes, bytes]]: shelley_witnesses = [] # include only one witness for each path @@ -511,8 +511,8 @@ def _cborize_shelley_witnesses( def _cborize_shelley_witness( - keychain: seed.Keychain, tx_body_hash: bytes, path: List[int] -) -> Tuple[bytes, bytes]: + keychain: seed.Keychain, tx_body_hash: bytes, path: list[int] +) -> tuple[bytes, bytes]: node = keychain.derive(path) signature = ed25519.sign_ext( @@ -525,10 +525,10 @@ def _cborize_shelley_witness( def _cborize_byron_witnesses( keychain: seed.Keychain, - inputs: List[CardanoTxInputType], + inputs: list[CardanoTxInputType], tx_body_hash: bytes, protocol_magic: int, -) -> List[Tuple[bytes, bytes, bytes, bytes]]: +) -> list[tuple[bytes, bytes, bytes, bytes]]: byron_witnesses = [] # include only one witness for each path @@ -704,7 +704,7 @@ async def _show_change_output_staking_warnings( # addresses from the same account as inputs should be hidden -def _should_hide_output(output: List[int], inputs: List[CardanoTxInputType]) -> bool: +def _should_hide_output(output: list[int], inputs: list[CardanoTxInputType]) -> bool: for tx_input in inputs: inp = tx_input.address_n if ( @@ -732,7 +732,7 @@ def _is_network_id_verifiable(msg: CardanoSignTx) -> bool: async def _fail_or_warn_if_invalid_path( - ctx: wire.Context, schema: PathSchema, path: List[int], path_name: str + ctx: wire.Context, schema: PathSchema, path: list[int], path_name: str ) -> None: if not schema.match(path): if safety_checks.is_strict(): diff --git a/core/src/apps/common/cbor.py b/core/src/apps/common/cbor.py index d45a88832..c04a169f1 100644 --- a/core/src/apps/common/cbor.py +++ b/core/src/apps/common/cbor.py @@ -10,10 +10,10 @@ from trezor import log, utils from . import readers, writers if False: - from typing import Any, List, Tuple, Union, Iterator + from typing import Any, Union, Iterator, Tuple Value = Any - CborSequence = Union[List[Value], Tuple[Value, ...]] + CborSequence = Union[list[Value], Tuple[Value, ...]] _CBOR_TYPE_MASK = const(0xE0) _CBOR_INFO_BITS = const(0x1F) @@ -214,7 +214,7 @@ class Raw: class IndefiniteLengthArray: - def __init__(self, array: List[Value]) -> None: + def __init__(self, array: list[Value]) -> None: self.array = array def __eq__(self, other: object) -> bool: diff --git a/core/src/apps/common/coininfo.py b/core/src/apps/common/coininfo.py index 0d20606b9..bf32af03e 100644 --- a/core/src/apps/common/coininfo.py +++ b/core/src/apps/common/coininfo.py @@ -5,7 +5,7 @@ from trezor.crypto.base58 import blake256d_32, groestl512d_32, keccak_32, sha256 from trezor.crypto.scripts import blake256_ripemd160_digest, sha256_ripemd160_digest if False: - from typing import Any, Dict, Optional + from typing import Any # flake8: noqa @@ -21,15 +21,15 @@ class CoinInfo: maxfee_kb: int, signed_message_header: str, xpub_magic: int, - xpub_magic_segwit_p2sh: Optional[int], - xpub_magic_segwit_native: Optional[int], - xpub_magic_multisig_segwit_p2sh: Optional[int], - xpub_magic_multisig_segwit_native: Optional[int], - bech32_prefix: Optional[str], - cashaddr_prefix: Optional[str], + xpub_magic_segwit_p2sh: int | None, + xpub_magic_segwit_native: int | None, + xpub_magic_multisig_segwit_p2sh: int | None, + xpub_magic_multisig_segwit_native: int | None, + bech32_prefix: str | None, + cashaddr_prefix: str | None, slip44: int, segwit: bool, - fork_id: Optional[int], + fork_id: int | None, force_bip143: bool, decred: bool, negative_fee: bool, @@ -37,7 +37,7 @@ class CoinInfo: extra_data: bool, timestamp: bool, overwintered: bool, - confidential_assets: Optional[Dict[str, Any]], + confidential_assets: dict[str, Any] | None, ) -> None: self.coin_name = coin_name self.coin_shortcut = coin_shortcut diff --git a/core/src/apps/common/coininfo.py.mako b/core/src/apps/common/coininfo.py.mako index c6b352c2b..eb73ae939 100644 --- a/core/src/apps/common/coininfo.py.mako +++ b/core/src/apps/common/coininfo.py.mako @@ -5,7 +5,7 @@ from trezor.crypto.base58 import blake256d_32, groestl512d_32, keccak_32, sha256 from trezor.crypto.scripts import blake256_ripemd160_digest, sha256_ripemd160_digest if False: - from typing import Any, Dict, Optional + from typing import Any # flake8: noqa @@ -21,15 +21,15 @@ class CoinInfo: maxfee_kb: int, signed_message_header: str, xpub_magic: int, - xpub_magic_segwit_p2sh: Optional[int], - xpub_magic_segwit_native: Optional[int], - xpub_magic_multisig_segwit_p2sh: Optional[int], - xpub_magic_multisig_segwit_native: Optional[int], - bech32_prefix: Optional[str], - cashaddr_prefix: Optional[str], + xpub_magic_segwit_p2sh: int | None, + xpub_magic_segwit_native: int | None, + xpub_magic_multisig_segwit_p2sh: int | None, + xpub_magic_multisig_segwit_native: int | None, + bech32_prefix: str | None, + cashaddr_prefix: str | None, slip44: int, segwit: bool, - fork_id: Optional[int], + fork_id: int | None, force_bip143: bool, decred: bool, negative_fee: bool, @@ -37,7 +37,7 @@ class CoinInfo: extra_data: bool, timestamp: bool, overwintered: bool, - confidential_assets: Optional[Dict[str, Any]], + confidential_assets: dict[str, Any] | None, ) -> None: self.coin_name = coin_name self.coin_shortcut = coin_shortcut diff --git a/core/src/apps/common/confirm.py b/core/src/apps/common/confirm.py index 1135dfd41..d93040e1a 100644 --- a/core/src/apps/common/confirm.py +++ b/core/src/apps/common/confirm.py @@ -15,7 +15,7 @@ if __debug__: if False: - from typing import Any, Callable, Optional + from typing import Any, Callable from trezor import ui from trezor.ui.components.tt.confirm import ButtonContent, ButtonStyleType from trezor.ui.loader import LoaderStyleType @@ -26,9 +26,9 @@ async def confirm( ctx: wire.GenericContext, content: ui.Component, code: EnumTypeButtonRequestType = ButtonRequestType.Other, - confirm: Optional[ButtonContent] = Confirm.DEFAULT_CONFIRM, + confirm: ButtonContent | None = Confirm.DEFAULT_CONFIRM, confirm_style: ButtonStyleType = Confirm.DEFAULT_CONFIRM_STYLE, - cancel: Optional[ButtonContent] = Confirm.DEFAULT_CANCEL, + cancel: ButtonContent | None = Confirm.DEFAULT_CANCEL, cancel_style: ButtonStyleType = Confirm.DEFAULT_CANCEL_STYLE, major_confirm: bool = False, ) -> bool: diff --git a/core/src/apps/common/keychain.py b/core/src/apps/common/keychain.py index a5e1e7672..32ab472f8 100644 --- a/core/src/apps/common/keychain.py +++ b/core/src/apps/common/keychain.py @@ -11,13 +11,8 @@ if False: Any, Awaitable, Callable, - Dict, Iterable, - List, - Optional, - Tuple, TypeVar, - Union, ) from typing_extensions import Protocol @@ -54,8 +49,8 @@ FORBIDDEN_KEY_PATH = wire.DataError("Forbidden key path") class LRUCache: def __init__(self, size: int) -> None: self.size = size - self.cache_keys: List[Any] = [] - self.cache: Dict[Any, Deletable] = {} + self.cache_keys: list[Any] = [] + self.cache: dict[Any, Deletable] = {} def insert(self, key: Any, value: Deletable) -> None: if key in self.cache_keys: @@ -98,7 +93,7 @@ class Keychain: self.slip21_namespaces = tuple(slip21_namespaces) self._cache = LRUCache(10) - self._root_fingerprint: Optional[int] = None + self._root_fingerprint: int | None = None def __del__(self) -> None: self._cache.__del__() @@ -127,7 +122,7 @@ class Keychain: new_root: Callable[[], NodeType], ) -> NodeType: cached_prefix = tuple(path[:prefix_len]) - cached_root: Optional[NodeType] = self._cache.get(cached_prefix) + cached_root: NodeType | None = self._cache.get(cached_prefix) if cached_root is None: cached_root = new_root() cached_root.derive_path(cached_prefix) @@ -196,7 +191,7 @@ def with_slip44_keychain( raise ValueError # specify a pattern if allow_testnet: - slip44_ids: Union[int, Tuple[int, int]] = (slip44_id, 1) + slip44_ids: int | tuple[int, int] = (slip44_id, 1) else: slip44_ids = slip44_id diff --git a/core/src/apps/common/mnemonic.py b/core/src/apps/common/mnemonic.py index c1f4cb479..44017742d 100644 --- a/core/src/apps/common/mnemonic.py +++ b/core/src/apps/common/mnemonic.py @@ -5,15 +5,14 @@ from trezor.messages import BackupType from trezor.ui.components.tt.text import Text if False: - from typing import Optional, Tuple from trezor.messages.ResetDevice import EnumTypeBackupType -def get() -> Tuple[Optional[bytes], int]: +def get() -> tuple[bytes | None, int]: return get_secret(), get_type() -def get_secret() -> Optional[bytes]: +def get_secret() -> bytes | None: return storage.device.get_mnemonic_secret() diff --git a/core/src/apps/common/paths.py b/core/src/apps/common/paths.py index 55ee31b9d..10abc8a96 100644 --- a/core/src/apps/common/paths.py +++ b/core/src/apps/common/paths.py @@ -11,10 +11,8 @@ if False: Collection, Container, Iterable, - List, Sequence, TypeVar, - Union, ) from typing_extensions import Protocol from trezor import wire @@ -106,7 +104,7 @@ class PathSchema: "**": Interval(0, 0xFFFF_FFFF), } - def __init__(self, pattern: str, slip44_id: Union[int, Iterable[int]]) -> None: + def __init__(self, pattern: str, slip44_id: int | Iterable[int]) -> None: if not pattern.startswith("m/"): raise ValueError # unsupported path template components = pattern[2:].split("/") @@ -114,7 +112,7 @@ class PathSchema: if isinstance(slip44_id, int): slip44_id = (slip44_id,) - self.schema: List[Container[int]] = [] + self.schema: list[Container[int]] = [] self.trailing_components: Container[int] = () for component in components: @@ -270,7 +268,7 @@ def path_is_hardened(address_n: Bip32Path) -> bool: return all(is_hardened(n) for n in address_n) -def break_address_n_to_lines(address_n: Bip32Path) -> List[str]: +def break_address_n_to_lines(address_n: Bip32Path) -> list[str]: lines = [] path_str = address_n_to_str(address_n) diff --git a/core/src/apps/common/request_pin.py b/core/src/apps/common/request_pin.py index 535013101..8dfe4509a 100644 --- a/core/src/apps/common/request_pin.py +++ b/core/src/apps/common/request_pin.py @@ -11,7 +11,7 @@ from . import button_request from .sdcard import SdCardUnavailable, request_sd_salt if False: - from typing import Any, NoReturn, Optional, Tuple + from typing import Any, NoReturn _last_successful_unlock = 0 @@ -25,7 +25,7 @@ def can_lock_device() -> bool: async def request_pin( ctx: wire.GenericContext, prompt: str = "Enter your PIN", - attempts_remaining: Optional[int] = None, + attempts_remaining: int | None = None, allow_cancel: bool = True, ) -> str: await button_request(ctx, code=ButtonRequestType.PinEntry) @@ -67,7 +67,7 @@ async def pin_mismatch() -> None: async def request_pin_and_sd_salt( ctx: wire.Context, prompt: str = "Enter your PIN", allow_cancel: bool = True -) -> Tuple[str, Optional[bytearray]]: +) -> tuple[str, bytearray | None]: if config.has_pin(): pin = await request_pin(ctx, prompt, config.get_pin_rem(), allow_cancel) config.ensure_not_wipe_code(pin) diff --git a/core/src/apps/common/safety_checks.py b/core/src/apps/common/safety_checks.py index bec261a04..c770fd6ab 100644 --- a/core/src/apps/common/safety_checks.py +++ b/core/src/apps/common/safety_checks.py @@ -5,7 +5,6 @@ from storage.device import SAFETY_CHECK_LEVEL_PROMPT, SAFETY_CHECK_LEVEL_STRICT from trezor.messages import SafetyCheckLevel if False: - from typing import Optional from trezor.messages.ApplySettings import EnumTypeSafetyCheckLevel @@ -13,9 +12,9 @@ def read_setting() -> EnumTypeSafetyCheckLevel: """ Returns the effective safety check level. """ - temporary_safety_check_level: Optional[ - EnumTypeSafetyCheckLevel - ] = storage.cache.get(APP_COMMON_SAFETY_CHECKS_TEMPORARY) + temporary_safety_check_level: EnumTypeSafetyCheckLevel | None = storage.cache.get( + APP_COMMON_SAFETY_CHECKS_TEMPORARY + ) if temporary_safety_check_level is not None: return temporary_safety_check_level else: diff --git a/core/src/apps/common/sdcard.py b/core/src/apps/common/sdcard.py index 317e75b6a..cea46f302 100644 --- a/core/src/apps/common/sdcard.py +++ b/core/src/apps/common/sdcard.py @@ -3,9 +3,6 @@ from storage.sd_salt import SD_CARD_HOT_SWAPPABLE from trezor import fatfs, sdcard, ui, wire from trezor.ui.layouts import confirm_action, show_error_and_raise -if False: - from typing import Optional - class SdCardUnavailable(wire.ProcessError): pass @@ -160,7 +157,7 @@ async def ensure_sdcard( async def request_sd_salt( ctx: wire.GenericContext = wire.DUMMY_CONTEXT, -) -> Optional[bytearray]: +) -> bytearray | None: if not storage.sd_salt.is_enabled(): return None diff --git a/core/src/apps/common/seed.py b/core/src/apps/common/seed.py index 218e00f5f..0a7948249 100644 --- a/core/src/apps/common/seed.py +++ b/core/src/apps/common/seed.py @@ -6,8 +6,6 @@ from . import mnemonic from .passphrase import get as get_passphrase if False: - from typing import Optional - from .paths import Bip32Path, Slip21Path @@ -17,9 +15,7 @@ class Slip21Node: https://github.com/satoshilabs/slips/blob/master/slip-0021.md. """ - def __init__( - self, seed: Optional[bytes] = None, data: Optional[bytes] = None - ) -> None: + def __init__(self, seed: bytes | None = None, data: bytes | None = None) -> None: assert seed is None or data is None, "Specify exactly one of: seed, data" if data is not None: self.data = data diff --git a/core/src/apps/debug/__init__.py b/core/src/apps/debug/__init__.py index 4a68b0fe0..8732209a2 100644 --- a/core/src/apps/debug/__init__.py +++ b/core/src/apps/debug/__init__.py @@ -11,7 +11,6 @@ if __debug__: from trezor.messages.Success import Success if False: - from typing import List, Optional from trezor.messages.DebugLinkDecision import DebugLinkDecision from trezor.messages.DebugLinkGetState import DebugLinkGetState from trezor.messages.DebugLinkRecordScreen import DebugLinkRecordScreen @@ -23,7 +22,7 @@ if __debug__: save_screen = False save_screen_directory = "." - reset_internal_entropy: Optional[bytes] = None + reset_internal_entropy: bytes | None = None reset_current_words = loop.chan() reset_word_index = loop.chan() @@ -37,7 +36,7 @@ if __debug__: debuglink_decision_chan = loop.chan() layout_change_chan = loop.chan() - current_content: List[str] = [] + current_content: list[str] = [] watch_layout_changes = False def screenshot() -> bool: diff --git a/core/src/apps/eos/actions/layout.py b/core/src/apps/eos/actions/layout.py index 8eddbb552..8c1181beb 100644 --- a/core/src/apps/eos/actions/layout.py +++ b/core/src/apps/eos/actions/layout.py @@ -11,7 +11,6 @@ from .. import helpers from ..layout import require_confirm if False: - from typing import List from trezor import wire from trezor.messages.EosAuthorization import EosAuthorization from trezor.messages.EosActionBuyRam import EosActionBuyRam @@ -39,7 +38,7 @@ _FIVE_FIELDS_PER_PAGE = const(5) async def _require_confirm_paginated( - ctx: wire.Context, header: str, fields: List[str], per_page: int + ctx: wire.Context, header: str, fields: list[str], per_page: int ) -> None: pages = [] for page in chunks(fields, per_page): @@ -265,7 +264,7 @@ async def confirm_action_unknown( await _require_confirm_paginated(ctx, text, fields, _FIVE_FIELDS_PER_PAGE) -def authorization_fields(auth: EosAuthorization) -> List[str]: +def authorization_fields(auth: EosAuthorization) -> list[str]: fields = [] fields.append("Threshold:") @@ -311,7 +310,7 @@ def authorization_fields(auth: EosAuthorization) -> List[str]: return fields -def split_data(data: str) -> List[str]: +def split_data(data: str) -> list[str]: lines = [] while data: lines.append("{} ".format(data[:_LINE_LENGTH])) diff --git a/core/src/apps/eos/get_public_key.py b/core/src/apps/eos/get_public_key.py index d49d1a7cb..bdba59e24 100644 --- a/core/src/apps/eos/get_public_key.py +++ b/core/src/apps/eos/get_public_key.py @@ -10,11 +10,10 @@ from .helpers import public_key_to_wif from .layout import require_get_public_key if False: - from typing import Tuple from trezor.crypto import bip32 -def _get_public_key(node: bip32.HDNode) -> Tuple[str, bytes]: +def _get_public_key(node: bip32.HDNode) -> tuple[str, bytes]: seckey = node.private_key() public_key = secp256k1.publickey(seckey, True) wif = public_key_to_wif(public_key) diff --git a/core/src/apps/ethereum/networks.py b/core/src/apps/ethereum/networks.py index 5e0757ca9..0bbecc193 100644 --- a/core/src/apps/ethereum/networks.py +++ b/core/src/apps/ethereum/networks.py @@ -9,7 +9,7 @@ SLIP44_WANCHAIN = const(5718350) SLIP44_ETHEREUM = const(60) if False: - from typing import Iterator, Optional + from typing import Iterator def is_wanchain(chain_id: int, tx_type: int) -> bool: @@ -24,14 +24,14 @@ def shortcut_by_chain_id(chain_id: int, tx_type: int = None) -> str: return n.shortcut if n is not None else "UNKN" -def by_chain_id(chain_id: int) -> Optional["NetworkInfo"]: +def by_chain_id(chain_id: int) -> "NetworkInfo" | None: for n in _networks_iterator(): if n.chain_id == chain_id: return n return None -def by_slip44(slip44: int) -> Optional["NetworkInfo"]: +def by_slip44(slip44: int) -> "NetworkInfo" | None: if slip44 == SLIP44_WANCHAIN: # Coerce to Ethereum slip44 = SLIP44_ETHEREUM diff --git a/core/src/apps/ethereum/networks.py.mako b/core/src/apps/ethereum/networks.py.mako index 5925745e9..c78632083 100644 --- a/core/src/apps/ethereum/networks.py.mako +++ b/core/src/apps/ethereum/networks.py.mako @@ -9,7 +9,7 @@ SLIP44_WANCHAIN = const(5718350) SLIP44_ETHEREUM = const(60) if False: - from typing import Iterator, Optional + from typing import Iterator def is_wanchain(chain_id: int, tx_type: int) -> bool: @@ -24,14 +24,14 @@ def shortcut_by_chain_id(chain_id: int, tx_type: int = None) -> str: return n.shortcut if n is not None else "UNKN" -def by_chain_id(chain_id: int) -> Optional["NetworkInfo"]: +def by_chain_id(chain_id: int) -> "NetworkInfo" | None: for n in _networks_iterator(): if n.chain_id == chain_id: return n return None -def by_slip44(slip44: int) -> Optional["NetworkInfo"]: +def by_slip44(slip44: int) -> "NetworkInfo" | None: if slip44 == SLIP44_WANCHAIN: # Coerce to Ethereum slip44 = SLIP44_ETHEREUM diff --git a/core/src/apps/homescreen/homescreen.py b/core/src/apps/homescreen/homescreen.py index fbeb567bb..928c35150 100644 --- a/core/src/apps/homescreen/homescreen.py +++ b/core/src/apps/homescreen/homescreen.py @@ -10,9 +10,6 @@ from apps.base import lock_device from . import HomescreenBase -if False: - from typing import Optional - _LOADER_DELAY_MS = const(500) _LOADER_TOTAL_MS = const(2500) @@ -34,7 +31,7 @@ class Homescreen(HomescreenBase): offset_y=-10, reverse_speedup=3, ) - self.touch_ms: Optional[int] = None + self.touch_ms: int | None = None def on_render(self) -> None: if not self.repaint: diff --git a/core/src/apps/management/backup_types.py b/core/src/apps/management/backup_types.py index cdc58e552..0f0248c45 100644 --- a/core/src/apps/management/backup_types.py +++ b/core/src/apps/management/backup_types.py @@ -2,8 +2,6 @@ from trezor.crypto.slip39 import Share from trezor.messages import BackupType if False: - from typing import Optional - from trezor.messages.ResetDevice import EnumTypeBackupType @@ -29,7 +27,7 @@ def is_slip39_backup_type(backup_type: EnumTypeBackupType) -> bool: def infer_backup_type( - is_slip39: bool, share: Optional[Share] = None + is_slip39: bool, share: Share | None = None ) -> EnumTypeBackupType: if not is_slip39: # BIP-39 return BackupType.Bip39 diff --git a/core/src/apps/management/recovery_device/homescreen.py b/core/src/apps/management/recovery_device/homescreen.py index dcdd2d742..b4c0db88c 100644 --- a/core/src/apps/management/recovery_device/homescreen.py +++ b/core/src/apps/management/recovery_device/homescreen.py @@ -17,7 +17,6 @@ from .. import backup_types from . import layout, recover if False: - from typing import Optional, Tuple from trezor.messages.ResetDevice import EnumTypeBackupType @@ -162,13 +161,13 @@ async def _request_word_count(ctx: wire.GenericContext, dry_run: bool) -> int: async def _process_words( ctx: wire.GenericContext, words: str -) -> Tuple[Optional[bytes], EnumTypeBackupType]: +) -> tuple[bytes | None, EnumTypeBackupType]: word_count = len(words.split(" ")) is_slip39 = backup_types.is_slip39_word_count(word_count) share = None if not is_slip39: # BIP-39 - secret: Optional[bytes] = recover.process_bip39(words) + secret: bytes | None = recover.process_bip39(words) else: secret, share = recover.process_slip39(words) diff --git a/core/src/apps/management/recovery_device/keyboard_bip39.py b/core/src/apps/management/recovery_device/keyboard_bip39.py index 04486f68c..d37e6e9cc 100644 --- a/core/src/apps/management/recovery_device/keyboard_bip39.py +++ b/core/src/apps/management/recovery_device/keyboard_bip39.py @@ -9,7 +9,6 @@ from trezor.ui.components.tt.button import ( ) if False: - from typing import Optional, Tuple from trezor.ui.components.tt.button import ButtonContent, ButtonStyleStateType @@ -120,7 +119,7 @@ class Bip39Keyboard(ui.Layout): ("abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz") ) ] - self.pending_button: Optional[Button] = None + self.pending_button: Button | None = None self.pending_index = 0 def dispatch(self, event: int, x: int, y: int) -> None: @@ -172,7 +171,7 @@ class Bip39Keyboard(ui.Layout): # Word was confirmed by the user. raise ui.Result(word) - def edit(self, text: str, button: Optional[Button] = None, index: int = 0) -> None: + def edit(self, text: str, button: Button | None = None, index: int = 0) -> None: self.pending_button = button self.pending_index = index @@ -217,7 +216,7 @@ class Bip39Keyboard(ui.Layout): if __debug__: - def create_tasks(self) -> Tuple[loop.Task, ...]: + def create_tasks(self) -> tuple[loop.Task, ...]: from apps.debug import input_signal return super().create_tasks() + (input_signal(),) diff --git a/core/src/apps/management/recovery_device/keyboard_slip39.py b/core/src/apps/management/recovery_device/keyboard_slip39.py index 576064b56..7fe140ae1 100644 --- a/core/src/apps/management/recovery_device/keyboard_slip39.py +++ b/core/src/apps/management/recovery_device/keyboard_slip39.py @@ -9,7 +9,6 @@ from trezor.ui.components.tt.button import ( ) if False: - from typing import Optional, Tuple from trezor.ui.components.tt.button import ButtonContent, ButtonStyleStateType @@ -33,8 +32,8 @@ class InputButton(Button): def __init__(self, area: ui.Area, keyboard: "Slip39Keyboard") -> None: super().__init__(area, "") self.word = "" - self.pending_button: Optional[Button] = None - self.pending_index: Optional[int] = None + self.pending_button: Button | None = None + self.pending_index: int | None = None self.keyboard = keyboard self.disable() @@ -42,8 +41,8 @@ class InputButton(Button): self, text: str, word: str, - pending_button: Optional[Button], - pending_index: Optional[int], + pending_button: Button | None, + pending_index: int | None, ) -> None: self.word = word self.text = text @@ -123,7 +122,7 @@ class Slip39Keyboard(ui.Layout): ("ab", "cd", "ef", "ghij", "klm", "nopq", "rs", "tuv", "wxyz") ) ] - self.pending_button: Optional[Button] = None + self.pending_button: Button | None = None self.pending_index = 0 self.button_sequence = "" self.mask = slip39.KEYBOARD_FULL_MASK @@ -170,7 +169,7 @@ class Slip39Keyboard(ui.Layout): # Word was confirmed by the user. raise ui.Result(word) - def edit(self, button: Optional[Button] = None, index: int = 0) -> None: + def edit(self, button: Button | None = None, index: int = 0) -> None: self.pending_button = button self.pending_index = index @@ -227,7 +226,7 @@ class Slip39Keyboard(ui.Layout): if __debug__: - def create_tasks(self) -> Tuple[loop.Task, ...]: + def create_tasks(self) -> tuple[loop.Task, ...]: from apps.debug import input_signal return super().create_tasks() + (input_signal(),) diff --git a/core/src/apps/management/recovery_device/layout.py b/core/src/apps/management/recovery_device/layout.py index d88211c72..fc8fa3ccb 100644 --- a/core/src/apps/management/recovery_device/layout.py +++ b/core/src/apps/management/recovery_device/layout.py @@ -17,7 +17,7 @@ from .keyboard_slip39 import Slip39Keyboard from .recover import RecoveryAborted if False: - from typing import List, Optional, Callable, Iterable, Tuple, Union + from typing import Callable, Iterable from trezor.messages.ResetDevice import EnumTypeBackupType @@ -61,14 +61,14 @@ async def request_word_count(ctx: wire.GenericContext, dry_run: bool) -> int: async def request_mnemonic( - ctx: wire.GenericContext, word_count: int, backup_type: Optional[EnumTypeBackupType] -) -> Optional[str]: + ctx: wire.GenericContext, word_count: int, backup_type: EnumTypeBackupType | None +) -> str | None: await button_request(ctx, code=ButtonRequestType.MnemonicInput) - words: List[str] = [] + words: list[str] = [] for i in range(word_count): if backup_types.is_slip39_word_count(word_count): - keyboard: Union[Slip39Keyboard, Bip39Keyboard] = Slip39Keyboard( + keyboard: Slip39Keyboard | Bip39Keyboard = Slip39Keyboard( "Type word %s of %s:" % (i + 1, word_count) ) else: @@ -94,11 +94,11 @@ async def request_mnemonic( async def show_remaining_shares( ctx: wire.GenericContext, - groups: Iterable[Tuple[int, Tuple[str, ...]]], # remaining + list 3 words - shares_remaining: List[int], + groups: Iterable[tuple[int, tuple[str, ...]]], # remaining + list 3 words + shares_remaining: list[int], group_threshold: int, ) -> None: - pages: List[ui.Component] = [] + pages: list[ui.Component] = [] for remaining, group in groups: if 0 < remaining < MAX_SHARE_COUNT: text = Text("Remaining Shares") @@ -205,7 +205,7 @@ async def show_group_threshold_reached(ctx: wire.GenericContext) -> None: class RecoveryHomescreen(ui.Component): - def __init__(self, text: str, subtext: Optional[str] = None): + def __init__(self, text: str, subtext: str | None = None): super().__init__() self.text = text self.subtext = subtext @@ -240,7 +240,7 @@ class RecoveryHomescreen(ui.Component): if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: return [self.__class__.__name__, self.text, self.subtext or ""] @@ -248,7 +248,7 @@ async def homescreen_dialog( ctx: wire.GenericContext, homepage: RecoveryHomescreen, button_label: str, - info_func: Optional[Callable] = None, + info_func: Callable | None = None, ) -> None: while True: if info_func: diff --git a/core/src/apps/management/recovery_device/recover.py b/core/src/apps/management/recovery_device/recover.py index ac9e3a8cb..f0b62a5b3 100644 --- a/core/src/apps/management/recovery_device/recover.py +++ b/core/src/apps/management/recovery_device/recover.py @@ -7,7 +7,7 @@ from .. import backup_types if False: from trezor.messages.ResetDevice import EnumTypeBackupType - from typing import Optional, Tuple, List, Union + from typing import Union class RecoveryAborted(Exception): @@ -24,7 +24,7 @@ def process_bip39(words: str) -> bytes: return words.encode() -def process_slip39(words: str) -> Tuple[Optional[bytes], slip39.Share]: +def process_slip39(words: str) -> tuple[bytes | None, slip39.Share]: """ Processes a single mnemonic share. Returns the encrypted master secret (or None if more shares are needed) and the share's group index and member index. @@ -92,7 +92,7 @@ def process_slip39(words: str) -> Tuple[Optional[bytes], slip39.Share]: if False: - Slip39State = Union[Tuple[int, EnumTypeBackupType], Tuple[None, None]] + Slip39State = Union[tuple[int, EnumTypeBackupType], tuple[None, None]] def load_slip39_state() -> Slip39State: @@ -106,7 +106,7 @@ def load_slip39_state() -> Slip39State: return word_count, backup_types.infer_backup_type(True, share) -def fetch_previous_mnemonics() -> Optional[List[List[str]]]: +def fetch_previous_mnemonics() -> list[list[str]] | None: mnemonics = [] if not storage.recovery.get_slip39_group_count(): return None diff --git a/core/src/apps/management/recovery_device/word_validity.py b/core/src/apps/management/recovery_device/word_validity.py index a72310718..b7dc5918c 100644 --- a/core/src/apps/management/recovery_device/word_validity.py +++ b/core/src/apps/management/recovery_device/word_validity.py @@ -4,7 +4,6 @@ from trezor.messages import BackupType from . import recover if False: - from typing import List, Optional from trezor.messages.ResetDevice import EnumTypeBackupType @@ -24,9 +23,7 @@ class ThresholdReached(WordValidityResult): pass -def check( - backup_type: Optional[EnumTypeBackupType], partial_mnemonic: List[str] -) -> None: +def check(backup_type: EnumTypeBackupType | None, partial_mnemonic: list[str]) -> None: # we can't perform any checks if the backup type was not yet decided if backup_type is None: return @@ -49,7 +46,7 @@ def check( def check_slip39_basic( - partial_mnemonic: List[str], previous_mnemonics: List[List[str]] + partial_mnemonic: list[str], previous_mnemonics: list[list[str]] ) -> None: # check if first 3 words of mnemonic match # we can check against the first one, others were checked already @@ -68,7 +65,7 @@ def check_slip39_basic( def check_slip39_advanced( - partial_mnemonic: List[str], previous_mnemonics: List[List[str]] + partial_mnemonic: list[str], previous_mnemonics: list[list[str]] ) -> None: current_index = len(partial_mnemonic) - 1 current_word = partial_mnemonic[-1] diff --git a/core/src/apps/management/reset_device/layout.py b/core/src/apps/management/reset_device/layout.py index d0a079db5..67e3c983a 100644 --- a/core/src/apps/management/reset_device/layout.py +++ b/core/src/apps/management/reset_device/layout.py @@ -15,7 +15,6 @@ from apps.common.confirm import confirm, require_hold_to_confirm if False: from trezor import loop - from typing import List, Tuple if __debug__: from apps import debug @@ -596,8 +595,8 @@ class MnemonicWordSelect(ui.Layout): if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: return self.text.read_content() + [b.text for b in self.buttons] - def create_tasks(self) -> Tuple[loop.Task, ...]: + def create_tasks(self) -> tuple[loop.Task, ...]: return super().create_tasks() + (debug.input_signal(),) diff --git a/core/src/apps/management/sd_protect.py b/core/src/apps/management/sd_protect.py index ea4efb6ab..cd954cff8 100644 --- a/core/src/apps/management/sd_protect.py +++ b/core/src/apps/management/sd_protect.py @@ -14,11 +14,11 @@ from apps.common.request_pin import ( from apps.common.sdcard import confirm_retry_sd, ensure_sdcard if False: - from typing import Awaitable, Tuple + from typing import Awaitable from trezor.messages.SdProtect import SdProtect -def _make_salt() -> Tuple[bytes, bytes, bytes]: +def _make_salt() -> tuple[bytes, bytes, bytes]: salt = random.bytes(storage.sd_salt.SD_SALT_LEN_BYTES) auth_key = random.bytes(storage.device.SD_SALT_AUTH_KEY_LEN_BYTES) tag = storage.sd_salt.compute_auth_tag(salt, auth_key) diff --git a/core/src/apps/misc/sign_identity.py b/core/src/apps/misc/sign_identity.py index 4f86afe87..8c307762e 100644 --- a/core/src/apps/misc/sign_identity.py +++ b/core/src/apps/misc/sign_identity.py @@ -10,8 +10,6 @@ from apps.common.keychain import get_keychain from apps.common.paths import AlwaysMatchingSchema if False: - from typing import Optional, Union - from trezor.messages.IdentityType import IdentityType from trezor.messages.SignIdentity import SignIdentity @@ -36,7 +34,7 @@ async def sign_identity(ctx: wire.Context, msg: SignIdentity) -> SignedIdentity: coin = coininfo.by_name("Bitcoin") if msg.ecdsa_curve_name == "secp256k1": # hardcoded bitcoin address type - address: Optional[str] = node.address(coin.address_type) + address: str | None = node.address(coin.address_type) else: address = None pubkey = node.public_key() @@ -81,7 +79,7 @@ async def sign_identity(ctx: wire.Context, msg: SignIdentity) -> SignedIdentity: async def require_confirm_sign_identity( - ctx: wire.Context, identity: IdentityType, challenge_visual: Optional[str] + ctx: wire.Context, identity: IdentityType, challenge_visual: str | None ) -> None: proto = identity.proto.upper() if identity.proto else "identity" await confirm_sign_identity( @@ -124,7 +122,7 @@ def sign_challenge( seckey: bytes, challenge_hidden: bytes, challenge_visual: str, - sigtype: Union[str, coininfo.CoinInfo], + sigtype: str | coininfo.CoinInfo, curve: str, ) -> bytes: from trezor.crypto.hashlib import sha256 diff --git a/core/src/apps/monero/layout/confirms.py b/core/src/apps/monero/layout/confirms.py index 198bbf496..d9e8e0a9e 100644 --- a/core/src/apps/monero/layout/confirms.py +++ b/core/src/apps/monero/layout/confirms.py @@ -14,7 +14,6 @@ DUMMY_PAYMENT_ID = b"\x00\x00\x00\x00\x00\x00\x00\x00" if False: - from typing import Optional from apps.monero.signing.state import State from trezor.messages.MoneroTransactionData import MoneroTransactionData from trezor.messages.MoneroTransactionDestinationEntry import ( @@ -209,7 +208,7 @@ class LiveRefreshStep(ui.Component): ) -async def transaction_step(state: State, step: int, sub_step: Optional[int] = None): +async def transaction_step(state: State, step: int, sub_step: int | None = None): if step == 0: info = ["Signing..."] elif step == state.STEP_INP: diff --git a/core/src/apps/monero/misc.py b/core/src/apps/monero/misc.py index faf76d6b4..7712a75da 100644 --- a/core/src/apps/monero/misc.py +++ b/core/src/apps/monero/misc.py @@ -1,5 +1,4 @@ if False: - from typing import Tuple from apps.monero.xmr.types import Sc25519 @@ -32,7 +31,7 @@ def compute_tx_key( def compute_enc_key_host( view_key_private: Sc25519, tx_prefix_hash: bytes -) -> Tuple[bytes, bytes]: +) -> tuple[bytes, bytes]: from apps.monero.xmr import crypto salt = crypto.random_bytes(32) diff --git a/core/src/apps/monero/signing/state.py b/core/src/apps/monero/signing/state.py index beda46e86..d0553790d 100644 --- a/core/src/apps/monero/signing/state.py +++ b/core/src/apps/monero/signing/state.py @@ -6,11 +6,10 @@ from trezor import log from apps.monero.xmr import crypto if False: - from typing import Dict, List, Optional, Tuple from apps.monero.xmr.types import Ge25519, Sc25519 from apps.monero.xmr.credentials import AccountCreds - Subaddresses = Dict[bytes, Tuple[int, int]] + Subaddresses = dict[bytes, tuple[int, int]] class State: @@ -37,11 +36,11 @@ class State: - spend private/public key - and its corresponding address """ - self.creds: Optional[AccountCreds] = None + self.creds: AccountCreds | None = None # HMAC/encryption keys used to protect offloaded data - self.key_hmac: Optional[bytes] = None - self.key_enc: Optional[bytes] = None + self.key_hmac: bytes | None = None + self.key_enc: bytes | None = None """ Transaction keys @@ -77,8 +76,8 @@ class State: self.account_idx = 0 # contains additional tx keys if need_additional_tx_keys is True - self.additional_tx_private_keys: List[Sc25519] = [] - self.additional_tx_public_keys: List[bytes] = [] + self.additional_tx_private_keys: list[Sc25519] = [] + self.additional_tx_public_keys: list[bytes] = [] # currently processed input/output index self.current_input_index = -1 @@ -92,14 +91,14 @@ class State: self.summary_outs_money = 0 # output commitments - self.output_pk_commitments: List[bytes] = [] + self.output_pk_commitments: list[bytes] = [] - self.output_amounts: List[int] = [] + self.output_amounts: list[int] = [] # output *range proof* masks. HP10+ makes them deterministic. - self.output_masks: List[Sc25519] = [] + self.output_masks: list[Sc25519] = [] # the range proofs are calculated in batches, this denotes the grouping - self.rsig_grouping: List[int] = [] + self.rsig_grouping: list[int] = [] # is range proof computing offloaded or not self.rsig_offload = False @@ -115,13 +114,13 @@ class State: # contains an array where each item denotes the input's position # (inputs are sorted by key images) - self.source_permutation: List[int] = [] + self.source_permutation: list[int] = [] # Last key image seen. Used for input permutation correctness check - self.last_ki: Optional[bytes] = None + self.last_ki: bytes | None = None # Encryption key to release to host after protocol ends without error - self.opening_key: Optional[bytes] = None + self.opening_key: bytes | None = None # Step transition automaton self.last_step = self.STEP_INIT @@ -132,7 +131,7 @@ class State: See Monero-Trezor documentation section 3.3 for more details. """ self.tx_prefix_hasher = KeccakXmrArchive() - self.tx_prefix_hash: Optional[bytes] = None + self.tx_prefix_hash: bytes | None = None """ Full message hasher/hash that is to be signed using MLSAG. @@ -140,7 +139,7 @@ class State: See Monero-Trezor documentation section 3.3 for more details. """ self.full_message_hasher = PreMlsagHasher() - self.full_message: Optional[bytes] = None + self.full_message: bytes | None = None def mem_trace(self, x=None, collect=False): 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 f2dedbae0..4a621c48b 100644 --- a/core/src/apps/monero/signing/step_01_init_transaction.py +++ b/core/src/apps/monero/signing/step_01_init_transaction.py @@ -10,7 +10,6 @@ from apps.monero.signing.state import State from apps.monero.xmr import crypto, monero if False: - from typing import List from apps.monero.xmr.types import Sc25519, Ge25519 from trezor.messages.MoneroTransactionData import MoneroTransactionData from trezor.messages.MoneroTransactionRsigData import MoneroTransactionRsigData @@ -122,7 +121,7 @@ async def init_transaction( return MoneroTransactionInitAck(hmacs=hmacs, rsig_data=rsig_data) -def _check_subaddresses(state: State, outputs: List[MoneroTransactionDestinationEntry]): +def _check_subaddresses(state: State, outputs: list[MoneroTransactionDestinationEntry]): """ Using subaddresses leads to a few poorly documented exceptions. @@ -221,7 +220,7 @@ def _check_grouping(state: State): raise ValueError("Invalid grouping") -def _check_change(state: State, outputs: List[MoneroTransactionDestinationEntry]): +def _check_change(state: State, outputs: list[MoneroTransactionDestinationEntry]): """ Check if the change address in state.output_change (from `tsx_data.outputs`) is a) among tx outputs @@ -288,7 +287,7 @@ def _compute_sec_keys(state: State, tsx_data: MoneroTransactionData): state.key_enc = crypto.keccak_2hash(b"enc" + master_key) -def _precompute_subaddr(state: State, account: int, indices: List[int]): +def _precompute_subaddr(state: State, account: int, indices: list[int]): """ Precomputes subaddresses for account (major) and list of indices (minors) Subaddresses have to be stored in encoded form - unique representation. 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 0469d53c1..7b9c80c7d 100644 --- a/core/src/apps/monero/signing/step_02_set_input.py +++ b/core/src/apps/monero/signing/step_02_set_input.py @@ -17,7 +17,6 @@ from apps.monero.xmr import crypto, monero, serialize from .state import State if False: - from typing import List, Tuple, Optional from apps.monero.xmr.types import Sc25519, Ge25519 from trezor.messages.MoneroTransactionSourceEntry import ( MoneroTransactionSourceEntry, @@ -139,7 +138,7 @@ async def set_input( ) -def _gen_commitment(state: State, in_amount: int) -> Tuple[Sc25519, Ge25519]: +def _gen_commitment(state: State, in_amount: int) -> tuple[Sc25519, Ge25519]: """ Computes Pedersen commitment - pseudo outs Here is slight deviation from the original protocol. @@ -155,7 +154,7 @@ def _gen_commitment(state: State, in_amount: int) -> Tuple[Sc25519, Ge25519]: return alpha, crypto.gen_commitment(alpha, in_amount) -def _absolute_output_offsets_to_relative(off: List[int]) -> List[int]: +def _absolute_output_offsets_to_relative(off: list[int]) -> list[int]: """ Mixin outputs are specified in relative numbers. First index is absolute and the rest is an offset of a previous one. @@ -173,7 +172,7 @@ def _absolute_output_offsets_to_relative(off: List[int]) -> List[int]: def _get_additional_public_key( src_entr: MoneroTransactionSourceEntry, -) -> Optional[Ge25519]: +) -> Ge25519 | None: additional_tx_pub_key = None if len(src_entr.real_out_additional_tx_keys) == 1: # compression additional_tx_pub_key = crypto.decodepoint( diff --git a/core/src/apps/monero/signing/step_03_inputs_permutation.py b/core/src/apps/monero/signing/step_03_inputs_permutation.py index 9acede9e5..9f2ff7481 100644 --- a/core/src/apps/monero/signing/step_03_inputs_permutation.py +++ b/core/src/apps/monero/signing/step_03_inputs_permutation.py @@ -21,14 +21,13 @@ from apps.monero.layout.confirms import transaction_step from .state import State if False: - from typing import List from trezor.messages.MoneroTransactionInputsPermutationAck import ( MoneroTransactionInputsPermutationAck, ) async def tsx_inputs_permutation( - state: State, permutation: List[int] + state: State, permutation: list[int] ) -> MoneroTransactionInputsPermutationAck: from trezor.messages.MoneroTransactionInputsPermutationAck import ( MoneroTransactionInputsPermutationAck, @@ -54,7 +53,7 @@ async def tsx_inputs_permutation( return MoneroTransactionInputsPermutationAck() -def _check_permutation(permutation: List[int]): +def _check_permutation(permutation: list[int]): for n in range(len(permutation)): if n not in permutation: raise ValueError("Invalid permutation") 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 14143c795..c260c6962 100644 --- a/core/src/apps/monero/signing/step_06_set_output.py +++ b/core/src/apps/monero/signing/step_06_set_output.py @@ -14,7 +14,6 @@ from apps.monero.xmr import crypto, serialize from .state import State if False: - from typing import Tuple from apps.monero.xmr.types import Sc25519, Ge25519 from apps.monero.xmr.serialize_messages.tx_ecdh import EcdhTuple from apps.monero.xmr.serialize_messages.tx_rsig_bulletproof import Bulletproof @@ -177,7 +176,7 @@ def _validate( def _compute_tx_keys( state: State, dst_entr: MoneroTransactionDestinationEntry -) -> Tuple[Ge25519, Sc25519]: +) -> tuple[Ge25519, Sc25519]: """Computes tx_out_key, amount_key""" if state.is_processing_offloaded: @@ -206,7 +205,7 @@ def _compute_tx_keys( def _set_out_tx_out( state: State, dst_entr: MoneroTransactionDestinationEntry, tx_out_key: Ge25519 -) -> Tuple[bytes, bytes]: +) -> tuple[bytes, bytes]: """ Manually serializes TxOut(0, TxoutToKey(key)) and calculates hmac. """ @@ -230,7 +229,7 @@ def _set_out_tx_out( def _range_proof( state: State, rsig_data: MoneroTransactionRsigData -) -> Tuple[MoneroTransactionRsigData, Sc25519]: +) -> tuple[MoneroTransactionRsigData, Sc25519]: """ Computes rangeproof and handles range proof offloading logic. @@ -413,7 +412,7 @@ def _return_rsig_data( def _get_ecdh_info_and_out_pk( state: State, tx_out_key: Ge25519, amount: int, mask: Sc25519, amount_key: Sc25519 -) -> Tuple[bytes, bytes, bytes]: +) -> tuple[bytes, bytes, bytes]: """ Calculates the Pedersen commitment C = aG + bH and returns it as CtKey. Also encodes the two items - `mask` and `amount` - into ecdh info, 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 e7eb20c5a..4435550f4 100644 --- a/core/src/apps/monero/signing/step_09_sign_input.py +++ b/core/src/apps/monero/signing/step_09_sign_input.py @@ -20,7 +20,6 @@ from apps.monero.xmr import crypto from .state import State if False: - from typing import List from trezor.messages.MoneroTransactionSourceEntry import ( MoneroTransactionSourceEntry, ) @@ -225,7 +224,7 @@ async def sign_input( ) -def _protect_signature(state: State, mg_buffer: List[bytes]) -> List[bytes]: +def _protect_signature(state: State, mg_buffer: list[bytes]) -> list[bytes]: """ Encrypts the signature with keys derived from state.opening_key. After protocol finishes without error, opening_key is sent to the 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 763fdbdbf..2c373e0c9 100644 --- a/core/src/apps/monero/signing/step_10_sign_final.py +++ b/core/src/apps/monero/signing/step_10_sign_final.py @@ -17,7 +17,6 @@ from apps.monero.xmr.crypto import chacha_poly from .state import State if False: - from typing import Tuple from apps.monero.xmr.types import Sc25519 @@ -48,7 +47,7 @@ def final_msg(state: State) -> MoneroTransactionFinalAck: def _compute_tx_key( spend_key_private: Sc25519, tx_prefix_hash: bytes -) -> Tuple[bytes, bytes, bytes]: +) -> tuple[bytes, bytes, bytes]: salt = crypto.random_bytes(32) rand_mult_num = crypto.random_scalar() diff --git a/core/src/apps/monero/xmr/addresses.py b/core/src/apps/monero/xmr/addresses.py index 501065a0a..936a8a631 100644 --- a/core/src/apps/monero/xmr/addresses.py +++ b/core/src/apps/monero/xmr/addresses.py @@ -3,7 +3,6 @@ from trezor.crypto import monero as tcry from apps.monero.xmr.networks import NetworkTypes, net_version if False: - from typing import List, Tuple, Optional from apps.monero.xmr.types import Ge25519 from trezor.messages.MoneroAccountPublicAddress import MoneroAccountPublicAddress from trezor.messages.MoneroTransactionDestinationEntry import ( @@ -19,7 +18,7 @@ def addr_to_hash(addr: MoneroAccountPublicAddress) -> bytes: def encode_addr( - version, spend_pub: Ge25519, view_pub: Ge25519, payment_id: Optional[bytes] = None + version, spend_pub: Ge25519, view_pub: Ge25519, payment_id: bytes | None = None ) -> str: """ Builds Monero address from public keys @@ -30,7 +29,7 @@ def encode_addr( return tcry.xmr_base58_addr_encode_check(ord(version), bytes(buf)) -def decode_addr(addr: bytes) -> Tuple[int, bytes, bytes]: +def decode_addr(addr: bytes) -> tuple[int, bytes, bytes]: """ Given address, get version and public spend and view keys. """ @@ -51,9 +50,9 @@ def public_addr_encode( def classify_subaddresses( - tx_dests: List[MoneroTransactionDestinationEntry], + tx_dests: list[MoneroTransactionDestinationEntry], change_addr: MoneroAccountPublicAddress, -) -> Tuple[int, int, int]: +) -> tuple[int, int, int]: """ Classify destination subaddresses """ @@ -84,7 +83,7 @@ def addr_eq(a: MoneroAccountPublicAddress, b: MoneroAccountPublicAddress): def get_change_addr_idx( - outputs: List[MoneroTransactionDestinationEntry], + outputs: list[MoneroTransactionDestinationEntry], change_dts: MoneroTransactionDestinationEntry, ) -> int: """ diff --git a/core/src/apps/monero/xmr/credentials.py b/core/src/apps/monero/xmr/credentials.py index 573efa068..90a1844fd 100644 --- a/core/src/apps/monero/xmr/credentials.py +++ b/core/src/apps/monero/xmr/credentials.py @@ -3,7 +3,6 @@ from apps.monero.xmr.addresses import encode_addr from apps.monero.xmr.networks import NetworkTypes, net_version if False: - from typing import Optional from apps.monero.xmr.types import Sc25519, Ge25519 @@ -14,11 +13,11 @@ class AccountCreds: def __init__( self, - view_key_private: Optional[Sc25519] = None, - spend_key_private: Optional[Sc25519] = None, - view_key_public: Optional[Ge25519] = None, - spend_key_public: Optional[Ge25519] = None, - address: Optional[str] = None, + view_key_private: Sc25519 | None = None, + spend_key_private: Sc25519 | None = None, + view_key_public: Ge25519 | None = None, + spend_key_public: Ge25519 | None = None, + address: str | None = None, network_type=NetworkTypes.MAINNET, ): self.view_key_private = view_key_private diff --git a/core/src/apps/monero/xmr/crypto/__init__.py b/core/src/apps/monero/xmr/crypto/__init__.py index 0bff3e820..867cdafdf 100644 --- a/core/src/apps/monero/xmr/crypto/__init__.py +++ b/core/src/apps/monero/xmr/crypto/__init__.py @@ -11,7 +11,6 @@ from trezor.crypto import monero as tcry, random from trezor.crypto.hashlib import sha3_256 if False: - from typing import Tuple, Optional, Union from apps.monero.xmr.types import Sc25519, Ge25519 @@ -182,7 +181,7 @@ def ge25519_double_scalarmult_base_vartime(a, A, b) -> Ge25519: ge25519_double_scalarmult_vartime2 = tcry.xmr_add_keys3 -def identity(byte_enc=False) -> Union[Ge25519, bytes]: +def identity(byte_enc=False) -> Ge25519 | bytes: idd = tcry.ge25519_set_neutral() return idd if not byte_enc else encodepoint(idd) @@ -203,7 +202,7 @@ http://elligator.cr.yp.to/elligator-20130828.pdf cn_fast_hash = keccak_hash -def hash_to_scalar(data: bytes, length: Optional[int] = None): +def hash_to_scalar(data: bytes, length: int | None = None): """ H_s(P) """ @@ -211,7 +210,7 @@ def hash_to_scalar(data: bytes, length: Optional[int] = None): return tcry.xmr_hash_to_scalar(dt) -def hash_to_scalar_into(r: Sc25519, data: bytes, length: Optional[int] = None): +def hash_to_scalar_into(r: Sc25519, data: bytes, length: int | None = None): dt = data[:length] if length else data return tcry.xmr_hash_to_scalar(r, dt) @@ -289,7 +288,7 @@ def get_subaddress_secret_key( return tcry.xmr_get_subaddress_secret_key(major, minor, secret_key) -def generate_signature(data: bytes, priv: Sc25519) -> Tuple[Sc25519, Sc25519, Ge25519]: +def generate_signature(data: bytes, priv: Sc25519) -> tuple[Sc25519, Sc25519, Ge25519]: """ Generate EC signature crypto_ops::generate_signature(const hash &prefix_hash, const public_key &pub, const secret_key &sec, signature &sig) diff --git a/core/src/apps/monero/xmr/key_image.py b/core/src/apps/monero/xmr/key_image.py index 2432a5e38..78e58bf19 100644 --- a/core/src/apps/monero/xmr/key_image.py +++ b/core/src/apps/monero/xmr/key_image.py @@ -2,13 +2,12 @@ from apps.monero.xmr import crypto, monero from apps.monero.xmr.serialize.int_serialize import dump_uvarint_b if False: - from typing import List, Tuple, Optional, Dict from apps.monero.xmr.types import Ge25519, Sc25519 from apps.monero.xmr.credentials import AccountCreds from trezor.messages.MoneroTransferDetails import MoneroTransferDetails - Subaddresses = Dict[bytes, Tuple[int, int]] - Sig = List[List[Sc25519]] + Subaddresses = dict[bytes, tuple[int, int]] + Sig = list[list[Sc25519]] def compute_hash(rr: MoneroTransferDetails) -> bytes: @@ -24,7 +23,7 @@ def compute_hash(rr: MoneroTransferDetails) -> bytes: def export_key_image( creds: AccountCreds, subaddresses: Subaddresses, td: MoneroTransferDetails -) -> Tuple[Ge25519, Sig]: +) -> tuple[Ge25519, Sig]: out_key = crypto.decodepoint(td.out_key) tx_pub_key = crypto.decodepoint(td.tx_pub_key) @@ -57,12 +56,12 @@ def _export_key_image( subaddresses: Subaddresses, pkey: Ge25519, tx_pub_key: Ge25519, - additional_tx_pub_key: Optional[Ge25519], + additional_tx_pub_key: Ge25519 | None, out_idx: int, test: bool = True, sub_addr_major: int = None, sub_addr_minor: int = None, -) -> Tuple[Ge25519, Sig]: +) -> tuple[Ge25519, Sig]: """ Generates key image for the TXO + signature for the key image """ @@ -87,7 +86,7 @@ def _export_key_image( def generate_ring_signature( prefix_hash: bytes, image: Ge25519, - pubs: List[Ge25519], + pubs: list[Ge25519], sec: Sc25519, sec_idx: int, test: bool = False, diff --git a/core/src/apps/monero/xmr/mlsag.py b/core/src/apps/monero/xmr/mlsag.py index 03d50d800..e286e0339 100644 --- a/core/src/apps/monero/xmr/mlsag.py +++ b/core/src/apps/monero/xmr/mlsag.py @@ -48,12 +48,11 @@ from apps.monero.xmr import crypto from apps.monero.xmr.serialize import int_serialize if False: - from typing import List, Tuple from apps.monero.xmr.types import Ge25519, Sc25519 from apps.monero.xmr.serialize_messages.tx_ct_key import CtKey from trezor.messages.MoneroRctKeyPublic import MoneroRctKeyPublic - KeyM = List[List[bytes]] + KeyM = list[list[bytes]] _HASH_KEY_CLSAG_ROUND = b"CLSAG_round\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" @@ -63,13 +62,13 @@ _HASH_KEY_CLSAG_AGG_1 = b"CLSAG_agg_1\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 def generate_mlsag_simple( message: bytes, - pubs: List[MoneroRctKeyPublic], + pubs: list[MoneroRctKeyPublic], in_sk: CtKey, a: Sc25519, cout: Ge25519, index: int, - mg_buff: List[bytes], -) -> List[bytes]: + mg_buff: list[bytes], +) -> list[bytes]: """ MLSAG for RctType.Simple :param message: the full message to be signed (actually its hash) @@ -110,7 +109,7 @@ def generate_mlsag_simple( return generate_mlsag(message, M, sk, index, dsRows, mg_buff) -def gen_mlsag_assert(pk: KeyM, xx: List[Sc25519], index: int, dsRows: int): +def gen_mlsag_assert(pk: KeyM, xx: list[Sc25519], index: int, dsRows: int): """ Conditions check """ @@ -137,12 +136,12 @@ def gen_mlsag_assert(pk: KeyM, xx: List[Sc25519], index: int, dsRows: int): def generate_first_c_and_key_images( message: bytes, pk: KeyM, - xx: List[Sc25519], + xx: list[Sc25519], index: int, dsRows: int, rows: int, cols: int, -) -> Tuple[Sc25519, List[Ge25519], List[Ge25519]]: +) -> tuple[Sc25519, list[Ge25519], list[Ge25519]]: """ MLSAG computation - the part with secret keys :param message: the full message to be signed (actually its hash) @@ -197,11 +196,11 @@ def generate_first_c_and_key_images( def generate_mlsag( message: bytes, pk: KeyM, - xx: List[Sc25519], + xx: list[Sc25519], index: int, dsRows: int, - mg_buff: List[bytes], -) -> List[bytes]: + mg_buff: list[bytes], +) -> list[bytes]: """ Multilayered Spontaneous Anonymous Group Signatures (MLSAG signatures) @@ -298,13 +297,13 @@ def generate_mlsag( def generate_clsag_simple( message: bytes, - pubs: List[MoneroRctKeyPublic], + pubs: list[MoneroRctKeyPublic], in_sk: CtKey, a: Sc25519, cout: Ge25519, index: int, - mg_buff: List[bytes], -) -> List[bytes]: + mg_buff: list[bytes], +) -> list[bytes]: """ CLSAG for RctType.Simple https://eprint.iacr.org/2019/654.pdf @@ -341,14 +340,14 @@ def generate_clsag_simple( def _generate_clsag( message: bytes, - P: List[bytes], + P: list[bytes], p: Sc25519, - C_nonzero: List[bytes], + C_nonzero: list[bytes], z: Sc25519, Cout: Ge25519, index: int, - mg_buff: List[bytes], -) -> List[bytes]: + mg_buff: list[bytes], +) -> list[bytes]: sI = crypto.new_point() # sig.I sD = crypto.new_point() # sig.D sc1 = crypto.new_scalar() # sig.c1 diff --git a/core/src/apps/monero/xmr/mlsag_hasher.py b/core/src/apps/monero/xmr/mlsag_hasher.py index 91ef41b6e..39f51fb65 100644 --- a/core/src/apps/monero/xmr/mlsag_hasher.py +++ b/core/src/apps/monero/xmr/mlsag_hasher.py @@ -2,7 +2,6 @@ from apps.monero.xmr import crypto from apps.monero.xmr.keccak_hasher import KeccakXmrArchive if False: - from typing import List, Union from apps.monero.xmr.serialize_messages.tx_rsig_bulletproof import Bulletproof @@ -54,7 +53,7 @@ class PreMlsagHasher: self.kc_master.update(c_hash) self.rtcsig_hasher = None - def rsig_val(self, p: Union[bytes, List[bytes], Bulletproof], raw: bool = False): + def rsig_val(self, p: bytes | list[bytes] | Bulletproof, raw: bool = False): if self.state == 8: raise ValueError("State error") diff --git a/core/src/apps/monero/xmr/monero.py b/core/src/apps/monero/xmr/monero.py index 23654f671..7d646e813 100644 --- a/core/src/apps/monero/xmr/monero.py +++ b/core/src/apps/monero/xmr/monero.py @@ -1,11 +1,10 @@ from apps.monero.xmr import crypto if False: - from typing import List, Tuple, Optional, Dict from apps.monero.xmr.types import Ge25519, Sc25519 from apps.monero.xmr.credentials import AccountCreds - Subaddresses = Dict[bytes, Tuple[int, int]] + Subaddresses = dict[bytes, tuple[int, int]] class XmrException(Exception): @@ -70,7 +69,7 @@ def is_out_to_account( derivation: Ge25519, additional_derivation: Ge25519, output_index: int, - creds: Optional[AccountCreds] = None, + creds: AccountCreds | None = None, sub_addr_major: int = None, sub_addr_minor: int = None, ): @@ -125,8 +124,8 @@ def generate_tx_spend_and_key_image( out_key: Ge25519, recv_derivation: Ge25519, real_output_index: int, - received_index: Tuple[int, int], -) -> Optional[Tuple[Sc25519, Ge25519]]: + received_index: tuple[int, int], +) -> tuple[Sc25519, Ge25519] | None: """ Generates UTXO spending key and key image. Corresponds to generate_key_image_helper_precomp() in the Monero codebase. @@ -191,7 +190,7 @@ def generate_tx_spend_and_key_image_and_derivation( real_output_index: int, sub_addr_major: int = None, sub_addr_minor: int = None, -) -> Tuple[Sc25519, Ge25519, Ge25519]: +) -> tuple[Sc25519, Ge25519, Ge25519]: """ Generates UTXO spending key and key image and corresponding derivation. Supports subaddresses. @@ -239,8 +238,8 @@ def generate_tx_spend_and_key_image_and_derivation( def compute_subaddresses( creds: AccountCreds, account: int, - indices: List[int], - subaddresses: Optional[Subaddresses] = None, + indices: list[int], + subaddresses: Subaddresses | None = None, ) -> Subaddresses: """ Computes subaddress public spend key for receiving transactions. @@ -267,12 +266,12 @@ def compute_subaddresses( return subaddresses -def generate_keys(recovery_key: Sc25519) -> Tuple[Sc25519, Ge25519]: +def generate_keys(recovery_key: Sc25519) -> tuple[Sc25519, Ge25519]: pub = crypto.scalarmult_base(recovery_key) return recovery_key, pub -def generate_monero_keys(seed: bytes) -> Tuple[Sc25519, Ge25519, Sc25519, Ge25519]: +def generate_monero_keys(seed: bytes) -> tuple[Sc25519, Ge25519, Sc25519, Ge25519]: """ Generates spend key / view key from the seed in the same manner as Monero code does. @@ -287,7 +286,7 @@ def generate_monero_keys(seed: bytes) -> Tuple[Sc25519, Ge25519, Sc25519, Ge2551 def generate_sub_address_keys( view_sec: Sc25519, spend_pub: Ge25519, major: int, minor: int -) -> Tuple[Ge25519, Ge25519]: +) -> tuple[Ge25519, Ge25519]: if major == 0 and minor == 0: # special case, Monero-defined return spend_pub, crypto.scalarmult_base(view_sec) @@ -298,7 +297,7 @@ def generate_sub_address_keys( return D, C -def commitment_mask(key: bytes, buff: Optional[Sc25519] = None) -> Sc25519: +def commitment_mask(key: bytes, buff: Sc25519 | None = None) -> Sc25519: """ Generates deterministic commitment mask for Bulletproof2 """ diff --git a/core/src/apps/monero/xmr/range_signatures.py b/core/src/apps/monero/xmr/range_signatures.py index 819d44e52..3362e0703 100644 --- a/core/src/apps/monero/xmr/range_signatures.py +++ b/core/src/apps/monero/xmr/range_signatures.py @@ -13,12 +13,11 @@ import gc from apps.monero.xmr import crypto if False: - from typing import List from apps.monero.xmr.types import Sc25519 from apps.monero.xmr.serialize_messages.tx_rsig_bulletproof import Bulletproof -def prove_range_bp_batch(amounts: List[int], masks: List[Sc25519]) -> Bulletproof: +def prove_range_bp_batch(amounts: list[int], masks: list[Sc25519]) -> Bulletproof: """Calculates Bulletproof in batches""" from apps.monero.xmr import bulletproof as bp @@ -30,7 +29,7 @@ def prove_range_bp_batch(amounts: List[int], masks: List[Sc25519]) -> Bulletproo return bp_proof -def verify_bp(bp_proof: Bulletproof, amounts: List[int], masks: List[Sc25519]) -> bool: +def verify_bp(bp_proof: Bulletproof, amounts: list[int], masks: list[Sc25519]) -> bool: """Verifies Bulletproof""" from apps.monero.xmr import bulletproof as bp diff --git a/core/src/apps/webauthn/add_resident_credential.py b/core/src/apps/webauthn/add_resident_credential.py index 0bf2109a3..3972b6a15 100644 --- a/core/src/apps/webauthn/add_resident_credential.py +++ b/core/src/apps/webauthn/add_resident_credential.py @@ -10,9 +10,6 @@ from .confirm import ConfirmContent, ConfirmInfo from .credential import Fido2Credential from .resident_credentials import store_resident_credential -if False: - from typing import Optional - class ConfirmAddCredential(ConfirmInfo): def __init__(self, cred: Fido2Credential): @@ -26,7 +23,7 @@ class ConfirmAddCredential(ConfirmInfo): def app_name(self) -> str: return self._cred.app_name() - def account_name(self) -> Optional[str]: + def account_name(self) -> str | None: return self._cred.account_name() diff --git a/core/src/apps/webauthn/confirm.py b/core/src/apps/webauthn/confirm.py index 7381e85d4..416d9a295 100644 --- a/core/src/apps/webauthn/confirm.py +++ b/core/src/apps/webauthn/confirm.py @@ -1,16 +1,12 @@ from trezor import ui from trezor.ui.components.tt.text import text_center_trim_left, text_center_trim_right -if False: - from typing import Optional - - DEFAULT_ICON = "apps/webauthn/res/icon_webauthn.toif" class ConfirmInfo: def __init__(self) -> None: - self.app_icon: Optional[bytes] = None + self.app_icon: bytes | None = None def get_header(self) -> str: raise NotImplementedError @@ -18,7 +14,7 @@ class ConfirmInfo: def app_name(self) -> str: raise NotImplementedError - def account_name(self) -> Optional[str]: + def account_name(self) -> str | None: return None def load_icon(self, rp_id_hash: bytes) -> None: diff --git a/core/src/apps/webauthn/credential.py b/core/src/apps/webauthn/credential.py index 103496219..6c91b8ca0 100644 --- a/core/src/apps/webauthn/credential.py +++ b/core/src/apps/webauthn/credential.py @@ -12,7 +12,7 @@ from apps.common import HARDENED, cbor, seed from . import common if False: - from typing import Iterable, Optional + from typing import Iterable # Credential ID values _CRED_ID_VERSION = b"\xf1\xd0\x02\x00" @@ -55,11 +55,11 @@ _U2F_KEY_PATH = const(0x8055_3246) class Credential: def __init__(self) -> None: - self.index: Optional[int] = None + self.index: int | None = None self.id: bytes = b"" self.rp_id: str = "" self.rp_id_hash: bytes = b"" - self.user_id: Optional[bytes] = None + self.user_id: bytes | None = None def __lt__(self, other: "Credential") -> bool: raise NotImplementedError @@ -67,7 +67,7 @@ class Credential: def app_name(self) -> str: raise NotImplementedError - def account_name(self) -> Optional[str]: + def account_name(self) -> str | None: return None def public_key(self) -> bytes: @@ -89,7 +89,7 @@ class Credential: def bogus_signature(self) -> bytes: raise NotImplementedError - def hmac_secret_key(self) -> Optional[bytes]: + def hmac_secret_key(self) -> bytes | None: return None def next_signature_counter(self) -> int: @@ -111,9 +111,9 @@ class Fido2Credential(Credential): def __init__(self) -> None: super().__init__() - self.rp_name: Optional[str] = None - self.user_name: Optional[str] = None - self.user_display_name: Optional[str] = None + self.rp_name: str | None = None + self.user_name: str | None = None + self.user_display_name: str | None = None self.creation_time: int = 0 self.hmac_secret: bool = False self.use_sign_count: bool = False @@ -168,7 +168,7 @@ class Fido2Credential(Credential): @classmethod def from_cred_id( - cls, cred_id: bytes, rp_id_hash: Optional[bytes] + cls, cred_id: bytes, rp_id_hash: bytes | None ) -> "Fido2Credential": if len(cred_id) < CRED_ID_MIN_LENGTH or cred_id[0:4] != _CRED_ID_VERSION: raise ValueError # invalid length or version @@ -271,7 +271,7 @@ class Fido2Credential(Credential): return self.rp_id - def account_name(self) -> Optional[str]: + def account_name(self) -> str | None: if self.user_name: return self.user_name elif self.user_display_name: @@ -342,7 +342,7 @@ class Fido2Credential(Credential): raise TypeError - def hmac_secret_key(self) -> Optional[bytes]: + def hmac_secret_key(self) -> bytes | None: # Returns the symmetric key for the hmac-secret extension also known as CredRandom. if not self.hmac_secret: @@ -363,7 +363,7 @@ class Fido2Credential(Credential): class U2fCredential(Credential): def __init__(self) -> None: super().__init__() - self.node: Optional[bip32.HDNode] = None + self.node: bip32.HDNode | None = None def __lt__(self, other: "Credential") -> bool: # Sort U2F credentials after FIDO2 credentials. @@ -441,7 +441,7 @@ class U2fCredential(Credential): @staticmethod def _node_from_key_handle( rp_id_hash: bytes, keyhandle: bytes, pathformat: str - ) -> Optional[bip32.HDNode]: + ) -> bip32.HDNode | None: # unpack the keypath from the first half of keyhandle keypath = keyhandle[:32] path = ustruct.unpack(pathformat, keypath) diff --git a/core/src/apps/webauthn/fido2.py b/core/src/apps/webauthn/fido2.py index b4478ff88..f4970a04d 100644 --- a/core/src/apps/webauthn/fido2.py +++ b/core/src/apps/webauthn/fido2.py @@ -32,10 +32,6 @@ if False: Coroutine, Iterable, Iterator, - List, - Optional, - Tuple, - Union, ) _CID_BROADCAST = const(0xFFFF_FFFF) # broadcast channel id @@ -350,7 +346,7 @@ def overlay_struct(buf: bytearray, desc: dict) -> Any: return uctypes.struct(uctypes.addressof(buf), desc, uctypes.BIG_ENDIAN) -def make_struct(desc: dict) -> Tuple[bytearray, Any]: +def make_struct(desc: dict) -> tuple[bytearray, Any]: desc_size = uctypes.sizeof(desc, uctypes.BIG_ENDIAN) # type: ignore buf = bytearray(desc_size) return buf, uctypes.struct(uctypes.addressof(buf), desc, uctypes.BIG_ENDIAN) @@ -389,7 +385,7 @@ class Cmd: return Msg(self.cid, cla, ins, p1, p2, lc, data) -async def read_cmd(iface: io.HID) -> Optional[Cmd]: +async def read_cmd(iface: io.HID) -> Cmd | None: desc_init = frame_init() desc_cont = frame_cont() read = loop.wait(iface.iface_num() | io.POLL_READ) @@ -568,7 +564,7 @@ async def handle_reports(iface: io.HID) -> None: dialog_mgr.get_cid(), _CID_BROADCAST, ): - resp: Optional[Cmd] = cmd_error(req.cid, _ERR_CHANNEL_BUSY) + resp: Cmd | None = cmd_error(req.cid, _ERR_CHANNEL_BUSY) else: resp = dispatch_cmd(req, dialog_mgr) if resp is not None: @@ -624,7 +620,7 @@ class State: def timeout_ms(self) -> int: raise NotImplementedError - async def confirm_dialog(self) -> Union[bool, "State"]: + async def confirm_dialog(self) -> bool | "State": pass async def on_confirm(self) -> None: @@ -656,7 +652,7 @@ class U2fState(State, ConfirmInfo): def app_name(self) -> str: return self._cred.app_name() - def account_name(self) -> Optional[str]: + def account_name(self) -> str | None: return self._cred.account_name() @@ -769,17 +765,17 @@ class Fido2State(State): class Fido2Unlock(Fido2State): def __init__( self, - process_func: Callable[[Cmd, "DialogManager"], Union[State, Cmd]], + process_func: Callable[[Cmd, "DialogManager"], State | Cmd], req: Cmd, dialog_mgr: "DialogManager", ) -> None: super().__init__(req.cid, dialog_mgr.iface) self.process_func = process_func self.req = req - self.resp: Optional[Cmd] = None + self.resp: Cmd | None = None self.dialog_mgr = dialog_mgr - async def confirm_dialog(self) -> Union[bool, "State"]: + async def confirm_dialog(self) -> bool | "State": if not await verify_user(KeepaliveCallback(self.cid, self.iface)): return False @@ -820,7 +816,7 @@ class Fido2ConfirmMakeCredential(Fido2State, ConfirmInfo): def app_name(self) -> str: return self._cred.app_name() - def account_name(self) -> Optional[str]: + def account_name(self) -> str | None: return self._cred.account_name() async def confirm_dialog(self) -> bool: @@ -871,8 +867,8 @@ class Fido2ConfirmGetAssertion(Fido2State, ConfirmInfo, Pageable): cid: int, iface: io.HID, client_data_hash: bytes, - creds: List[Credential], - hmac_secret: Optional[dict], + creds: list[Credential], + hmac_secret: dict | None, resident: bool, user_verification: bool, ) -> None: @@ -892,7 +888,7 @@ class Fido2ConfirmGetAssertion(Fido2State, ConfirmInfo, Pageable): def app_name(self) -> str: return self._creds[self.page()].app_name() - def account_name(self) -> Optional[str]: + def account_name(self) -> str | None: return self._creds[self.page()].account_name() def page_count(self) -> int: @@ -997,11 +993,11 @@ class DialogManager: self._clear() def _clear(self) -> None: - self.state: Optional[State] = None + self.state: State | None = None self.deadline = 0 self.result = _RESULT_NONE - self.workflow: Optional[loop.spawn] = None - self.keepalive: Optional[Coroutine] = None + self.workflow: loop.spawn | None = None + self.keepalive: Coroutine | None = None def _workflow_is_running(self) -> bool: return self.workflow is not None and not self.workflow.finished @@ -1094,7 +1090,7 @@ class DialogManager: await self.state.on_decline() -def dispatch_cmd(req: Cmd, dialog_mgr: DialogManager) -> Optional[Cmd]: +def dispatch_cmd(req: Cmd, dialog_mgr: DialogManager) -> Cmd | None: if req.cmd == _CMD_MSG: try: m = req.to_msg() @@ -1409,7 +1405,7 @@ def cbor_error(cid: int, code: int) -> Cmd: def credentials_from_descriptor_list( - descriptor_list: List[dict], rp_id_hash: bytes + descriptor_list: list[dict], rp_id_hash: bytes ) -> Iterator[Credential]: for credential_descriptor in descriptor_list: credential_type = credential_descriptor["type"] @@ -1429,10 +1425,10 @@ def credentials_from_descriptor_list( yield cred -def distinguishable_cred_list(credentials: Iterable[Credential]) -> List[Credential]: +def distinguishable_cred_list(credentials: Iterable[Credential]) -> list[Credential]: """Reduces the input to a list of credentials which can be distinguished by the user. It is assumed that all input credentials share the same RP ID.""" - cred_list: List[Credential] = [] + cred_list: list[Credential] = [] for cred in credentials: for i, prev_cred in enumerate(cred_list): if prev_cred.account_name() == cred.account_name(): @@ -1446,7 +1442,7 @@ def distinguishable_cred_list(credentials: Iterable[Credential]) -> List[Credent return cred_list -def algorithms_from_pub_key_cred_params(pub_key_cred_params: List[dict]) -> List[int]: +def algorithms_from_pub_key_cred_params(pub_key_cred_params: list[dict]) -> list[int]: alg_list = [] for pkcp in pub_key_cred_params: pub_key_cred_type = pkcp["type"] @@ -1462,7 +1458,7 @@ def algorithms_from_pub_key_cred_params(pub_key_cred_params: List[dict]) -> List return alg_list -def cbor_make_credential(req: Cmd, dialog_mgr: DialogManager) -> Optional[Cmd]: +def cbor_make_credential(req: Cmd, dialog_mgr: DialogManager) -> Cmd | None: if config.is_unlocked(): resp = cbor_make_credential_process(req, dialog_mgr) else: @@ -1477,9 +1473,7 @@ def cbor_make_credential(req: Cmd, dialog_mgr: DialogManager) -> Optional[Cmd]: return resp -def cbor_make_credential_process( - req: Cmd, dialog_mgr: DialogManager -) -> Union[State, Cmd]: +def cbor_make_credential_process(req: Cmd, dialog_mgr: DialogManager) -> State | Cmd: from . import knownapps if not storage.device.is_initialized(): @@ -1644,7 +1638,7 @@ def cbor_make_credential_sign( ) -def cbor_get_assertion(req: Cmd, dialog_mgr: DialogManager) -> Optional[Cmd]: +def cbor_get_assertion(req: Cmd, dialog_mgr: DialogManager) -> Cmd | None: if config.is_unlocked(): resp = cbor_get_assertion_process(req, dialog_mgr) else: @@ -1659,9 +1653,7 @@ def cbor_get_assertion(req: Cmd, dialog_mgr: DialogManager) -> Optional[Cmd]: return resp -def cbor_get_assertion_process( - req: Cmd, dialog_mgr: DialogManager -) -> Union[State, Cmd]: +def cbor_get_assertion_process(req: Cmd, dialog_mgr: DialogManager) -> State | Cmd: if not storage.device.is_initialized(): if __debug__: log.warning(__name__, "not initialized") @@ -1766,9 +1758,7 @@ def cbor_get_assertion_process( ) -def cbor_get_assertion_hmac_secret( - cred: Credential, hmac_secret: dict -) -> Optional[bytes]: +def cbor_get_assertion_hmac_secret(cred: Credential, hmac_secret: dict) -> bytes | None: 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, # because there is currently no valid value which describes the actual key agreement algorithm. @@ -1819,7 +1809,7 @@ def cbor_get_assertion_sign( client_data_hash: bytes, rp_id_hash: bytes, cred: Credential, - hmac_secret: Optional[dict], + hmac_secret: dict | None, resident: bool, user_presence: bool, user_verification: bool, @@ -1922,7 +1912,7 @@ def cbor_client_pin(req: Cmd) -> Cmd: return Cmd(req.cid, _CMD_CBOR, bytes([_ERR_NONE]) + cbor.encode(response_data)) -def cbor_reset(req: Cmd, dialog_mgr: DialogManager) -> Optional[Cmd]: +def cbor_reset(req: Cmd, dialog_mgr: DialogManager) -> Cmd | None: if not storage.device.is_initialized(): if __debug__: log.warning(__name__, "not initialized") diff --git a/core/src/apps/webauthn/knownapps.py b/core/src/apps/webauthn/knownapps.py index 0704dcc05..e00241e69 100644 --- a/core/src/apps/webauthn/knownapps.py +++ b/core/src/apps/webauthn/knownapps.py @@ -3,17 +3,13 @@ # flake8: noqa -if False: - from typing import Optional - - class FIDOApp: def __init__( self, label: str, - icon: Optional[str], - use_sign_count: Optional[bool], - use_self_attestation: Optional[bool], + icon: str | None, + use_sign_count: bool | None, + use_self_attestation: bool | None, ) -> None: self.label = label self.icon = icon @@ -22,7 +18,7 @@ class FIDOApp: # fmt: off -def by_rp_id_hash(rp_id_hash: bytes) -> Optional[FIDOApp]: +def by_rp_id_hash(rp_id_hash: bytes) -> FIDOApp | None: if False: raise RuntimeError # if false elif rp_id_hash == b"\x96\x89\x78\xa2\x99\x53\xde\x52\xd3\xef\x0f\x0c\x71\xb7\xb7\xb6\xb1\xaf\x9f\x08\xe2\x57\x89\x6a\x8d\x81\x26\x91\x85\x30\x29\x3b": diff --git a/core/src/apps/webauthn/knownapps.py.mako b/core/src/apps/webauthn/knownapps.py.mako index 2bf85eb32..81aa68a2d 100644 --- a/core/src/apps/webauthn/knownapps.py.mako +++ b/core/src/apps/webauthn/knownapps.py.mako @@ -3,17 +3,13 @@ # flake8: noqa -if False: - from typing import Optional - - class FIDOApp: def __init__( self, label: str, - icon: Optional[str], - use_sign_count: Optional[bool], - use_self_attestation: Optional[bool], + icon: str | None, + use_sign_count: bool | None, + use_self_attestation: bool | None, ) -> None: self.label = label self.icon = icon @@ -37,7 +33,7 @@ for app in fido: app.icon_res = None %>\ # fmt: off -def by_rp_id_hash(rp_id_hash: bytes) -> Optional[FIDOApp]: +def by_rp_id_hash(rp_id_hash: bytes) -> FIDOApp | None: if False: raise RuntimeError # if false % for label, rp_id_hash, type, app in fido_entries: diff --git a/core/src/apps/webauthn/remove_resident_credential.py b/core/src/apps/webauthn/remove_resident_credential.py index 4f24b331b..c3c75bda3 100644 --- a/core/src/apps/webauthn/remove_resident_credential.py +++ b/core/src/apps/webauthn/remove_resident_credential.py @@ -12,9 +12,6 @@ from .confirm import ConfirmContent, ConfirmInfo from .credential import Fido2Credential from .resident_credentials import get_resident_credential -if False: - from typing import Optional - class ConfirmRemoveCredential(ConfirmInfo): def __init__(self, cred: Fido2Credential): @@ -28,7 +25,7 @@ class ConfirmRemoveCredential(ConfirmInfo): def app_name(self) -> str: return self._cred.app_name() - def account_name(self) -> Optional[str]: + def account_name(self) -> str | None: return self._cred.account_name() diff --git a/core/src/apps/webauthn/resident_credentials.py b/core/src/apps/webauthn/resident_credentials.py index 3f04804cb..8ff6a19ae 100644 --- a/core/src/apps/webauthn/resident_credentials.py +++ b/core/src/apps/webauthn/resident_credentials.py @@ -6,7 +6,7 @@ from storage.resident_credentials import MAX_RESIDENT_CREDENTIALS from .credential import Fido2Credential if False: - from typing import Iterator, Optional + from typing import Iterator RP_ID_HASH_LENGTH = const(32) @@ -42,7 +42,7 @@ def find_by_rp_id_hash(rp_id_hash: bytes) -> Iterator[Fido2Credential]: yield _credential_from_data(index, data) -def get_resident_credential(index: int) -> Optional[Fido2Credential]: +def get_resident_credential(index: int) -> Fido2Credential | None: if not (0 <= index < MAX_RESIDENT_CREDENTIALS): return None diff --git a/core/src/protobuf.py b/core/src/protobuf.py index 9cb0caba5..c8e3919a1 100644 --- a/core/src/protobuf.py +++ b/core/src/protobuf.py @@ -7,12 +7,7 @@ if False: from typing import ( Any, Callable, - Dict, Iterable, - List, - Optional, - Tuple, - Type, TypeVar, Union, ) @@ -192,26 +187,26 @@ FLAG_EXPERIMENTAL = object() if False: MessageTypeDef = Union[ - Type[UVarintType], - Type[SVarintType], - Type[BoolType], + type[UVarintType], + type[SVarintType], + type[BoolType], EnumType, - Type[BytesType], - Type[UnicodeType], - Type[MessageType], + type[BytesType], + type[UnicodeType], + type[MessageType], ] - FieldDef = Tuple[str, MessageTypeDef, Any] - FieldDict = Dict[int, FieldDef] + FieldDef = tuple[str, MessageTypeDef, Any] + FieldDict = dict[int, FieldDef] - FieldCache = Dict[Type[MessageType], FieldDict] + FieldCache = dict[type[MessageType], FieldDict] LoadedMessageType = TypeVar("LoadedMessageType", bound=MessageType) def load_message( reader: Reader, - msg_type: Type[LoadedMessageType], - field_cache: Optional[FieldCache] = None, + msg_type: type[LoadedMessageType], + field_cache: FieldCache | None = None, experimental_enabled: bool = True, ) -> LoadedMessageType: if field_cache is None: @@ -236,7 +231,7 @@ def load_message( if False: SingularValue = Union[int, bool, bytearray, str, MessageType] - Value = Union[SingularValue, List[SingularValue]] + Value = Union[SingularValue, list[SingularValue]] fvalue: Value = 0 while True: @@ -306,7 +301,7 @@ def load_message( def dump_message( - writer: Writer, msg: MessageType, field_cache: Optional[FieldCache] = None + writer: Writer, msg: MessageType, field_cache: FieldCache | None = None ) -> None: repvalue = [0] @@ -371,7 +366,7 @@ def dump_message( raise TypeError -def count_message(msg: MessageType, field_cache: Optional[FieldCache] = None) -> int: +def count_message(msg: MessageType, field_cache: FieldCache | None = None) -> int: nbytes = 0 repvalue = [0] @@ -441,7 +436,7 @@ def count_message(msg: MessageType, field_cache: Optional[FieldCache] = None) -> return nbytes -def _count_bytes_list(svalue: List[bytes]) -> int: +def _count_bytes_list(svalue: list[bytes]) -> int: res = 0 for x in svalue: res += len(x) diff --git a/core/src/storage/cache.py b/core/src/storage/cache.py index 3234325d1..c1f39f70c 100644 --- a/core/src/storage/cache.py +++ b/core/src/storage/cache.py @@ -2,7 +2,7 @@ from trezor import wire from trezor.crypto import random if False: - from typing import Optional, Dict, List, Any + from typing import Any _MAX_SESSIONS_COUNT = 10 _SESSIONLESS_FLAG = 128 @@ -18,10 +18,10 @@ APP_COMMON_SEED_WITHOUT_PASSPHRASE = 1 | _SESSIONLESS_FLAG APP_COMMON_SAFETY_CHECKS_TEMPORARY = 2 | _SESSIONLESS_FLAG -_active_session_id: Optional[bytes] = None -_caches: Dict[bytes, Dict[int, Any]] = {} -_session_ids: List[bytes] = [] -_sessionless_cache: Dict[int, Any] = {} +_active_session_id: bytes | None = None +_caches: dict[bytes, dict[int, Any]] = {} +_session_ids: list[bytes] = [] +_sessionless_cache: dict[int, Any] = {} if False: from typing import Any, Callable, TypeVar @@ -41,7 +41,7 @@ def _move_session_ids_queue(session_id: bytes) -> None: _session_ids.insert(0, session_id) -def start_session(received_session_id: Optional[bytes] = None) -> bytes: +def start_session(received_session_id: bytes | None = None) -> bytes: if received_session_id and received_session_id in _session_ids: session_id = received_session_id else: diff --git a/core/src/storage/common.py b/core/src/storage/common.py index 2d6e746b4..ba6c4b89e 100644 --- a/core/src/storage/common.py +++ b/core/src/storage/common.py @@ -2,9 +2,6 @@ from micropython import const from trezor import config -if False: - from typing import Optional - # Namespaces: # fmt: off APP_DEVICE = const(0x01) @@ -24,7 +21,7 @@ def set(app: int, key: int, data: bytes, public: bool = False) -> None: config.set(app, key, data, public) -def get(app: int, key: int, public: bool = False) -> Optional[bytes]: +def get(app: int, key: int, public: bool = False) -> bytes | None: return config.get(app, key, public) @@ -56,7 +53,7 @@ def set_uint8(app: int, key: int, val: int) -> None: set(app, key, val.to_bytes(1, "big")) -def get_uint8(app: int, key: int) -> Optional[int]: +def get_uint8(app: int, key: int) -> int | None: val = get(app, key) if not val: return None @@ -67,7 +64,7 @@ def set_uint16(app: int, key: int, val: int) -> None: set(app, key, val.to_bytes(2, "big")) -def get_uint16(app: int, key: int) -> Optional[int]: +def get_uint16(app: int, key: int) -> int | None: val = get(app, key) if not val: return None diff --git a/core/src/storage/device.py b/core/src/storage/device.py index 1e3bc4fd4..50dea0855 100644 --- a/core/src/storage/device.py +++ b/core/src/storage/device.py @@ -7,7 +7,6 @@ from trezor.messages import BackupType if False: from trezor.messages.ResetDevice import EnumTypeBackupType - from typing import Optional from typing_extensions import Literal # Namespace: @@ -67,7 +66,7 @@ def is_version_stored() -> bool: return bool(common.get(_NAMESPACE, _VERSION)) -def get_version() -> Optional[bytes]: +def get_version() -> bytes | None: return common.get(_NAMESPACE, _VERSION) @@ -104,7 +103,7 @@ def set_rotation(value: int) -> None: common.set(_NAMESPACE, _ROTATION, value.to_bytes(2, "big"), True) # public -def get_label() -> Optional[str]: +def get_label() -> str | None: label = common.get(_NAMESPACE, _LABEL, True) # public if label is None: return None @@ -117,7 +116,7 @@ def set_label(label: str) -> None: common.set(_NAMESPACE, _LABEL, label.encode(), True) # public -def get_mnemonic_secret() -> Optional[bytes]: +def get_mnemonic_secret() -> bytes | None: return common.get(_NAMESPACE, _MNEMONIC_SECRET) @@ -146,7 +145,7 @@ def set_passphrase_enabled(enable: bool) -> None: set_passphrase_always_on_device(False) -def get_homescreen() -> Optional[bytes]: +def get_homescreen() -> bytes | None: return common.get(_NAMESPACE, _HOMESCREEN, public=True) @@ -260,7 +259,7 @@ def set_slip39_identifier(identifier: int) -> None: common.set_uint16(_NAMESPACE, _SLIP39_IDENTIFIER, identifier) -def get_slip39_identifier() -> Optional[int]: +def get_slip39_identifier() -> int | None: """The device's actual SLIP-39 identifier used in passphrase derivation.""" return common.get_uint16(_NAMESPACE, _SLIP39_IDENTIFIER) @@ -274,14 +273,14 @@ def set_slip39_iteration_exponent(exponent: int) -> None: common.set_uint8(_NAMESPACE, _SLIP39_ITERATION_EXPONENT, exponent) -def get_slip39_iteration_exponent() -> Optional[int]: +def get_slip39_iteration_exponent() -> int | None: """ The device's actual SLIP-39 iteration exponent used in passphrase derivation. """ return common.get_uint8(_NAMESPACE, _SLIP39_ITERATION_EXPONENT) -def get_sd_salt_auth_key() -> Optional[bytes]: +def get_sd_salt_auth_key() -> bytes | None: """ The key used to check the authenticity of the SD card salt. """ @@ -291,7 +290,7 @@ def get_sd_salt_auth_key() -> Optional[bytes]: return auth_key -def set_sd_salt_auth_key(auth_key: Optional[bytes]) -> None: +def set_sd_salt_auth_key(auth_key: bytes | None) -> None: """ The key used to check the authenticity of the SD card salt. """ diff --git a/core/src/storage/recovery.py b/core/src/storage/recovery.py index 71dc58cd1..bac8a7fe0 100644 --- a/core/src/storage/recovery.py +++ b/core/src/storage/recovery.py @@ -24,10 +24,6 @@ _SLIP39_GROUP_COUNT = const(0x07) # int _DEFAULT_SLIP39_GROUP_COUNT = const(1) -if False: - from typing import List, Optional - - def _require_progress() -> None: if not is_in_progress(): raise RuntimeError @@ -56,7 +52,7 @@ def set_slip39_identifier(identifier: int) -> None: common.set_uint16(_NAMESPACE, _SLIP39_IDENTIFIER, identifier) -def get_slip39_identifier() -> Optional[int]: +def get_slip39_identifier() -> int | None: _require_progress() return common.get_uint16(_NAMESPACE, _SLIP39_IDENTIFIER) @@ -66,7 +62,7 @@ def set_slip39_iteration_exponent(exponent: int) -> None: common.set_uint8(_NAMESPACE, _SLIP39_ITERATION_EXPONENT, exponent) -def get_slip39_iteration_exponent() -> Optional[int]: +def get_slip39_iteration_exponent() -> int | None: _require_progress() return common.get_uint8(_NAMESPACE, _SLIP39_ITERATION_EXPONENT) @@ -102,7 +98,7 @@ def set_slip39_remaining_shares(shares_remaining: int, group_index: int) -> None common.set(_NAMESPACE, _REMAINING, remaining) -def get_slip39_remaining_shares(group_index: int) -> Optional[int]: +def get_slip39_remaining_shares(group_index: int) -> int | None: _require_progress() remaining = common.get(_NAMESPACE, _REMAINING) if remaining is None or remaining[group_index] == slip39.MAX_SHARE_COUNT: @@ -111,7 +107,7 @@ def get_slip39_remaining_shares(group_index: int) -> Optional[int]: return remaining[group_index] -def fetch_slip39_remaining_shares() -> Optional[List[int]]: +def fetch_slip39_remaining_shares() -> list[int] | None: _require_progress() remaining = common.get(_NAMESPACE, _REMAINING) if not remaining: diff --git a/core/src/storage/recovery_shares.py b/core/src/storage/recovery_shares.py index 5469246f8..5930b940d 100644 --- a/core/src/storage/recovery_shares.py +++ b/core/src/storage/recovery_shares.py @@ -1,9 +1,6 @@ from storage import common from trezor.crypto import slip39 -if False: - from typing import List, Optional - # Mnemonics stored during SLIP-39 recovery process. # Each mnemonic is stored under key = index. @@ -16,7 +13,7 @@ def set(index: int, group_index: int, mnemonic: str) -> None: ) -def get(index: int, group_index: int) -> Optional[str]: +def get(index: int, group_index: int) -> str | None: m = common.get( common.APP_RECOVERY_SHARES, index + group_index * slip39.MAX_SHARE_COUNT ) @@ -25,7 +22,7 @@ def get(index: int, group_index: int) -> Optional[str]: return None -def fetch_group(group_index: int) -> List[str]: +def fetch_group(group_index: int) -> list[str]: mnemonics = [] for index in range(slip39.MAX_SHARE_COUNT): m = get(index, group_index) diff --git a/core/src/storage/resident_credentials.py b/core/src/storage/resident_credentials.py index 4e7952941..9484f1e4b 100644 --- a/core/src/storage/resident_credentials.py +++ b/core/src/storage/resident_credentials.py @@ -2,16 +2,12 @@ from micropython import const from storage import common -if False: - from typing import Optional - - _RESIDENT_CREDENTIAL_START_KEY = const(1) MAX_RESIDENT_CREDENTIALS = const(100) -def get(index: int) -> Optional[bytes]: +def get(index: int) -> bytes | None: if not (0 <= index < MAX_RESIDENT_CREDENTIALS): raise ValueError # invalid credential index diff --git a/core/src/storage/sd_salt.py b/core/src/storage/sd_salt.py index 234c5e210..b3539fcb3 100644 --- a/core/src/storage/sd_salt.py +++ b/core/src/storage/sd_salt.py @@ -7,7 +7,7 @@ from trezor.sdcard import with_filesystem from trezor.utils import consteq if False: - from typing import Optional, TypeVar, Callable + from typing import TypeVar, Callable T = TypeVar("T", bound=Callable) @@ -38,7 +38,7 @@ def _get_salt_path(new: bool = False) -> str: @with_filesystem -def _load_salt(auth_key: bytes, path: str) -> Optional[bytearray]: +def _load_salt(auth_key: bytes, path: str) -> bytearray | None: # Load the salt file if it exists. try: with fatfs.open(path, "r") as f: @@ -58,7 +58,7 @@ def _load_salt(auth_key: bytes, path: str) -> Optional[bytearray]: @with_filesystem -def load_sd_salt() -> Optional[bytearray]: +def load_sd_salt() -> bytearray | None: salt_auth_key = storage.device.get_sd_salt_auth_key() if salt_auth_key is None: return None diff --git a/core/src/trezor/crypto/bech32.py b/core/src/trezor/crypto/bech32.py index 4ec0c08d4..9c1ab08f9 100644 --- a/core/src/trezor/crypto/bech32.py +++ b/core/src/trezor/crypto/bech32.py @@ -21,18 +21,18 @@ """Reference implementation for Bech32 and segwit addresses.""" if False: - from typing import Iterable, List, Optional, Tuple, Union, TypeVar + from typing import Iterable, Union, TypeVar A = TypeVar("A") B = TypeVar("B") - # usage: OptionalTuple[int, List[int]] is either (None, None) or (someint, somelist) + # usage: OptionalTuple[int, list[int]] is either (None, None) or (someint, somelist) # but not (None, somelist) - OptionalTuple = Union[Tuple[None, None], Tuple[A, B]] + OptionalTuple = Union[tuple[None, None], tuple[A, B]] CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" -def bech32_polymod(values: List[int]) -> int: +def bech32_polymod(values: list[int]) -> int: """Internal function that computes the Bech32 checksum.""" generator = [0x3B6A_57B2, 0x2650_8E6D, 0x1EA1_19FA, 0x3D42_33DD, 0x2A14_62B3] chk = 1 @@ -44,30 +44,30 @@ def bech32_polymod(values: List[int]) -> int: return chk -def bech32_hrp_expand(hrp: str) -> List[int]: +def bech32_hrp_expand(hrp: str) -> list[int]: """Expand the HRP into values for checksum computation.""" return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp] -def bech32_verify_checksum(hrp: str, data: List[int]) -> bool: +def bech32_verify_checksum(hrp: str, data: list[int]) -> bool: """Verify a checksum given HRP and converted data characters.""" return bech32_polymod(bech32_hrp_expand(hrp) + data) == 1 -def bech32_create_checksum(hrp: str, data: List[int]) -> List[int]: +def bech32_create_checksum(hrp: str, data: list[int]) -> list[int]: """Compute the checksum values given HRP and data.""" values = bech32_hrp_expand(hrp) + data polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1 return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)] -def bech32_encode(hrp: str, data: List[int]) -> str: +def bech32_encode(hrp: str, data: list[int]) -> str: """Compute a Bech32 string given HRP and data values.""" combined = data + bech32_create_checksum(hrp, data) return hrp + "1" + "".join([CHARSET[d] for d in combined]) -def bech32_decode(bech: str, max_bech_len: int = 90) -> OptionalTuple[str, List[int]]: +def bech32_decode(bech: str, max_bech_len: int = 90) -> OptionalTuple[str, list[int]]: """Validate a Bech32 string, and determine HRP and data.""" if (any(ord(x) < 33 or ord(x) > 126 for x in bech)) or ( bech.lower() != bech and bech.upper() != bech @@ -88,7 +88,7 @@ def bech32_decode(bech: str, max_bech_len: int = 90) -> OptionalTuple[str, List[ def convertbits( data: Iterable[int], frombits: int, tobits: int, pad: bool = True -) -> Optional[List[int]]: +) -> list[int] | None: """General power-of-2 base conversion.""" acc = 0 bits = 0 @@ -111,7 +111,7 @@ def convertbits( return ret -def decode(hrp: str, addr: str) -> OptionalTuple[int, List[int]]: +def decode(hrp: str, addr: str) -> OptionalTuple[int, list[int]]: """Decode a segwit address.""" hrpgot, data = bech32_decode(addr) if data is None or hrpgot != hrp: @@ -126,7 +126,7 @@ def decode(hrp: str, addr: str) -> OptionalTuple[int, List[int]]: return (data[0], decoded) -def encode(hrp: str, witver: int, witprog: Iterable[int]) -> Optional[str]: +def encode(hrp: str, witver: int, witprog: Iterable[int]) -> str | None: """Encode a segwit address.""" data = convertbits(witprog, 8, 5) if data is None: diff --git a/core/src/trezor/crypto/cashaddr.py b/core/src/trezor/crypto/cashaddr.py index abdb4f226..2e02498d6 100644 --- a/core/src/trezor/crypto/cashaddr.py +++ b/core/src/trezor/crypto/cashaddr.py @@ -21,14 +21,14 @@ # THE SOFTWARE. if False: - from typing import Iterable, List, Tuple + from typing import Iterable CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" ADDRESS_TYPE_P2KH = 0 ADDRESS_TYPE_P2SH = 8 -def cashaddr_polymod(values: List[int]) -> int: +def cashaddr_polymod(values: list[int]) -> int: generator = [ 0x98_F2BC_8E61, 0x79_B76D_99E2, @@ -45,11 +45,11 @@ def cashaddr_polymod(values: List[int]) -> int: return chk ^ 1 -def prefix_expand(prefix: str) -> List[int]: +def prefix_expand(prefix: str) -> list[int]: return [ord(x) & 0x1F for x in prefix] + [0] -def calculate_checksum(prefix: str, payload: List[int]) -> List[int]: +def calculate_checksum(prefix: str, payload: list[int]) -> list[int]: poly = cashaddr_polymod(prefix_expand(prefix) + payload + [0, 0, 0, 0, 0, 0, 0, 0]) out = list() for i in range(8): @@ -57,18 +57,18 @@ def calculate_checksum(prefix: str, payload: List[int]) -> List[int]: return out -def verify_checksum(prefix: str, payload: List[int]) -> bool: +def verify_checksum(prefix: str, payload: list[int]) -> bool: return cashaddr_polymod(prefix_expand(prefix) + payload) == 0 -def b32decode(inputs: str) -> List[int]: +def b32decode(inputs: str) -> list[int]: out = list() for letter in inputs: out.append(CHARSET.find(letter)) return out -def b32encode(inputs: List[int]) -> str: +def b32encode(inputs: list[int]) -> str: out = "" for char_code in inputs: out += CHARSET[char_code] @@ -77,7 +77,7 @@ def b32encode(inputs: List[int]) -> str: def convertbits( data: Iterable[int], frombits: int, tobits: int, pad: bool = True -) -> List[int]: +) -> list[int]: acc = 0 bits = 0 ret = [] @@ -106,7 +106,7 @@ def encode(prefix: str, version: int, payload_bytes: bytes) -> str: return prefix + ":" + b32encode(payload + checksum) -def decode(prefix: str, addr: str) -> Tuple[int, bytes]: +def decode(prefix: str, addr: str) -> tuple[int, bytes]: addr = addr.lower() decoded = b32decode(addr) if not verify_checksum(prefix, decoded): diff --git a/core/src/trezor/crypto/der.py b/core/src/trezor/crypto/der.py index 80824e3e8..960ea6d35 100644 --- a/core/src/trezor/crypto/der.py +++ b/core/src/trezor/crypto/der.py @@ -1,8 +1,5 @@ from trezor.utils import BufferReader -if False: - from typing import List - def encode_length(l: int) -> bytes: if l < 0x80: @@ -75,7 +72,7 @@ def encode_seq(seq: tuple) -> bytes: return b"\x30" + encode_length(len(res)) + res -def decode_seq(data: bytes) -> List[bytes]: +def decode_seq(data: bytes) -> list[bytes]: r = BufferReader(data) if r.get() != 0x30: diff --git a/core/src/trezor/crypto/slip39.py b/core/src/trezor/crypto/slip39.py index ae76a4804..af861b5ef 100644 --- a/core/src/trezor/crypto/slip39.py +++ b/core/src/trezor/crypto/slip39.py @@ -37,10 +37,10 @@ from trezor.crypto import hmac, pbkdf2, random from trezor.errors import MnemonicError if False: - from typing import Dict, Iterable, List, Optional, Set, Tuple + from typing import Iterable, Tuple Indices = Tuple[int, ...] - MnemonicGroups = Dict[int, Tuple[int, Set[Tuple[int, bytes]]]] + MnemonicGroups = dict[int, tuple[int, set[tuple[int, bytes]]]] """ ## Simple helpers @@ -196,11 +196,11 @@ def generate_random_identifier() -> int: def split_ems( group_threshold: int, # The number of groups required to reconstruct the master secret. - groups: List[Tuple[int, int]], # A list of (member_threshold, member_count). + groups: list[tuple[int, int]], # A list of (member_threshold, member_count). identifier: int, iteration_exponent: int, encrypted_master_secret: bytes, # The encrypted master secret to split. -) -> List[List[str]]: +) -> list[list[str]]: """ Splits an encrypted master secret into mnemonic shares using Shamir's secret sharing scheme. @@ -229,7 +229,7 @@ def split_ems( # Split the Encrypted Master Secret on the group level. group_shares = _split_secret(group_threshold, len(groups), encrypted_master_secret) - mnemonics: List[List[str]] = [] + mnemonics: list[list[str]] = [] for (member_threshold, member_count), (group_index, group_secret) in zip( groups, group_shares ): @@ -253,7 +253,7 @@ def split_ems( return mnemonics -def recover_ems(mnemonics: List[str]) -> Tuple[int, int, bytes]: +def recover_ems(mnemonics: list[str]) -> tuple[int, int, bytes]: """ Combines mnemonic shares to obtain the encrypted master secret which was previously split using Shamir's secret sharing scheme. @@ -426,7 +426,7 @@ def _rs1024_verify_checksum(data: Indices) -> bool: return _rs1024_polymod(tuple(_CUSTOMIZATION_STRING) + data) == 1 -def _rs1024_error_index(data: Indices) -> Optional[int]: +def _rs1024_error_index(data: Indices) -> int | None: """ Returns the index where an error possibly occurred. Currently unused. @@ -484,7 +484,7 @@ def _create_digest(random_data: bytes, shared_secret: bytes) -> bytes: def _split_secret( threshold: int, share_count: int, shared_secret: bytes -) -> List[Tuple[int, bytes]]: +) -> list[tuple[int, bytes]]: if threshold < 1: raise ValueError( "The requested threshold ({}) must be a positive integer.".format(threshold) @@ -526,7 +526,7 @@ def _split_secret( return shares -def _recover_secret(threshold: int, shares: List[Tuple[int, bytes]]) -> bytes: +def _recover_secret(threshold: int, shares: list[tuple[int, bytes]]) -> bytes: # If the threshold is 1, then the digest of the shared secret is not used. if threshold == 1: return shares[0][1] @@ -591,8 +591,8 @@ def _encode_mnemonic( def _decode_mnemonics( - mnemonics: List[str], -) -> Tuple[int, int, int, int, MnemonicGroups]: + mnemonics: list[str], +) -> tuple[int, int, int, int, MnemonicGroups]: identifiers = set() iteration_exponents = set() group_thresholds = set() diff --git a/core/src/trezor/loop.py b/core/src/trezor/loop.py index fd6bfdea6..fe6a766de 100644 --- a/core/src/trezor/loop.py +++ b/core/src/trezor/loop.py @@ -18,35 +18,30 @@ if False: Awaitable, Callable, Coroutine, - Dict, Generator, - List, - Optional, - Set, - Tuple, ) Task = Coroutine Finalizer = Callable[[Task, Any], None] # function to call after every task step -after_step_hook: Optional[Callable[[], None]] = None +after_step_hook: Callable[[], None] | None = None # tasks scheduled for execution in the future _queue = utimeq.utimeq(64) # tasks paused on I/O -_paused: Dict[int, Set[Task]] = {} +_paused: dict[int, set[Task]] = {} # functions to execute after a task is finished -_finalizers: Dict[int, Finalizer] = {} +_finalizers: dict[int, Finalizer] = {} # reference to the task that is currently executing -this_task: Optional[Task] = None +this_task: Task | None = None if __debug__: # synthetic event queue - synthetic_events: List[Tuple[int, Any]] = [] + synthetic_events: list[tuple[int, Any]] = [] class TaskClosed(Exception): @@ -59,8 +54,8 @@ TASK_CLOSED = TaskClosed() def schedule( task: Task, value: Any = None, - deadline: Optional[int] = None, - finalizer: Optional[Finalizer] = None, + deadline: int | None = None, + finalizer: Finalizer | None = None, reschedule: bool = False, ) -> None: """ @@ -298,8 +293,8 @@ class race(Syscall): def __init__(self, *children: Awaitable, exit_others: bool = True) -> None: self.children = children self.exit_others = exit_others - self.finished: List[Awaitable] = [] # children that finished - self.scheduled: List[Task] = [] # scheduled wrapper tasks + self.finished: list[Awaitable] = [] # children that finished + self.scheduled: list[Task] = [] # scheduled wrapper tasks def handle(self, task: Task) -> None: """ @@ -322,7 +317,7 @@ class race(Syscall): scheduled.append(child_task) # TODO: document the types here - def exit(self, except_for: Optional[Task] = None) -> None: + def exit(self, except_for: Task | None = None) -> None: for task in self.scheduled: if task != except_for: close(task) @@ -385,7 +380,7 @@ class chan: def __init__(self, ch: "chan", value: Any) -> None: self.ch = ch self.value = value - self.task: Optional[Task] = None + self.task: Task | None = None def handle(self, task: Task) -> None: self.task = task @@ -394,15 +389,15 @@ class chan: class Take(Syscall): def __init__(self, ch: "chan") -> None: self.ch = ch - self.task: Optional[Task] = None + self.task: Task | None = None def handle(self, task: Task) -> None: self.task = task self.ch._schedule_take(task) def __init__(self) -> None: - self.putters: List[Tuple[Optional[Task], Any]] = [] - self.takers: List[Task] = [] + self.putters: list[tuple[Task | None, Any]] = [] + self.takers: list[Task] = [] def put(self, value: Any) -> Awaitable[None]: # type: ignore put = chan.Put(self, value) @@ -482,8 +477,8 @@ class spawn(Syscall): def __init__(self, task: Task) -> None: self.task = task - self.callback: Optional[Task] = None - self.finalizer_callback: Optional[Callable[["spawn"], None]] = None + self.callback: Task | None = None + self.finalizer_callback: Callable[["spawn"], None] | None = None self.finished = False self.return_value: Any = None diff --git a/core/src/trezor/messages/__init__.py b/core/src/trezor/messages/__init__.py index bf7c2a20f..94dc675df 100644 --- a/core/src/trezor/messages/__init__.py +++ b/core/src/trezor/messages/__init__.py @@ -4,13 +4,12 @@ if __debug__: from trezor import log if False: - from typing import Dict, Type # noqa: F401 from protobuf import MessageType as MessageType_ # noqa: F401 - MessageClass = Type[MessageType_] + MessageClass = type[MessageType_] -type_to_name = {} # type: Dict[int, str] # reverse table of wire_type mapping -registered = {} # type: Dict[int, MessageClass] # dynamically registered types +type_to_name: dict[int, str] = {} # reverse table of wire_type mapping +registered: dict[int, MessageClass] = {} # dynamically registered types def register(msg_type: MessageClass) -> None: diff --git a/core/src/trezor/pin.py b/core/src/trezor/pin.py index d94374b90..84d6eeb85 100644 --- a/core/src/trezor/pin.py +++ b/core/src/trezor/pin.py @@ -1,11 +1,11 @@ from trezor import ui, utils if False: - from typing import Any, Optional + from typing import Any -_previous_progress: Optional[int] = None -_previous_seconds: Optional[int] = None +_previous_progress: int | None = None +_previous_seconds: int | None = None keepalive_callback: Any = None diff --git a/core/src/trezor/sdcard.py b/core/src/trezor/sdcard.py index 06c6c39e9..01d0813ee 100644 --- a/core/src/trezor/sdcard.py +++ b/core/src/trezor/sdcard.py @@ -1,13 +1,13 @@ from trezorio import fatfs, sdcard if False: - from typing import Any, Callable, Optional, TypeVar + from typing import Any, Callable, TypeVar T = TypeVar("T", bound=Callable) class FilesystemWrapper: - _INSTANCE = None # type: Optional[FilesystemWrapper] + _INSTANCE: "FilesystemWrapper" | None = None def __init__(self, mounted: bool) -> None: self.mounted = mounted diff --git a/core/src/trezor/ui/__init__.py b/core/src/trezor/ui/__init__.py index bd2b84d82..fc3a1652d 100644 --- a/core/src/trezor/ui/__init__.py +++ b/core/src/trezor/ui/__init__.py @@ -9,10 +9,10 @@ if __debug__: from apps.debug import notify_layout_change if False: - from typing import Any, Awaitable, Generator, List, Tuple, TypeVar + from typing import Any, Awaitable, Generator, TypeVar - Pos = Tuple[int, int] - Area = Tuple[int, int, int, int] + Pos = tuple[int, int] + Area = tuple[int, int, int, int] ResultValue = TypeVar("ResultValue") # all rendering is done through a singleton of `Display` @@ -267,7 +267,7 @@ class Component: if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: return [self.__class__.__name__] @@ -343,7 +343,7 @@ class Layout(Component): def __await__(self) -> Generator[Any, Any, ResultValue]: return self.__iter__() # type: ignore - def create_tasks(self) -> Tuple[loop.Task, ...]: + def create_tasks(self) -> tuple[loop.Task, ...]: """ Called from `__iter__`. Creates and returns a sequence of tasks that run this layout. Tasks are executed in parallel. When one of them diff --git a/core/src/trezor/ui/components/common/__init__.py b/core/src/trezor/ui/components/common/__init__.py index 40f9dc493..5ce89a9cb 100644 --- a/core/src/trezor/ui/components/common/__init__.py +++ b/core/src/trezor/ui/components/common/__init__.py @@ -3,11 +3,8 @@ The components/common module contains code that is used by both components/tt and components/t1. """ -if False: - from typing import List - -def break_path_to_lines(path_str: str, per_line: int) -> List[str]: +def break_path_to_lines(path_str: str, per_line: int) -> list[str]: lines = [] while len(path_str) > per_line: i = path_str[:per_line].rfind("/") diff --git a/core/src/trezor/ui/components/common/confirm.py b/core/src/trezor/ui/components/common/confirm.py index 4a163ea78..5ad912176 100644 --- a/core/src/trezor/ui/components/common/confirm.py +++ b/core/src/trezor/ui/components/common/confirm.py @@ -4,7 +4,7 @@ if __debug__: from apps.debug import confirm_signal if False: - from typing import List, Tuple, Optional, Any, Awaitable + from typing import Any, Awaitable CONFIRMED = object() CANCELLED = object() @@ -25,8 +25,8 @@ class ConfirmBase(ui.Layout): def __init__( self, content: ui.Component, - confirm: Optional[ui.Component] = None, - cancel: Optional[ui.Component] = None, + confirm: ui.Component | None = None, + cancel: ui.Component | None = None, ) -> None: self.content = content self.confirm = confirm @@ -48,8 +48,8 @@ class ConfirmBase(ui.Layout): if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: return self.content.read_content() - def create_tasks(self) -> Tuple[loop.Task, ...]: + def create_tasks(self) -> tuple[loop.Task, ...]: return super().create_tasks() + (confirm_signal(),) diff --git a/core/src/trezor/ui/components/common/text.py b/core/src/trezor/ui/components/common/text.py index e49d6401a..837277e8d 100644 --- a/core/src/trezor/ui/components/common/text.py +++ b/core/src/trezor/ui/components/common/text.py @@ -11,7 +11,7 @@ from ...constants import ( ) if False: - from typing import Any, List, Optional, Union + from typing import Any, Union TextContent = Union[str, int] @@ -172,7 +172,7 @@ _WORKING_SPAN = Span() def render_text( - items: List[TextContent], + items: list[TextContent], new_lines: bool, max_lines: int, font: int = ui.NORMAL, @@ -329,7 +329,7 @@ if __debug__: """ def __init__(self) -> None: - self.screen_contents: List[str] = [] + self.screen_contents: list[str] = [] self.orig_display = ui.display def __getattr__(self, key: str) -> Any: @@ -350,7 +350,7 @@ if __debug__: fg: int, bg: int, start: int = 0, - length: Optional[int] = None, + length: int | None = None, ) -> None: if length is None: length = len(string) - start @@ -379,7 +379,7 @@ class TextBase(ui.Component): self.new_lines = new_lines self.break_words = break_words self.render_page_overflow = render_page_overflow - self.content: List[TextContent] = [] + self.content: list[TextContent] = [] self.content_offset = content_offset self.char_offset = char_offset self.line_width = line_width @@ -423,7 +423,7 @@ class TextBase(ui.Component): if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: display_mock = DisplayMock() should_repaint = self.repaint try: @@ -471,7 +471,7 @@ class Label(ui.Component): if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: return [self.content] diff --git a/core/src/trezor/ui/components/tt/button.py b/core/src/trezor/ui/components/tt/button.py index 88f023ecb..ed0656a5b 100644 --- a/core/src/trezor/ui/components/tt/button.py +++ b/core/src/trezor/ui/components/tt/button.py @@ -4,7 +4,7 @@ from trezor import ui from trezor.ui import display, in_area if False: - from typing import List, Optional, Type, Union + from typing import Union class ButtonDefault: @@ -110,9 +110,9 @@ class ButtonMonoConfirm(ButtonDefault): if False: - ButtonContent = Optional[Union[str, bytes]] - ButtonStyleType = Type[ButtonDefault] - ButtonStyleStateType = Type[ButtonDefault.normal] + ButtonContent = Union[str, bytes, None] + ButtonStyleType = type[ButtonDefault] + ButtonStyleStateType = type[ButtonDefault.normal] # button states @@ -250,5 +250,5 @@ class Button(ui.Component): if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: return ["".format(self.text)] diff --git a/core/src/trezor/ui/components/tt/checklist.py b/core/src/trezor/ui/components/tt/checklist.py index a5185ec63..c4669a0b4 100644 --- a/core/src/trezor/ui/components/tt/checklist.py +++ b/core/src/trezor/ui/components/tt/checklist.py @@ -5,7 +5,7 @@ from trezor import res, ui from ...constants import TEXT_HEADER_HEIGHT, TEXT_LINE_HEIGHT if False: - from typing import Iterable, List, Union + from typing import Iterable, Union ChecklistItem = Union[str, Iterable[str]] @@ -19,7 +19,7 @@ class Checklist(ui.Component): super().__init__() self.title = title self.icon = icon - self.items: List[ChecklistItem] = [] + self.items: list[ChecklistItem] = [] self.active = 0 def add(self, item: ChecklistItem) -> None: diff --git a/core/src/trezor/ui/components/tt/confirm.py b/core/src/trezor/ui/components/tt/confirm.py index 045085ff4..7a6468dfb 100644 --- a/core/src/trezor/ui/components/tt/confirm.py +++ b/core/src/trezor/ui/components/tt/confirm.py @@ -10,7 +10,7 @@ if __debug__: from apps.debug import swipe_signal, confirm_signal if False: - from typing import Any, List, Tuple, Optional + from typing import Any from .button import ButtonContent, ButtonStyleType from trezor.ui.loader import LoaderStyleType @@ -24,15 +24,15 @@ class Confirm(ConfirmBase): def __init__( self, content: ui.Component, - confirm: Optional[ButtonContent] = DEFAULT_CONFIRM, + confirm: ButtonContent | None = DEFAULT_CONFIRM, confirm_style: ButtonStyleType = DEFAULT_CONFIRM_STYLE, - cancel: Optional[ButtonContent] = DEFAULT_CANCEL, + cancel: ButtonContent | None = DEFAULT_CANCEL, cancel_style: ButtonStyleType = DEFAULT_CANCEL_STYLE, major_confirm: bool = False, ) -> None: self.content = content - button_confirm: Optional[Button] = None - button_cancel: Optional[Button] = None + button_confirm: Button | None = None + button_cancel: Button | None = None if confirm is not None: if cancel is None: @@ -111,7 +111,7 @@ class ConfirmPageable(Confirm): if self.cancel is not None: self.cancel.repaint = True - def create_tasks(self) -> Tuple[loop.Task, ...]: + def create_tasks(self) -> tuple[loop.Task, ...]: tasks = super().create_tasks() if self.pageable.page_count() > 1: return tasks + (self.handle_paging(),) @@ -192,10 +192,10 @@ class InfoConfirm(ui.Layout): if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: return self.content.read_content() - def create_tasks(self) -> Tuple[loop.Task, ...]: + def create_tasks(self) -> tuple[loop.Task, ...]: return super().create_tasks() + (confirm_signal(),) @@ -269,8 +269,8 @@ class HoldToConfirm(ui.Layout): if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: return self.content.read_content() - def create_tasks(self) -> Tuple[loop.Task, ...]: + def create_tasks(self) -> tuple[loop.Task, ...]: return super().create_tasks() + (confirm_signal(),) diff --git a/core/src/trezor/ui/components/tt/info.py b/core/src/trezor/ui/components/tt/info.py index e8c08b158..5977af135 100644 --- a/core/src/trezor/ui/components/tt/info.py +++ b/core/src/trezor/ui/components/tt/info.py @@ -6,7 +6,6 @@ from .confirm import CONFIRMED from .text import render_text if False: - from typing import Type from .button import ButtonContent @@ -24,7 +23,7 @@ class DefaultInfoConfirm: if False: - InfoConfirmStyleType = Type[DefaultInfoConfirm] + InfoConfirmStyleType = type[DefaultInfoConfirm] class InfoConfirm(ui.Layout): diff --git a/core/src/trezor/ui/components/tt/passphrase.py b/core/src/trezor/ui/components/tt/passphrase.py index b9610ae96..aa961ea02 100644 --- a/core/src/trezor/ui/components/tt/passphrase.py +++ b/core/src/trezor/ui/components/tt/passphrase.py @@ -7,7 +7,7 @@ from .button import Button, ButtonClear, ButtonConfirm from .swipe import SWIPE_HORIZONTAL, SWIPE_LEFT, Swipe if False: - from typing import Iterable, List, Optional, Tuple + from typing import Iterable from .button import ButtonContent, ButtonStyleStateType SPACE = res.load(ui.ICON_SPACE) @@ -67,7 +67,7 @@ class KeyButton(Button): def key_buttons( keys: Iterable[ButtonContent], keyboard: "PassphraseKeyboard" -) -> List[KeyButton]: +) -> list[KeyButton]: return [KeyButton(digit_area(i), k, keyboard) for i, k in enumerate(keys)] @@ -146,7 +146,7 @@ class PassphraseKeyboard(ui.Layout): self.done.on_click = self.on_confirm # type: ignore self.keys = key_buttons(KEYBOARD_KEYS[self.page], self) - self.pending_button: Optional[KeyButton] = None + self.pending_button: KeyButton | None = None self.pending_index = 0 def dispatch(self, event: int, x: int, y: int) -> None: @@ -191,9 +191,7 @@ class PassphraseKeyboard(ui.Layout): # Timeout occurred, let's just reset the pending marker. self.edit(self.input.text) - def edit( - self, text: str, button: Optional[KeyButton] = None, index: int = 0 - ) -> None: + def edit(self, text: str, button: KeyButton | None = None, index: int = 0) -> None: if len(text) > self.max_length: return @@ -248,8 +246,8 @@ class PassphraseKeyboard(ui.Layout): def on_confirm(self) -> None: raise ui.Result(self.input.text) - def create_tasks(self) -> Tuple[loop.Task, ...]: - tasks: Tuple[loop.Task, ...] = ( + def create_tasks(self) -> tuple[loop.Task, ...]: + tasks: tuple[loop.Task, ...] = ( self.handle_input(), self.handle_rendering(), self.handle_paging(), diff --git a/core/src/trezor/ui/components/tt/pin.py b/core/src/trezor/ui/components/tt/pin.py index e90594f25..a69ec882b 100644 --- a/core/src/trezor/ui/components/tt/pin.py +++ b/core/src/trezor/ui/components/tt/pin.py @@ -8,7 +8,7 @@ from .button import Button, ButtonCancel, ButtonClear, ButtonConfirm, ButtonMono if False: from trezor import loop - from typing import Iterable, Optional, Tuple + from typing import Iterable def digit_area(i: int) -> ui.Area: @@ -26,7 +26,7 @@ def generate_digits() -> Iterable[int]: class PinInput(ui.Component): - def __init__(self, prompt: str, subprompt: Optional[str], pin: str) -> None: + def __init__(self, prompt: str, subprompt: str | None, pin: str) -> None: super().__init__() self.prompt = prompt self.subprompt = subprompt @@ -104,7 +104,7 @@ class PinDialog(ui.Layout): def __init__( self, prompt: str, - subprompt: Optional[str], + subprompt: str | None, allow_cancel: bool = True, maxlength: int = 50, ) -> None: @@ -175,7 +175,7 @@ class PinDialog(ui.Layout): if __debug__: - def create_tasks(self) -> Tuple[loop.Task, ...]: + def create_tasks(self) -> tuple[loop.Task, ...]: from apps.debug import input_signal return super().create_tasks() + (input_signal(),) diff --git a/core/src/trezor/ui/components/tt/scroll.py b/core/src/trezor/ui/components/tt/scroll.py index 28f47e70b..4a0123e65 100644 --- a/core/src/trezor/ui/components/tt/scroll.py +++ b/core/src/trezor/ui/components/tt/scroll.py @@ -10,10 +10,6 @@ from .text import TEXT_MAX_LINES, Span, Text if __debug__: from apps.debug import confirm_signal, swipe_signal, notify_layout_change -if False: - from typing import List, Tuple, Union - - _PAGINATED_LINE_WIDTH = const(204) @@ -54,7 +50,7 @@ def render_swipe_text() -> None: class Paginated(ui.Layout): def __init__( - self, pages: List[ui.Component], page: int = 0, one_by_one: bool = False + self, pages: list[ui.Component], page: int = 0, one_by_one: bool = False ): super().__init__() self.pages = pages @@ -102,8 +98,8 @@ class Paginated(ui.Layout): self.on_change() - def create_tasks(self) -> Tuple[loop.Task, ...]: - tasks: Tuple[loop.Task, ...] = ( + def create_tasks(self) -> tuple[loop.Task, ...]: + tasks: tuple[loop.Task, ...] = ( self.handle_input(), self.handle_rendering(), self.handle_paging(), @@ -124,7 +120,7 @@ class Paginated(ui.Layout): if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: return self.pages[self.page].read_content() @@ -186,13 +182,13 @@ class PageWithButtons(ui.Component): if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: return self.content.read_content() class PaginatedWithButtons(ui.Layout): def __init__( - self, pages: List[ui.Component], page: int = 0, one_by_one: bool = False + self, pages: list[ui.Component], page: int = 0, one_by_one: bool = False ) -> None: super().__init__() self.pages = [ @@ -230,10 +226,10 @@ class PaginatedWithButtons(ui.Layout): if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: return self.pages[self.page].read_content() - def create_tasks(self) -> Tuple[loop.Task, ...]: + def create_tasks(self) -> tuple[loop.Task, ...]: return super().create_tasks() + (confirm_signal(),) @@ -244,7 +240,7 @@ def paginate_text( header_icon: str = ui.ICON_DEFAULT, icon_color: int = ui.ORANGE_ICON, break_words: bool = False, -) -> Union[Confirm, Paginated]: +) -> Confirm | Paginated: span = Span(text, 0, font, break_words=break_words) if span.count_lines() <= TEXT_MAX_LINES: result = Text( @@ -258,7 +254,7 @@ def paginate_text( return Confirm(result) else: - pages: List[ui.Component] = [] + pages: list[ui.Component] = [] span.reset( text, 0, font, break_words=break_words, line_width=_PAGINATED_LINE_WIDTH ) diff --git a/core/src/trezor/ui/components/tt/swipe.py b/core/src/trezor/ui/components/tt/swipe.py index 45d63e6ad..ae37390c8 100644 --- a/core/src/trezor/ui/components/tt/swipe.py +++ b/core/src/trezor/ui/components/tt/swipe.py @@ -3,7 +3,7 @@ from micropython import const from trezor import io, loop, ui if False: - from typing import Generator, Optional + from typing import Generator SWIPE_UP = const(0x01) SWIPE_DOWN = const(0x02) @@ -19,7 +19,7 @@ _SWIPE_TRESHOLD = const(30) class Swipe(ui.Component): def __init__( - self, directions: int = SWIPE_ALL, area: Optional[ui.Area] = None + self, directions: int = SWIPE_ALL, area: ui.Area | None = None ) -> None: super().__init__() if area is None: diff --git a/core/src/trezor/ui/components/tt/text.py b/core/src/trezor/ui/components/tt/text.py index 28b2c4f0d..a68ee1354 100644 --- a/core/src/trezor/ui/components/tt/text.py +++ b/core/src/trezor/ui/components/tt/text.py @@ -12,9 +12,6 @@ from ..common.text import ( # noqa: F401 render_text, ) -if False: - from typing import List - def header( title: str, @@ -87,7 +84,7 @@ class Label(ui.Component): if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: return [self.content] diff --git a/core/src/trezor/ui/components/tt/word_select.py b/core/src/trezor/ui/components/tt/word_select.py index f3b600a14..57ecf0438 100644 --- a/core/src/trezor/ui/components/tt/word_select.py +++ b/core/src/trezor/ui/components/tt/word_select.py @@ -4,7 +4,6 @@ from .button import Button if False: from trezor import loop - from typing import Tuple # todo improve? @@ -49,7 +48,7 @@ class WordSelector(ui.Layout): if __debug__: - def create_tasks(self) -> Tuple[loop.Task, ...]: + def create_tasks(self) -> tuple[loop.Task, ...]: from apps.debug import input_signal return super().create_tasks() + (input_signal(),) diff --git a/core/src/trezor/ui/container.py b/core/src/trezor/ui/container.py index 8b24d91b8..d11360737 100644 --- a/core/src/trezor/ui/container.py +++ b/core/src/trezor/ui/container.py @@ -1,8 +1,5 @@ from trezor import ui -if False: - from typing import List - class Container(ui.Component): def __init__(self, *children: ui.Component): @@ -15,5 +12,5 @@ class Container(ui.Component): if __debug__: - def read_content(self) -> List[str]: + def read_content(self) -> list[str]: return sum((c.read_content() for c in self.children), []) diff --git a/core/src/trezor/ui/layouts/tt.py b/core/src/trezor/ui/layouts/tt.py index 9e48d79e1..4ff7131a7 100644 --- a/core/src/trezor/ui/layouts/tt.py +++ b/core/src/trezor/ui/layouts/tt.py @@ -26,11 +26,9 @@ from .common import interact if False: from typing import ( Iterator, - List, Sequence, Type, Union, - Optional, Awaitable, NoReturn, ) @@ -71,16 +69,16 @@ async def confirm_action( ctx: wire.GenericContext, br_type: str, title: str, - action: Optional[str] = None, - description: Optional[str] = None, - description_param: Optional[str] = None, + action: str | None = None, + description: str | None = None, + description_param: str | None = None, description_param_font: int = ui.BOLD, - verb: Union[str, bytes, None] = Confirm.DEFAULT_CONFIRM, - verb_cancel: Union[str, bytes, None] = Confirm.DEFAULT_CANCEL, + verb: str | bytes | None = Confirm.DEFAULT_CONFIRM, + verb_cancel: str | bytes | None = Confirm.DEFAULT_CANCEL, hold: bool = False, hold_danger: bool = False, - icon: Optional[str] = None, # TODO cleanup @ redesign - icon_color: Optional[int] = None, # TODO cleanup @ redesign + icon: str | None = None, # TODO cleanup @ redesign + icon_color: int | None = None, # TODO cleanup @ redesign reverse: bool = False, # TODO cleanup @ redesign larger_vspace: bool = False, # TODO cleanup @ redesign exc: ExceptionType = wire.ActionCancelled, @@ -235,7 +233,7 @@ def _truncate_hex( def _show_address( address: str, desc: str, - network: Optional[str] = None, + network: str | None = None, ) -> Confirm: text = Text(desc, ui.ICON_RECEIVE, ui.GREEN) if network is not None: @@ -246,7 +244,7 @@ def _show_address( def _show_xpub(xpub: str, desc: str, cancel: str) -> Paginated: - pages: List[ui.Component] = [] + pages: list[ui.Component] = [] for lines in chunks(list(chunks(xpub, 16)), 5): text = Text(desc, ui.ICON_RECEIVE, ui.GREEN) text.mono(*lines) @@ -279,10 +277,10 @@ async def show_xpub( async def show_address( ctx: wire.GenericContext, address: str, - address_qr: Optional[str] = None, + address_qr: str | None = None, desc: str = "Confirm address", - network: Optional[str] = None, - multisig_index: Optional[int] = None, + network: str | None = None, + multisig_index: int | None = None, xpubs: Sequence[str] = [], ) -> None: is_multisig = len(xpubs) > 0 @@ -344,10 +342,10 @@ async def _show_modal( br_type: str, br_code: EnumTypeButtonRequestType, header: str, - subheader: Optional[str], + subheader: str | None, content: str, - button_confirm: Optional[str], - button_cancel: Optional[str], + button_confirm: str | None, + button_cancel: str | None, icon: str, icon_color: int, exc: ExceptionType = wire.ActionCancelled, @@ -374,7 +372,7 @@ async def show_error_and_raise( br_type: str, content: str, header: str = "Error", - subheader: Optional[str] = None, + subheader: str | None = None, button: str = "Close", red: bool = False, exc: ExceptionType = wire.ActionCancelled, @@ -400,7 +398,7 @@ def show_warning( br_type: str, content: str, header: str = "Warning", - subheader: Optional[str] = None, + subheader: str | None = None, button: str = "Try again", br_code: EnumTypeButtonRequestType = ButtonRequestType.Warning, ) -> Awaitable[None]: @@ -422,7 +420,7 @@ def show_success( ctx: wire.GenericContext, br_type: str, content: str, - subheader: Optional[str] = None, + subheader: str | None = None, button: str = "Continue", ) -> Awaitable[None]: return _show_modal( @@ -476,7 +474,7 @@ async def confirm_hex( br_type: str, title: str, data: str, - description: Optional[str] = None, + description: str | None = None, br_code: EnumTypeButtonRequestType = ButtonRequestType.Other, icon: str = ui.ICON_SEND, # TODO cleanup @ redesign icon_color: int = ui.GREEN, # TODO cleanup @ redesign @@ -534,7 +532,7 @@ async def confirm_metadata( br_type: str, title: str, content: str, - param: Optional[str] = None, + param: str | None = None, br_code: EnumTypeButtonRequestType = ButtonRequestType.SignTx, ) -> None: text = Text(title, ui.ICON_SEND, ui.GREEN, new_lines=False) @@ -613,7 +611,7 @@ async def confirm_modify_fee( async def confirm_coinjoin( - ctx: wire.GenericContext, fee_per_anonymity: Optional[str], total_fee: str + ctx: wire.GenericContext, fee_per_anonymity: str | None, total_fee: str ) -> None: text = Text("Authorize CoinJoin", ui.ICON_RECOVERY, new_lines=False) if fee_per_anonymity is not None: @@ -628,9 +626,9 @@ async def confirm_coinjoin( # TODO cleanup @ redesign async def confirm_sign_identity( - ctx: wire.GenericContext, proto: str, identity: str, challenge_visual: Optional[str] + ctx: wire.GenericContext, proto: str, identity: str, challenge_visual: str | None ) -> None: - lines: List[TextContent] = [] + lines: list[TextContent] = [] if challenge_visual: lines.append(challenge_visual) @@ -645,7 +643,7 @@ async def confirm_sign_identity( async def confirm_signverify( - ctx: wire.GenericContext, coin: str, message: str, address: Optional[str] = None + ctx: wire.GenericContext, coin: str, message: str, address: str | None = None ) -> None: if address: header = "Verify {} message".format(coin) diff --git a/core/src/trezor/ui/loader.py b/core/src/trezor/ui/loader.py index 04dc50190..b170acb5c 100644 --- a/core/src/trezor/ui/loader.py +++ b/core/src/trezor/ui/loader.py @@ -4,22 +4,19 @@ from micropython import const from trezor import res, ui, utils from trezor.ui import display -if False: - from typing import Optional, Type - class LoaderDefault: class normal: bg_color = ui.BG fg_color = ui.GREEN - icon: Optional[str] = None - icon_fg_color: Optional[int] = None + icon: str | None = None + icon_fg_color: int | None = None class active(normal): bg_color = ui.BG fg_color = ui.GREEN - icon: Optional[str] = ui.ICON_CHECK - icon_fg_color: Optional[int] = ui.WHITE + icon: str | None = ui.ICON_CHECK + icon_fg_color: int | None = ui.WHITE class LoaderDanger(LoaderDefault): @@ -39,7 +36,7 @@ class LoaderNeutral(LoaderDefault): if False: - LoaderStyleType = Type[LoaderDefault] + LoaderStyleType = type[LoaderDefault] _TARGET_MS = const(1000) @@ -59,8 +56,8 @@ class Loader(ui.Component): self.normal_style = style.normal self.active_style = style.active self.target_ms = target_ms - self.start_ms: Optional[int] = None - self.stop_ms: Optional[int] = None + self.start_ms: int | None = None + self.stop_ms: int | None = None self.offset_y = offset_y self.reverse_speedup = reverse_speedup diff --git a/core/src/trezor/ui/popup.py b/core/src/trezor/ui/popup.py index 25704ab25..7a7fd7223 100644 --- a/core/src/trezor/ui/popup.py +++ b/core/src/trezor/ui/popup.py @@ -1,8 +1,5 @@ from trezor import loop, ui, utils -if False: - from typing import Tuple - class Popup(ui.Layout): def __init__(self, content: ui.Component, time_ms: int = 0) -> None: @@ -16,7 +13,7 @@ class Popup(ui.Layout): def dispatch(self, event: int, x: int, y: int) -> None: self.content.dispatch(event, x, y) - def create_tasks(self) -> Tuple[loop.Task, ...]: + def create_tasks(self) -> tuple[loop.Task, ...]: return self.handle_input(), self.handle_rendering(), self.handle_timeout() def handle_timeout(self) -> loop.Task: # type: ignore diff --git a/core/src/trezor/utils.py b/core/src/trezor/utils.py index 73e3d24ba..5009eb5c0 100644 --- a/core/src/trezor/utils.py +++ b/core/src/trezor/utils.py @@ -29,7 +29,6 @@ if False: Any, Iterable, Iterator, - Optional, Protocol, Union, TypeVar, @@ -62,7 +61,7 @@ def unimport_end(mods: Iterable[str]) -> None: gc.collect() -def ensure(cond: bool, msg: Optional[str] = None) -> None: +def ensure(cond: bool, msg: str | None = None) -> None: if not cond: if msg is None: raise AssertionError @@ -182,7 +181,7 @@ class BufferReader: self.offset += nread return nread - def read(self, length: Optional[int] = None) -> bytes: + def read(self, length: int | None = None) -> bytes: """Read and return exactly `length` bytes, or raise EOFError. If `length` is unspecified, reads all remaining data. diff --git a/core/src/trezor/wire/__init__.py b/core/src/trezor/wire/__init__.py index 19303cc0d..5508fa54e 100644 --- a/core/src/trezor/wire/__init__.py +++ b/core/src/trezor/wire/__init__.py @@ -52,11 +52,7 @@ if False: Awaitable, Callable, Coroutine, - Dict, Iterable, - Optional, - Tuple, - Type, TypeVar, ) from trezorio import WireInterface @@ -67,11 +63,11 @@ if False: # Maps a wire type directly to a handler. -workflow_handlers: Dict[int, Handler] = {} +workflow_handlers: dict[int, Handler] = {} # Maps a wire type to a tuple of package and module. This allows handlers # to be dynamically imported when such message arrives. -workflow_packages: Dict[int, Tuple[str, str]] = {} +workflow_packages: dict[int, tuple[str, str]] = {} # If set to False protobuf messages marked with "unstable" option are rejected. experimental_enabled: bool = False @@ -105,11 +101,11 @@ if False: async def call( self, msg: protobuf.MessageType, - expected_type: Type[protobuf.LoadedMessageType], + expected_type: type[protobuf.LoadedMessageType], ) -> Any: ... - async def read(self, expected_type: Type[protobuf.LoadedMessageType]) -> Any: + async def read(self, expected_type: type[protobuf.LoadedMessageType]) -> Any: ... async def write(self, msg: protobuf.MessageType) -> None: @@ -122,8 +118,8 @@ if False: def _wrap_protobuf_load( reader: protobuf.Reader, - expected_type: Type[protobuf.LoadedMessageType], - field_cache: Optional[protobuf.FieldCache] = None, + expected_type: type[protobuf.LoadedMessageType], + field_cache: protobuf.FieldCache | None = None, ) -> protobuf.LoadedMessageType: try: return protobuf.load_message( @@ -168,8 +164,8 @@ class Context: async def call( self, msg: protobuf.MessageType, - expected_type: Type[protobuf.LoadedMessageType], - field_cache: Optional[protobuf.FieldCache] = None, + expected_type: type[protobuf.LoadedMessageType], + field_cache: protobuf.FieldCache | None = None, ) -> protobuf.LoadedMessageType: await self.write(msg, field_cache) del msg @@ -188,8 +184,8 @@ class Context: async def read( self, - expected_type: Type[protobuf.LoadedMessageType], - field_cache: Optional[protobuf.FieldCache] = None, + expected_type: type[protobuf.LoadedMessageType], + field_cache: protobuf.FieldCache | None = None, ) -> protobuf.LoadedMessageType: if __debug__: log.debug( @@ -258,7 +254,7 @@ class Context: async def write( self, msg: protobuf.MessageType, - field_cache: Optional[protobuf.FieldCache] = None, + field_cache: protobuf.FieldCache | None = None, ) -> None: if __debug__: log.debug( @@ -309,8 +305,8 @@ async def handle_session( iface: WireInterface, session_id: int, use_workflow: bool = True ) -> None: ctx = Context(iface, session_id) - next_msg: Optional[codec_v1.Message] = None - res_msg: Optional[protobuf.MessageType] = None + next_msg: codec_v1.Message | None = None + res_msg: protobuf.MessageType | None = None req_type = None req_msg = None while True: @@ -363,7 +359,7 @@ async def handle_session( # We found a valid handler for this message type. # Workflow task, declared for the finally block - wf_task: Optional[HandlerTask] = None + wf_task: HandlerTask | None = None # Here we make sure we always respond with a Failure response # in case of any errors. @@ -456,7 +452,7 @@ async def handle_session( def find_registered_workflow_handler( iface: WireInterface, msg_type: int -) -> Optional[Handler]: +) -> Handler | None: if msg_type in workflow_handlers: # Message has a handler available, return it directly. handler = workflow_handlers[msg_type] diff --git a/core/src/trezor/workflow.py b/core/src/trezor/workflow.py index becb0cc62..7e7b67a4c 100644 --- a/core/src/trezor/workflow.py +++ b/core/src/trezor/workflow.py @@ -3,7 +3,7 @@ import utime from trezor import log, loop if False: - from typing import Callable, Dict, Optional, Set + from typing import Callable IdleCallback = Callable[[], None] @@ -16,14 +16,14 @@ if __debug__: # Set of workflow tasks. Multiple workflows can be running at the same time. -tasks: Set[loop.spawn] = set() +tasks: set[loop.spawn] = set() # Default workflow task, if a default workflow is running. Default workflow # is not contained in the `tasks` set above. -default_task: Optional[loop.spawn] = None +default_task: loop.spawn | None = None # Constructor for the default workflow. Returns a workflow task. -default_constructor: Optional[Callable[[], loop.Task]] = None +default_constructor: Callable[[], loop.Task] | None = None def _on_start(workflow: loop.spawn) -> None: @@ -159,8 +159,8 @@ class IdleTimer: """ def __init__(self) -> None: - self.timeouts: Dict[IdleCallback, int] = {} - self.tasks: Dict[IdleCallback, loop.Task] = {} + self.timeouts: dict[IdleCallback, int] = {} + self.tasks: dict[IdleCallback, loop.Task] = {} async def _timeout_task(self, callback: IdleCallback) -> None: # This function is async, so the result of self._timeout_task() is an awaitable, diff --git a/setup.cfg b/setup.cfg index f0a499431..31290543c 100644 --- a/setup.cfg +++ b/setup.cfg @@ -51,4 +51,5 @@ warn_return_any = True warn_unused_configs = True warn_unused_ignores = True show_error_codes = True - +# type union operator support, should be removed after 3.10 is the default +python_version = 3.10