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
pull/1559/head
Martin Milata 3 years ago committed by matejcik
parent 0278998f72
commit ac711fb8ee

@ -47,7 +47,7 @@ STATIC secbool wrapped_ui_wait_callback(uint32_t wait, uint32_t progress,
} }
/// def init( /// def init(
/// ui_wait_callback: Optional[Callable[[int, int, str], bool]] = None /// ui_wait_callback: Callable[[int, int, str], bool] | None = None
/// ) -> None: /// ) -> None:
/// """ /// """
/// Initializes the storage. Must be called before any other method is /// 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, STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorconfig_init_obj, 0, 1,
mod_trezorconfig_init); 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. /// Attempts to unlock the storage with the given PIN and external salt.
/// Returns True on success, False on failure. /// 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, STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorconfig_unlock_obj,
mod_trezorconfig_unlock); 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. /// Check the given PIN with the given external salt.
/// Returns True on success, False on failure. /// 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( /// def change_pin(
/// oldpin: str, /// oldpin: str,
/// newpin: str, /// newpin: str,
/// old_ext_salt: Optional[bytes], /// old_ext_salt: bytes | None,
/// new_ext_salt: Optional[bytes], /// new_ext_salt: bytes | None,
/// ) -> bool: /// ) -> bool:
/// """ /// """
/// Change PIN and external salt. Returns True on success, False on failure. /// 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( /// def change_wipe_code(
/// pin: str, /// pin: str,
/// ext_salt: Optional[bytes], /// ext_salt: bytes | None,
/// wipe_code: str, /// wipe_code: str,
/// ) -> bool: /// ) -> 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_obj, 3, 3,
mod_trezorconfig_change_wipe_code); 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). /// 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 /// Raises a RuntimeError if decryption or authentication of the stored

@ -53,7 +53,7 @@ typedef struct _mp_obj_AES_t {
/// self, /// self,
/// mode: int, /// mode: int,
/// key: bytes, /// key: bytes,
/// iv: Optional[bytes] = None, /// iv: bytes | None = None,
/// ) -> None: /// ) -> None:
/// """ /// """
/// Initialize AES context. /// Initialize AES context.

@ -49,9 +49,9 @@ STATIC const mp_obj_type_t mod_trezorcrypto_HDNode_type;
/// fingerprint: int, /// fingerprint: int,
/// child_num: int, /// child_num: int,
/// chain_code: bytes, /// chain_code: bytes,
/// private_key: Optional[bytes] = None, /// private_key: bytes | None = None,
/// public_key: Optional[bytes] = None, /// public_key: bytes | None = None,
/// curve_name: Optional[str] = None, /// curve_name: str | None = None,
/// ) -> None: /// ) -> None:
/// """ /// """
/// """ /// """

@ -25,7 +25,7 @@
/// package: trezorcrypto.bip39 /// 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. /// 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( /// def seed(
/// mnemonic: str, /// mnemonic: str,
/// passphrase: str, /// passphrase: str,
/// callback: Optional[Callable[[int, int], None]] = None, /// callback: Callable[[int, int], None] | None = None,
/// ) -> bytes: /// ) -> bytes:
/// """ /// """
/// Generate seed from mnemonic and passphrase. /// Generate seed from mnemonic and passphrase.

@ -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); 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. /// Creates a hash context object.
/// """ /// """

@ -41,10 +41,10 @@ STATIC mp_obj_t mod_trezorcrypto_Blake2b_update(mp_obj_t self, mp_obj_t data);
/// def __init__( /// def __init__(
/// self, /// self,
/// data: Optional[bytes] = None, /// data: bytes | None = None,
/// outlen: int = blake2b.digest_size, /// outlen: int = blake2b.digest_size,
/// key: Optional[bytes] = None, /// key: bytes | None = None,
/// personal: Optional[bytes] = None, /// personal: bytes | None = None,
/// ) -> None: /// ) -> None:
/// """ /// """
/// Creates a hash context object. /// Creates a hash context object.

@ -41,10 +41,10 @@ STATIC mp_obj_t mod_trezorcrypto_Blake2s_update(mp_obj_t self, mp_obj_t data);
/// def __init__( /// def __init__(
/// self, /// self,
/// data: Optional[bytes] = None, /// data: bytes | None = None,
/// outlen: int = blake2s.digest_size, /// outlen: int = blake2s.digest_size,
/// key: Optional[bytes] = None, /// key: bytes | None = None,
/// personal: Optional[bytes] = None, /// personal: bytes | None = None,
/// ) -> None: /// ) -> None:
/// """ /// """
/// Creates a hash context object. /// Creates a hash context object.

@ -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, STATIC MP_DEFINE_CONST_FUN_OBJ_3(mod_trezorcrypto_ed25519_verify_obj,
mod_trezorcrypto_ed25519_verify); 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. /// 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_obj,
mod_trezorcrypto_ed25519_cosi_combine_publickeys); 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. /// Combines a list of signatures used in COSI cosigning scheme.
/// """ /// """

@ -41,7 +41,7 @@ typedef struct _mp_obj_Groestl512_t {
STATIC mp_obj_t mod_trezorcrypto_Groestl512_update(mp_obj_t self, STATIC mp_obj_t mod_trezorcrypto_Groestl512_update(mp_obj_t self,
mp_obj_t data); 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. /// Creates a hash context object.
/// """ /// """

@ -48,7 +48,7 @@ STATIC mp_obj_t mod_trezorcrypto_Hmac_update(mp_obj_t self, mp_obj_t data);
/// self, /// self,
/// hashtype: int, /// hashtype: int,
/// key: bytes, /// key: bytes,
/// message: Optional[bytes] = None, /// message: bytes | None = None,
/// ) -> None: /// ) -> None:
/// """ /// """
/// Create a HMAC context. /// Create a HMAC context.

@ -180,7 +180,7 @@ STATIC void mp_unpack_scalar(bignum256modm r, const mp_obj_t arg,
/// EC point on ED25519 /// EC point on ED25519
/// """ /// """
/// ///
/// def __init__(self, x: Optional[Union[Ge25519, bytes]] = None): /// def __init__(self, x: Ge25519 | bytes | None = None):
/// """ /// """
/// Constructor /// Constructor
/// """ /// """
@ -218,7 +218,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_monero_ge25519___del___obj,
/// EC scalar on 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 /// Constructor
/// """ /// """
@ -261,7 +261,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(
/// XMR hasher /// XMR hasher
/// """ /// """
/// ///
/// def __init__(self, x: Optional[bytes] = None): /// def __init__(self, x: bytes | None = None):
/// """ /// """
/// Constructor /// Constructor
/// """ /// """
@ -314,7 +314,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_monero_hasher___del___obj,
/// mock:global /// mock:global
/// def init256_modm( /// def init256_modm(
/// dst: Optional[Sc25519], val: Union[int, bytes, Sc25519] /// dst: Sc25519 | None, val: int | bytes | Sc25519
/// ) -> Sc25519: /// ) -> Sc25519:
/// """ /// """
/// Initializes Sc25519 scalar /// 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, STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_monero_get256_modm_obj,
mod_trezorcrypto_monero_get256_modm); 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 /// 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_obj, 2, 3,
mod_trezorcrypto_monero_add256_modm); 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 /// 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_obj, 2, 3,
mod_trezorcrypto_monero_sub256_modm); 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 /// Scalar multiplication
/// """ /// """
@ -460,7 +460,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_mul256_modm); mod_trezorcrypto_monero_mul256_modm);
/// def mulsub256_modm( /// def mulsub256_modm(
/// r: Optional[Sc25519], a: Sc25519, b: Sc25519, c: Sc25519 /// r: Sc25519 | None, a: Sc25519, b: Sc25519, c: Sc25519
/// ) -> Sc25519: /// ) -> Sc25519:
/// """ /// """
/// c - a*b /// c - a*b
@ -484,7 +484,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_mulsub256_modm); mod_trezorcrypto_monero_mulsub256_modm);
/// def muladd256_modm( /// def muladd256_modm(
/// r: Optional[Sc25519], a: Sc25519, b: Sc25519, c: Sc25519 /// r: Sc25519 | None, a: Sc25519, b: Sc25519, c: Sc25519
/// ) -> Sc25519: /// ) -> Sc25519:
/// """ /// """
/// c + a*b /// 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_obj, 3, 4,
mod_trezorcrypto_monero_muladd256_modm); 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 /// Scalar modular inversion
/// """ /// """
@ -542,7 +542,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_inv256_modm); mod_trezorcrypto_monero_inv256_modm);
/// def pack256_modm( /// def pack256_modm(
/// r: Optional[bytes], a: Sc25519, offset: Optional[int] = 0 /// r: bytes | None, a: Sc25519, offset: int | None = 0
/// ) -> bytes: /// ) -> bytes:
/// """ /// """
/// Scalar compression /// Scalar compression
@ -572,7 +572,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_pack256_modm); mod_trezorcrypto_monero_pack256_modm);
/// def unpack256_modm( /// def unpack256_modm(
/// r: Optional[Sc25519], a: bytes, offset: int = 0 /// r: Sc25519 | None, a: bytes, offset: int = 0
/// ) -> Sc25519: /// ) -> Sc25519:
/// """ /// """
/// Scalar decompression /// Scalar decompression
@ -591,7 +591,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_unpack256_modm); mod_trezorcrypto_monero_unpack256_modm);
/// def unpack256_modm_noreduce( /// def unpack256_modm_noreduce(
/// r: Optional[Sc25519], a: bytes, offset: int = 0 /// r: Sc25519 | None, a: bytes, offset: int = 0
/// ) -> Sc25519: /// ) -> Sc25519:
/// """ /// """
/// Scalar decompression, raw, without modular reduction /// Scalar decompression, raw, without modular reduction
@ -620,7 +620,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
// GE25519 Defs // GE25519 Defs
// //
/// def ge25519_set_neutral(r: Optional[Ge25519]) -> Ge25519: /// def ge25519_set_neutral(r: Ge25519 | None) -> Ge25519:
/// """ /// """
/// Sets neutral point /// 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_obj, 0, 1,
mod_trezorcrypto_monero_ge25519_set_neutral); 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 /// 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, STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_monero_ge25519_eq_obj,
mod_trezorcrypto_monero_ge25519_eq); 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 /// 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_obj, 2, 3,
mod_trezorcrypto_monero_ge25519_add); 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 /// 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_obj, 2, 3,
mod_trezorcrypto_monero_ge25519_sub); 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 /// 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_obj, 1, 2,
mod_trezorcrypto_monero_ge25519_double); 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 /// EC point * 8
/// """ /// """
@ -751,7 +751,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_mul8); mod_trezorcrypto_monero_ge25519_mul8);
/// def ge25519_double_scalarmult_vartime( /// def ge25519_double_scalarmult_vartime(
/// r: Optional[Ge25519], p1: Ge25519, s1: Sc25519, s2: Sc25519 /// r: Ge25519 | None, p1: Ge25519, s1: Sc25519, s2: Sc25519
/// ) -> Ge25519: /// ) -> Ge25519:
/// """ /// """
/// s1 * G + s2 * p1 /// s1 * G + s2 * p1
@ -775,7 +775,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_double_scalarmult_vartime); mod_trezorcrypto_monero_ge25519_double_scalarmult_vartime);
/// def ge25519_double_scalarmult_vartime2( /// def ge25519_double_scalarmult_vartime2(
/// r: Optional[Ge25519], /// r: Ge25519 | None,
/// p1: Ge25519, /// p1: Ge25519,
/// s1: Sc25519, /// s1: Sc25519,
/// p2: Ge25519, /// p2: Ge25519,
@ -806,7 +806,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_double_scalarmult_vartime2); mod_trezorcrypto_monero_ge25519_double_scalarmult_vartime2);
/// def ge25519_scalarmult_base( /// def ge25519_scalarmult_base(
/// r: Optional[Ge25519], s: Union[Sc25519, int] /// r: Ge25519 | None, s: Sc25519 | int
/// ) -> Ge25519: /// ) -> Ge25519:
/// """ /// """
/// s * G /// s * G
@ -835,7 +835,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_scalarmult_base); mod_trezorcrypto_monero_ge25519_scalarmult_base);
/// def ge25519_scalarmult( /// def ge25519_scalarmult(
/// r: Optional[Ge25519], p: Ge25519, s: Union[Sc25519, int] /// r: Ge25519 | None, p: Ge25519, s: Sc25519 | int
/// ) -> Ge25519: /// ) -> Ge25519:
/// """ /// """
/// s * p /// s * p
@ -894,7 +894,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_pack); mod_trezorcrypto_monero_ge25519_pack);
/// def ge25519_unpack_vartime( /// def ge25519_unpack_vartime(
/// r: Optional[Ge25519], buff: bytes, offset: int = 0 /// r: Ge25519 | None, buff: bytes, offset: int = 0
/// ) -> Ge25519: /// ) -> Ge25519:
/// """ /// """
/// Point decompression /// 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_obj, 2, 2,
mod_trezorcrypto_monero_xmr_base58_addr_encode_check); 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 /// Monero block base 58 decoding, returning (decoded, tag) or raising on
/// error. /// 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_obj, 1, 1,
mod_trezorcrypto_monero_xmr_base58_addr_decode_check); 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 /// Generates a random scalar
/// """ /// """
@ -987,7 +987,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_random_scalar); mod_trezorcrypto_monero_xmr_random_scalar);
// clang-format off // 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 // clang-format on
/// """ /// """
/// XMR fast hash /// XMR fast hash
@ -1027,7 +1027,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_fast_hash); mod_trezorcrypto_monero_xmr_fast_hash);
// clang-format off // 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: /// int) -> Ge25519:
// clang-format on // clang-format on
/// """ /// """
@ -1056,7 +1056,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_hash_to_ec); mod_trezorcrypto_monero_xmr_hash_to_ec);
// clang-format off // 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: /// offset: int) -> Sc25519:
// clang-format on // clang-format on
/// """ /// """
@ -1085,7 +1085,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_hash_to_scalar); mod_trezorcrypto_monero_xmr_hash_to_scalar);
/// def xmr_derivation_to_scalar( /// def xmr_derivation_to_scalar(
/// r: Optional[Sc25519], p: Ge25519, output_index: int /// r: Sc25519 | None, p: Ge25519, output_index: int
/// ) -> Sc25519: /// ) -> Sc25519:
/// """ /// """
/// H_s(derivation || varint(output_index)) /// 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); mod_trezorcrypto_monero_xmr_derivation_to_scalar);
/// def xmr_generate_key_derivation( /// def xmr_generate_key_derivation(
/// r: Optional[Ge25519], A: Ge25519, b: Sc25519 /// r: Ge25519 | None, A: Ge25519, b: Sc25519
/// ) -> Ge25519: /// ) -> Ge25519:
/// """ /// """
/// 8*(key2*key1) /// 8*(key2*key1)
@ -1127,7 +1127,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_generate_key_derivation); mod_trezorcrypto_monero_xmr_generate_key_derivation);
/// def xmr_derive_private_key( /// def xmr_derive_private_key(
/// r: Optional[Sc25519], deriv: Ge25519, idx: int, base: Sc25519 /// r: Sc25519 | None, deriv: Ge25519, idx: int, base: Sc25519
/// ) -> Sc25519: /// ) -> Sc25519:
/// """ /// """
/// base + H_s(derivation || varint(output_index)) /// 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); mod_trezorcrypto_monero_xmr_derive_private_key);
/// def xmr_derive_public_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: /// ) -> Ge25519:
/// """ /// """
/// H_s(derivation || varint(output_index))G + base /// 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); mod_trezorcrypto_monero_xmr_derive_public_key);
/// def xmr_add_keys2( /// def xmr_add_keys2(
/// r: Optional[Ge25519], a: Sc25519, b: Sc25519, B: Ge25519 /// r: Ge25519 | None, a: Sc25519, b: Sc25519, B: Ge25519
/// ) -> Ge25519: /// ) -> Ge25519:
/// """ /// """
/// aG + bB, G is basepoint /// aG + bB, G is basepoint
@ -1193,7 +1193,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_add_keys2); mod_trezorcrypto_monero_xmr_add_keys2);
/// def xmr_add_keys2_vartime( /// def xmr_add_keys2_vartime(
/// r: Optional[Ge25519], a: Sc25519, b: Sc25519, B: Ge25519 /// r: Ge25519 | None, a: Sc25519, b: Sc25519, B: Ge25519
/// ) -> Ge25519: /// ) -> Ge25519:
/// """ /// """
/// aG + bB, G is basepoint /// aG + bB, G is basepoint
@ -1216,7 +1216,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_add_keys2_vartime); mod_trezorcrypto_monero_xmr_add_keys2_vartime);
/// def xmr_add_keys3( /// 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: /// ) -> Ge25519:
/// """ /// """
/// aA + bB /// aA + bB
@ -1240,7 +1240,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_add_keys3); mod_trezorcrypto_monero_xmr_add_keys3);
/// def xmr_add_keys3_vartime( /// 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: /// ) -> Ge25519:
/// """ /// """
/// aA + bB /// aA + bB
@ -1265,7 +1265,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_add_keys3_vartime); mod_trezorcrypto_monero_xmr_add_keys3_vartime);
/// def xmr_get_subaddress_secret_key( /// 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: /// ) -> Sc25519:
/// """ /// """
/// Hs(SubAddr || a || index_major || index_minor) /// 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_obj, 3, 4,
mod_trezorcrypto_monero_xmr_get_subaddress_secret_key); 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 /// aG + amount * H
/// """ /// """

@ -49,7 +49,7 @@ STATIC mp_obj_t mod_trezorcrypto_Pbkdf2_update(mp_obj_t self, mp_obj_t data);
/// prf: int, /// prf: int,
/// password: bytes, /// password: bytes,
/// salt: bytes, /// salt: bytes,
/// iterations: Optional[int] = None, /// iterations: int | None = None,
/// blocknr: int = 1, /// blocknr: int = 1,
/// ) -> None: /// ) -> None:
/// """ /// """

@ -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); 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. /// Creates a hash context object.
/// """ /// """

@ -113,7 +113,7 @@ enum {
/// secret_key: bytes, /// secret_key: bytes,
/// digest: bytes, /// digest: bytes,
/// compressed: bool = True, /// compressed: bool = True,
/// canonical: Optional[int] = None, /// canonical: int | None = None,
/// ) -> bytes: /// ) -> bytes:
/// """ /// """
/// Uses secret key to produce the signature of the digest. /// Uses secret key to produce the signature of the digest.

@ -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); 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. /// Creates a hash context object.
/// """ /// """

@ -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); 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. /// Creates a hash context object.
/// """ /// """

@ -40,7 +40,7 @@ STATIC mp_obj_t mod_trezorcrypto_Sha3_256_update(mp_obj_t self, mp_obj_t data);
/// def __init__( /// def __init__(
/// self, /// self,
/// data: Optional[bytes] = None, /// data: bytes | None = None,
/// keccak: bool = False, /// keccak: bool = False,
/// ) -> None: /// ) -> None:
/// """ /// """

@ -40,7 +40,7 @@ STATIC mp_obj_t mod_trezorcrypto_Sha3_512_update(mp_obj_t self, mp_obj_t data);
/// def __init__( /// def __init__(
/// self, /// self,
/// data: Optional[bytes] = None, /// data: bytes | None = None,
/// keccak: bool = False, /// keccak: bool = False,
/// ) -> None: /// ) -> None:
/// """ /// """

@ -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); 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. /// Creates a hash context object.
/// """ /// """

@ -27,7 +27,7 @@
/// package: trezorcrypto.shamir /// 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)). /// Returns f(x) given the Shamir shares (x_1, f(x_1)), ... , (x_k, f(x_k)).
/// :param shares: The Shamir shares. /// :param shares: The Shamir shares.

@ -170,9 +170,9 @@ typedef struct _mp_obj_FatFSFile_t {
/// from types import TracebackType /// from types import TracebackType
/// def __exit__( /// def __exit__(
/// self, type: Optional[Type[BaseException]], /// self, type: type[BaseException] | None,
/// value: Optional[BaseException], /// value: BaseException | None,
/// traceback: Optional[TracebackType], /// traceback: TracebackType | None,
/// ) -> None: /// ) -> None:
/// """ /// """
/// Close an open file object /// 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, STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorio_FatFSFile_read_obj,
mod_trezorio_FatFSFile_read); mod_trezorio_FatFSFile_read);
/// def write(self, data: Union[bytes, bytearray]) -> int: /// def write(self, data: bytes | bytearray) -> int:
/// """ /// """
/// Write data to the file /// 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, .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 /// Class encapsulating directory
/// """ /// """
@ -321,7 +321,7 @@ typedef struct _mp_obj_FatFSDir_t {
DIR dp; DIR dp;
} mp_obj_FatFSDir_t; } mp_obj_FatFSDir_t;
/// def __next__(self) -> Tuple[int, str, str]: /// def __next__(self) -> tuple[int, str, str]:
/// """ /// """
/// Read an entry in the directory /// 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, STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorio_fatfs_unlink_obj,
mod_trezorio_fatfs_unlink); mod_trezorio_fatfs_unlink);
/// def stat(path: str) -> Tuple[int, str, str]: /// def stat(path: str) -> tuple[int, str, str]:
/// """ /// """
/// Get file status /// Get file status
/// """ /// """

@ -28,7 +28,7 @@
/// package: trezorio.__init__ /// 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 /// 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 // `io.POLL_READ` and `io.POLL_WRITE`) and assign the result into

@ -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); 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. /// Registers passed interface into the USB stack.
/// """ /// """

@ -93,8 +93,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorui_Display_bar_obj, 6, 6,
/// w: int, /// w: int,
/// h: int, /// h: int,
/// fgcolor: int, /// fgcolor: int,
/// bgcolor: Optional[int] = None, /// bgcolor: int | None = None,
/// radius: Optional[int] = None, /// radius: int | None = None,
/// ) -> None: /// ) -> None:
/// """ /// """
/// Renders a rounded bar at position (x,y = upper left corner) with width w /// 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, 8, 8,
mod_trezorui_Display_bar_radius); 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 /// Returns tuple containing TOIF image dimensions: width, height, and
/// whether it is grayscale. /// 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, /// yoffset: int,
/// fgcolor: int, /// fgcolor: int,
/// bgcolor: int, /// bgcolor: int,
/// icon: Optional[bytes] = None, /// icon: bytes | None = None,
/// iconfgcolor: Optional[int] = None, /// iconfgcolor: int | None = None,
/// ) -> None: /// ) -> None:
/// """ /// """
/// Renders a rotating loader graphic. /// Renders a rotating loader graphic.
@ -317,8 +317,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorui_Display_print_obj,
/// font: int, /// font: int,
/// fgcolor: int, /// fgcolor: int,
/// bgcolor: int, /// bgcolor: int,
/// text_offset: Optional[int] = None, /// text_offset: int | None = None,
/// text_len: Optional[int] = None, /// text_len: int | None = None,
/// ) -> None: /// ) -> None:
/// """ /// """
/// Renders left-aligned text at position (x,y) where x is left position and /// 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, /// self,
/// text: str, /// text: str,
/// font: int, /// font: int,
/// text_offset: Optional[int] = None, /// text_offset: int | None = None,
/// text_len: Optional[int] = None, /// text_len: int | None = None,
/// ) -> int: /// ) -> int:
/// """ /// """
/// Returns a width of text in pixels. Font font is used for rendering. /// 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, STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorui_Display_qrcode_obj, 5,
5, mod_trezorui_Display_qrcode); 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. /// Sets display orientation to 0, 90, 180 or 270 degrees.
/// Everything needs to be redrawn again when this function is used. /// 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, 1, 2,
mod_trezorui_Display_orientation); 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. /// Sets backlight intensity to the value specified in val.
/// Call without the val parameter to just perform the read of the value. /// 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, 1, 2,
mod_trezorui_Display_backlight); 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. /// Sets offset (x, y) for all subsequent drawing calls.
/// Call without the xy parameter to just perform the read of the value. /// Call without the xy parameter to just perform the read of the value.

@ -58,11 +58,11 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorutils_consteq_obj,
mod_trezorutils_consteq); mod_trezorutils_consteq);
/// def memcpy( /// def memcpy(
/// dst: Union[bytearray, memoryview], /// dst: bytearray | memoryview,
/// dst_ofs: int, /// dst_ofs: int,
/// src: bytes, /// src: bytes,
/// src_ofs: int, /// src_ofs: int,
/// n: Optional[int] = None, /// n: int | None = None,
/// ) -> int: /// ) -> int:
/// """ /// """
/// Copies at most `n` bytes from `src` at offset `src_ofs` to /// 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, STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorutils_memcpy_obj, 4, 5,
mod_trezorutils_memcpy); mod_trezorutils_memcpy);
/// def halt(msg: Optional[str] = None) -> None: /// def halt(msg: str | None = None) -> None:
/// """ /// """
/// Halts execution. /// Halts execution.
/// """ /// """

@ -3,7 +3,7 @@ from typing import *
# extmod/modtrezorconfig/modtrezorconfig.c # extmod/modtrezorconfig/modtrezorconfig.c
def init( def init(
ui_wait_callback: Optional[Callable[[int, int, str], bool]] = None ui_wait_callback: Callable[[int, int, str], bool] | None = None
) -> None: ) -> None:
""" """
Initializes the storage. Must be called before any other method is Initializes the storage. Must be called before any other method is
@ -12,7 +12,7 @@ def init(
# extmod/modtrezorconfig/modtrezorconfig.c # 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. Attempts to unlock the storage with the given PIN and external salt.
Returns True on success, False on failure. Returns True on success, False on failure.
@ -20,7 +20,7 @@ def unlock(pin: str, ext_salt: Optional[bytes]) -> bool:
# extmod/modtrezorconfig/modtrezorconfig.c # 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. Check the given PIN with the given external salt.
Returns True on success, False on failure. Returns True on success, False on failure.
@ -59,8 +59,8 @@ def get_pin_rem() -> int:
def change_pin( def change_pin(
oldpin: str, oldpin: str,
newpin: str, newpin: str,
old_ext_salt: Optional[bytes], old_ext_salt: bytes | None,
new_ext_salt: Optional[bytes], new_ext_salt: bytes | None,
) -> bool: ) -> bool:
""" """
Change PIN and external salt. Returns True on success, False on failure. 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 # extmod/modtrezorconfig/modtrezorconfig.c
def change_wipe_code( def change_wipe_code(
pin: str, pin: str,
ext_salt: Optional[bytes], ext_salt: bytes | None,
wipe_code: str, wipe_code: str,
) -> bool: ) -> bool:
""" """
@ -93,7 +93,7 @@ def change_wipe_code(
# extmod/modtrezorconfig/modtrezorconfig.c # 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). 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 Raises a RuntimeError if decryption or authentication of the stored

@ -16,7 +16,7 @@ class aes:
self, self,
mode: int, mode: int,
key: bytes, key: bytes,
iv: Optional[bytes] = None, iv: bytes | None = None,
) -> None: ) -> None:
""" """
Initialize AES context. Initialize AES context.
@ -41,7 +41,7 @@ class blake256:
block_size: int block_size: int
digest_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. Creates a hash context object.
""" """
@ -67,10 +67,10 @@ class blake2b:
def __init__( def __init__(
self, self,
data: Optional[bytes] = None, data: bytes | None = None,
outlen: int = blake2b.digest_size, outlen: int = blake2b.digest_size,
key: Optional[bytes] = None, key: bytes | None = None,
personal: Optional[bytes] = None, personal: bytes | None = None,
) -> None: ) -> None:
""" """
Creates a hash context object. Creates a hash context object.
@ -97,10 +97,10 @@ class blake2s:
def __init__( def __init__(
self, self,
data: Optional[bytes] = None, data: bytes | None = None,
outlen: int = blake2s.digest_size, outlen: int = blake2s.digest_size,
key: Optional[bytes] = None, key: bytes | None = None,
personal: Optional[bytes] = None, personal: bytes | None = None,
) -> None: ) -> None:
""" """
Creates a hash context object. Creates a hash context object.
@ -162,7 +162,7 @@ class groestl512:
block_size: int block_size: int
digest_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. Creates a hash context object.
""" """
@ -190,7 +190,7 @@ class hmac:
self, self,
hashtype: int, hashtype: int,
key: bytes, key: bytes,
message: Optional[bytes] = None, message: bytes | None = None,
) -> None: ) -> None:
""" """
Create a HMAC context. Create a HMAC context.
@ -220,7 +220,7 @@ class pbkdf2:
prf: int, prf: int,
password: bytes, password: bytes,
salt: bytes, salt: bytes,
iterations: Optional[int] = None, iterations: int | None = None,
blocknr: int = 1, blocknr: int = 1,
) -> None: ) -> None:
""" """
@ -246,7 +246,7 @@ class ripemd160:
block_size: int block_size: int
digest_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. Creates a hash context object.
""" """
@ -270,7 +270,7 @@ class sha1:
block_size: int block_size: int
digest_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. Creates a hash context object.
""" """
@ -294,7 +294,7 @@ class sha256:
block_size: int block_size: int
digest_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. Creates a hash context object.
""" """
@ -320,7 +320,7 @@ class sha3_256:
def __init__( def __init__(
self, self,
data: Optional[bytes] = None, data: bytes | None = None,
keccak: bool = False, keccak: bool = False,
) -> None: ) -> None:
""" """
@ -353,7 +353,7 @@ class sha3_512:
def __init__( def __init__(
self, self,
data: Optional[bytes] = None, data: bytes | None = None,
keccak: bool = False, keccak: bool = False,
) -> None: ) -> None:
""" """
@ -384,7 +384,7 @@ class sha512:
block_size: int block_size: int
digest_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. Creates a hash context object.
""" """

@ -13,9 +13,9 @@ class HDNode:
fingerprint: int, fingerprint: int,
child_num: int, child_num: int,
chain_code: bytes, chain_code: bytes,
private_key: Optional[bytes] = None, private_key: bytes | None = None,
public_key: Optional[bytes] = None, public_key: bytes | None = None,
curve_name: Optional[str] = None, curve_name: str | None = None,
) -> None: ) -> None:
""" """
""" """

@ -2,7 +2,7 @@ from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-bip39.h # 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. Return the first word from the wordlist starting with prefix.
""" """
@ -42,7 +42,7 @@ def check(mnemonic: str) -> bool:
def seed( def seed(
mnemonic: str, mnemonic: str,
passphrase: str, passphrase: str,
callback: Optional[Callable[[int, int], None]] = None, callback: Callable[[int, int], None] | None = None,
) -> bytes: ) -> bytes:
""" """
Generate seed from mnemonic and passphrase. Generate seed from mnemonic and passphrase.

@ -40,14 +40,14 @@ def verify(public_key: bytes, signature: bytes, message: bytes) -> bool:
# extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h # 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. Combines a list of public keys used in COSI cosigning scheme.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h # 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. Combines a list of signatures used in COSI cosigning scheme.
""" """

@ -6,7 +6,7 @@ class Ge25519:
""" """
EC point on ED25519 EC point on ED25519
""" """
def __init__(self, x: Optional[Union[Ge25519, bytes]] = None): def __init__(self, x: Ge25519 | bytes | None = None):
""" """
Constructor Constructor
""" """
@ -17,7 +17,7 @@ class Sc25519:
""" """
EC scalar on 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 Constructor
""" """
@ -28,7 +28,7 @@ class Hasher:
""" """
XMR hasher XMR hasher
""" """
def __init__(self, x: Optional[bytes] = None): def __init__(self, x: bytes | None = None):
""" """
Constructor Constructor
""" """
@ -48,7 +48,7 @@ class Hasher:
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def init256_modm( def init256_modm(
dst: Optional[Sc25519], val: Union[int, bytes, Sc25519] dst: Sc25519 | None, val: int | bytes | Sc25519
) -> Sc25519: ) -> Sc25519:
""" """
Initializes Sc25519 scalar Initializes Sc25519 scalar
@ -85,21 +85,21 @@ def get256_modm(a: Sc25519) -> int:
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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 Scalar addition
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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 Scalar subtraction
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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 Scalar multiplication
""" """
@ -107,7 +107,7 @@ def mul256_modm(r: Optional[Sc25519], a: Sc25519, b: Sc25519) -> Sc25519:
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def mulsub256_modm( def mulsub256_modm(
r: Optional[Sc25519], a: Sc25519, b: Sc25519, c: Sc25519 r: Sc25519 | None, a: Sc25519, b: Sc25519, c: Sc25519
) -> Sc25519: ) -> Sc25519:
""" """
c - a*b c - a*b
@ -116,7 +116,7 @@ def mulsub256_modm(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def muladd256_modm( def muladd256_modm(
r: Optional[Sc25519], a: Sc25519, b: Sc25519, c: Sc25519 r: Sc25519 | None, a: Sc25519, b: Sc25519, c: Sc25519
) -> Sc25519: ) -> Sc25519:
""" """
c + a*b c + a*b
@ -124,7 +124,7 @@ def muladd256_modm(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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 Scalar modular inversion
""" """
@ -132,7 +132,7 @@ def inv256_modm(r: Optional[Sc25519], a: Sc25519) -> Sc25519:
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def pack256_modm( def pack256_modm(
r: Optional[bytes], a: Sc25519, offset: Optional[int] = 0 r: bytes | None, a: Sc25519, offset: int | None = 0
) -> bytes: ) -> bytes:
""" """
Scalar compression Scalar compression
@ -141,7 +141,7 @@ def pack256_modm(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def unpack256_modm( def unpack256_modm(
r: Optional[Sc25519], a: bytes, offset: int = 0 r: Sc25519 | None, a: bytes, offset: int = 0
) -> Sc25519: ) -> Sc25519:
""" """
Scalar decompression Scalar decompression
@ -150,7 +150,7 @@ def unpack256_modm(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def unpack256_modm_noreduce( def unpack256_modm_noreduce(
r: Optional[Sc25519], a: bytes, offset: int = 0 r: Sc25519 | None, a: bytes, offset: int = 0
) -> Sc25519: ) -> Sc25519:
""" """
Scalar decompression, raw, without modular reduction Scalar decompression, raw, without modular reduction
@ -158,14 +158,14 @@ def unpack256_modm_noreduce(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def ge25519_set_neutral(r: Optional[Ge25519]) -> Ge25519: def ge25519_set_neutral(r: Ge25519 | None) -> Ge25519:
""" """
Sets neutral point Sets neutral point
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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 Sets H point
""" """
@ -186,28 +186,28 @@ def ge25519_eq(a: Ge25519, b: Ge25519) -> bool:
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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 Adds EC points
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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 Subtracts EC points
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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 EC point doubling
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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 EC point * 8
""" """
@ -215,7 +215,7 @@ def ge25519_mul8(r: Optional[Ge25519], p: Ge25519) -> Ge25519:
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def ge25519_double_scalarmult_vartime( def ge25519_double_scalarmult_vartime(
r: Optional[Ge25519], p1: Ge25519, s1: Sc25519, s2: Sc25519 r: Ge25519 | None, p1: Ge25519, s1: Sc25519, s2: Sc25519
) -> Ge25519: ) -> Ge25519:
""" """
s1 * G + s2 * p1 s1 * G + s2 * p1
@ -224,7 +224,7 @@ def ge25519_double_scalarmult_vartime(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def ge25519_double_scalarmult_vartime2( def ge25519_double_scalarmult_vartime2(
r: Optional[Ge25519], r: Ge25519 | None,
p1: Ge25519, p1: Ge25519,
s1: Sc25519, s1: Sc25519,
p2: Ge25519, p2: Ge25519,
@ -237,7 +237,7 @@ def ge25519_double_scalarmult_vartime2(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def ge25519_scalarmult_base( def ge25519_scalarmult_base(
r: Optional[Ge25519], s: Union[Sc25519, int] r: Ge25519 | None, s: Sc25519 | int
) -> Ge25519: ) -> Ge25519:
""" """
s * G s * G
@ -246,7 +246,7 @@ def ge25519_scalarmult_base(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def ge25519_scalarmult( def ge25519_scalarmult(
r: Optional[Ge25519], p: Ge25519, s: Union[Sc25519, int] r: Ge25519 | None, p: Ge25519, s: Sc25519 | int
) -> Ge25519: ) -> Ge25519:
""" """
s * p s * p
@ -262,7 +262,7 @@ def ge25519_pack(r: bytes, p: Ge25519, offset: int = 0) -> bytes:
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def ge25519_unpack_vartime( def ge25519_unpack_vartime(
r: Optional[Ge25519], buff: bytes, offset: int = 0 r: Ge25519 | None, buff: bytes, offset: int = 0
) -> Ge25519: ) -> Ge25519:
""" """
Point decompression Point decompression
@ -277,7 +277,7 @@ def base58_addr_encode_check(tag: int, buff: bytes) -> bytes:
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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 Monero block base 58 decoding, returning (decoded, tag) or raising on
error. error.
@ -285,21 +285,21 @@ def base58_addr_decode_check(buff: bytes) -> Tuple[bytes, int]:
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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 Generates a random scalar
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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 XMR fast hash
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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: int) -> Ge25519:
""" """
XMR hashing to EC point XMR hashing to EC point
@ -307,7 +307,7 @@ int) -> Ge25519:
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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: offset: int) -> Sc25519:
""" """
XMR hashing to EC scalar XMR hashing to EC scalar
@ -316,7 +316,7 @@ offset: int) -> Sc25519:
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_derivation_to_scalar( def xmr_derivation_to_scalar(
r: Optional[Sc25519], p: Ge25519, output_index: int r: Sc25519 | None, p: Ge25519, output_index: int
) -> Sc25519: ) -> Sc25519:
""" """
H_s(derivation || varint(output_index)) H_s(derivation || varint(output_index))
@ -325,7 +325,7 @@ def xmr_derivation_to_scalar(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_generate_key_derivation( def xmr_generate_key_derivation(
r: Optional[Ge25519], A: Ge25519, b: Sc25519 r: Ge25519 | None, A: Ge25519, b: Sc25519
) -> Ge25519: ) -> Ge25519:
""" """
8*(key2*key1) 8*(key2*key1)
@ -334,7 +334,7 @@ def xmr_generate_key_derivation(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_derive_private_key( def xmr_derive_private_key(
r: Optional[Sc25519], deriv: Ge25519, idx: int, base: Sc25519 r: Sc25519 | None, deriv: Ge25519, idx: int, base: Sc25519
) -> Sc25519: ) -> Sc25519:
""" """
base + H_s(derivation || varint(output_index)) base + H_s(derivation || varint(output_index))
@ -343,7 +343,7 @@ def xmr_derive_private_key(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_derive_public_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: ) -> Ge25519:
""" """
H_s(derivation || varint(output_index))G + base H_s(derivation || varint(output_index))G + base
@ -352,7 +352,7 @@ def xmr_derive_public_key(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_add_keys2( def xmr_add_keys2(
r: Optional[Ge25519], a: Sc25519, b: Sc25519, B: Ge25519 r: Ge25519 | None, a: Sc25519, b: Sc25519, B: Ge25519
) -> Ge25519: ) -> Ge25519:
""" """
aG + bB, G is basepoint aG + bB, G is basepoint
@ -361,7 +361,7 @@ def xmr_add_keys2(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_add_keys2_vartime( def xmr_add_keys2_vartime(
r: Optional[Ge25519], a: Sc25519, b: Sc25519, B: Ge25519 r: Ge25519 | None, a: Sc25519, b: Sc25519, B: Ge25519
) -> Ge25519: ) -> Ge25519:
""" """
aG + bB, G is basepoint aG + bB, G is basepoint
@ -370,7 +370,7 @@ def xmr_add_keys2_vartime(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_add_keys3( 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: ) -> Ge25519:
""" """
aA + bB aA + bB
@ -379,7 +379,7 @@ def xmr_add_keys3(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_add_keys3_vartime( 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: ) -> Ge25519:
""" """
aA + bB aA + bB
@ -388,7 +388,7 @@ def xmr_add_keys3_vartime(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_get_subaddress_secret_key( 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: ) -> Sc25519:
""" """
Hs(SubAddr || a || index_major || index_minor) Hs(SubAddr || a || index_major || index_minor)
@ -396,7 +396,7 @@ def xmr_get_subaddress_secret_key(
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h # 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 aG + amount * H
""" """

@ -22,7 +22,7 @@ def sign(
secret_key: bytes, secret_key: bytes,
digest: bytes, digest: bytes,
compressed: bool = True, compressed: bool = True,
canonical: Optional[int] = None, canonical: int | None = None,
) -> bytes: ) -> bytes:
""" """
Uses secret key to produce the signature of the digest. Uses secret key to produce the signature of the digest.

@ -2,7 +2,7 @@ from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-shamir.h # 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)). Returns f(x) given the Shamir shares (x_1, f(x_1)), ... , (x_k, f(x_k)).
:param shares: The Shamir shares. :param shares: The Shamir shares.

@ -69,7 +69,7 @@ class HID:
# extmod/modtrezorio/modtrezorio-poll.h # 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 Wait until one of `ifaces` is ready to read or write (using masks
`list_ref`: `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. Registers passed interface into the USB stack.
""" """

@ -51,9 +51,9 @@ class FatFSFile:
from types import TracebackType from types import TracebackType
def __exit__( def __exit__(
self, type: Optional[Type[BaseException]], self, type: type[BaseException] | None,
value: Optional[BaseException], value: BaseException | None,
traceback: Optional[TracebackType], traceback: TracebackType | None,
) -> None: ) -> None:
""" """
Close an open file object Close an open file object
@ -69,7 +69,7 @@ class FatFSFile:
Read data from the file 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 Write data to the file
""" """
@ -91,12 +91,12 @@ class FatFSFile:
# extmod/modtrezorio/modtrezorio-fatfs.h # extmod/modtrezorio/modtrezorio-fatfs.h
class FatFSDir(Iterator[Tuple[int, str, str]]): class FatFSDir(Iterator[tuple[int, str, str]]):
""" """
Class encapsulating directory Class encapsulating directory
""" """
def __next__(self) -> Tuple[int, str, str]: def __next__(self) -> tuple[int, str, str]:
""" """
Read an entry in the directory Read an entry in the directory
""" """
@ -131,7 +131,7 @@ def unlink(path: str) -> None:
# extmod/modtrezorio/modtrezorio-fatfs.h # extmod/modtrezorio/modtrezorio-fatfs.h
def stat(path: str) -> Tuple[int, str, str]: def stat(path: str) -> tuple[int, str, str]:
""" """
Get file status Get file status
""" """

@ -40,8 +40,8 @@ class Display:
w: int, w: int,
h: int, h: int,
fgcolor: int, fgcolor: int,
bgcolor: Optional[int] = None, bgcolor: int | None = None,
radius: Optional[int] = None, radius: int | None = None,
) -> None: ) -> None:
""" """
Renders a rounded bar at position (x,y = upper left corner) with width w 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. 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 Returns tuple containing TOIF image dimensions: width, height, and
whether it is grayscale. whether it is grayscale.
@ -89,8 +89,8 @@ class Display:
yoffset: int, yoffset: int,
fgcolor: int, fgcolor: int,
bgcolor: int, bgcolor: int,
icon: Optional[bytes] = None, icon: bytes | None = None,
iconfgcolor: Optional[int] = None, iconfgcolor: int | None = None,
) -> None: ) -> None:
""" """
Renders a rotating loader graphic. Renders a rotating loader graphic.
@ -114,8 +114,8 @@ class Display:
font: int, font: int,
fgcolor: int, fgcolor: int,
bgcolor: int, bgcolor: int,
text_offset: Optional[int] = None, text_offset: int | None = None,
text_len: Optional[int] = None, text_len: int | None = None,
) -> None: ) -> None:
""" """
Renders left-aligned text at position (x,y) where x is left position and Renders left-aligned text at position (x,y) where x is left position and
@ -159,8 +159,8 @@ class Display:
self, self,
text: str, text: str,
font: int, font: int,
text_offset: Optional[int] = None, text_offset: int | None = None,
text_len: Optional[int] = None, text_len: int | None = None,
) -> int: ) -> int:
""" """
Returns a width of text in pixels. Font font is used for rendering. Returns a width of text in pixels. Font font is used for rendering.
@ -181,7 +181,7 @@ class Display:
Scale determines a zoom factor. 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. Sets display orientation to 0, 90, 180 or 270 degrees.
Everything needs to be redrawn again when this function is used. Everything needs to be redrawn again when this function is used.
@ -189,13 +189,13 @@ class Display:
value. 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. Sets backlight intensity to the value specified in val.
Call without the val parameter to just perform the read of the value. 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. Sets offset (x, y) for all subsequent drawing calls.
Call without the xy parameter to just perform the read of the value. Call without the xy parameter to just perform the read of the value.

@ -13,11 +13,11 @@ def consteq(sec: bytes, pub: bytes) -> bool:
# extmod/modtrezorutils/modtrezorutils.c # extmod/modtrezorutils/modtrezorutils.c
def memcpy( def memcpy(
dst: Union[bytearray, memoryview], dst: bytearray | memoryview,
dst_ofs: int, dst_ofs: int,
src: bytes, src: bytes,
src_ofs: int, src_ofs: int,
n: Optional[int] = None, n: int | None = None,
) -> int: ) -> int:
""" """
Copies at most `n` bytes from `src` at offset `src_ofs` to Copies at most `n` bytes from `src` at offset `src_ofs` to
@ -28,7 +28,7 @@ def memcpy(
# extmod/modtrezorutils/modtrezorutils.c # extmod/modtrezorutils/modtrezorutils.c
def halt(msg: Optional[str] = None) -> None: def halt(msg: str | None = None) -> None:
""" """
Halts execution. Halts execution.
""" """

@ -14,7 +14,7 @@ from apps.common.request_pin import verify_user_pin
if False: if False:
import protobuf import protobuf
from typing import Iterable, NoReturn, Optional, Protocol from typing import Iterable, NoReturn, Protocol
from trezor.messages.Initialize import Initialize from trezor.messages.Initialize import Initialize
from trezor.messages.EndSession import EndSession from trezor.messages.EndSession import EndSession
from trezor.messages.GetFeatures import GetFeatures 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( def get_pinlocked_handler(
iface: wire.WireInterface, msg_type: int 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) orig_handler = wire.find_registered_workflow_handler(iface, msg_type)
if orig_handler is None: if orig_handler is None:
return None return None

@ -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 from .scripts import output_script_multisig, output_script_native_p2wpkh_or_p2wsh
if False: if False:
from typing import List, Optional
from trezor.crypto import bip32 from trezor.crypto import bip32
from trezor.messages.TxInputType import EnumTypeInputScriptType from trezor.messages.TxInputType import EnumTypeInputScriptType
@ -21,7 +20,7 @@ def get_address(
script_type: EnumTypeInputScriptType, script_type: EnumTypeInputScriptType,
coin: CoinInfo, coin: CoinInfo,
node: bip32.HDNode, node: bip32.HDNode,
multisig: Optional[MultisigRedeemScriptType] = None, multisig: MultisigRedeemScriptType | None = None,
) -> str: ) -> str:
if multisig: if multisig:
# Ensure that our public key is included in the multisig. # Ensure that our public key is included in the multisig.
@ -74,7 +73,7 @@ def get_address(
raise wire.ProcessError("Invalid script type") 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: if coin.address_type_p2sh is None:
raise wire.ProcessError("Multisig not enabled on this coin") raise wire.ProcessError("Multisig not enabled on this coin")
redeem_script = output_script_multisig(pubkeys, m) 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) 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: if coin.address_type_p2sh is None:
raise wire.ProcessError("Multisig not enabled on this coin") raise wire.ProcessError("Multisig not enabled on this coin")
witness_script = output_script_multisig(pubkeys, m) 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) 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: if not hrp:
raise wire.ProcessError("Multisig not enabled on this coin") raise wire.ProcessError("Multisig not enabled on this coin")
witness_script = output_script_multisig(pubkeys, m) witness_script = output_script_multisig(pubkeys, m)

@ -8,7 +8,6 @@ from trezor.utils import ensure
if False: if False:
from apps.common.coininfo import CoinInfo from apps.common.coininfo import CoinInfo
from typing import Dict
from trezor.messages.TxInput import EnumTypeInputScriptType, TxInput from trezor.messages.TxInput import EnumTypeInputScriptType, TxInput
from trezor.messages.TxOutput import EnumTypeOutputScriptType from trezor.messages.TxOutput import EnumTypeOutputScriptType
@ -35,7 +34,7 @@ MULTISIG_OUTPUT_SCRIPT_TYPES = (
OutputScriptType.PAYTOWITNESS, OutputScriptType.PAYTOWITNESS,
) )
CHANGE_OUTPUT_TO_INPUT_SCRIPT_TYPES: Dict[ CHANGE_OUTPUT_TO_INPUT_SCRIPT_TYPES: dict[
EnumTypeOutputScriptType, EnumTypeInputScriptType EnumTypeOutputScriptType, EnumTypeInputScriptType
] = { ] = {
OutputScriptType.PAYTOADDRESS: InputScriptType.SPENDADDRESS, OutputScriptType.PAYTOADDRESS: InputScriptType.SPENDADDRESS,

@ -11,7 +11,6 @@ from .keychain import validate_path_against_script_type, with_keychain
from .multisig import multisig_pubkey_index from .multisig import multisig_pubkey_index
if False: if False:
from typing import List
from trezor.messages.GetAddress import GetAddress from trezor.messages.GetAddress import GetAddress
from trezor.messages.HDNodeType import HDNodeType from trezor.messages.HDNodeType import HDNodeType
from trezor import wire from trezor import wire
@ -20,8 +19,8 @@ if False:
def _get_xpubs( def _get_xpubs(
coin: CoinInfo, xpub_magic: int, pubnodes: List[HDNodeType] coin: CoinInfo, xpub_magic: int, pubnodes: list[HDNodeType]
) -> List[str]: ) -> list[str]:
result = [] result = []
for pubnode in pubnodes: for pubnode in pubnodes:
node = bip32.HDNode( node = bip32.HDNode(

@ -12,7 +12,6 @@ from .keychain import validate_path_against_script_type, with_keychain
from .ownership import generate_proof, get_identifier from .ownership import generate_proof, get_identifier
if False: if False:
from typing import Optional
from apps.common.coininfo import CoinInfo from apps.common.coininfo import CoinInfo
from apps.common.keychain import Keychain from apps.common.keychain import Keychain
from .authorization import CoinJoinAuthorization from .authorization import CoinJoinAuthorization
@ -27,7 +26,7 @@ async def get_ownership_proof(
msg: GetOwnershipProof, msg: GetOwnershipProof,
keychain: Keychain, keychain: Keychain,
coin: CoinInfo, coin: CoinInfo,
authorization: Optional[CoinJoinAuthorization] = None, authorization: CoinJoinAuthorization | None = None,
) -> OwnershipProof: ) -> OwnershipProof:
if authorization: if authorization:
if not authorization.check_get_ownership_proof(msg): if not authorization.check_get_ownership_proof(msg):

@ -8,7 +8,7 @@ from apps.common.paths import PATTERN_BIP44, PathSchema
from .common import BITCOIN_NAMES from .common import BITCOIN_NAMES
if False: 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 typing_extensions import Protocol
from trezor.messages.TxInputType import EnumTypeInputScriptType from trezor.messages.TxInputType import EnumTypeInputScriptType
@ -23,8 +23,8 @@ if False:
class MsgWithAddressScriptType(Protocol): class MsgWithAddressScriptType(Protocol):
# XXX should be Bip32Path but that fails # XXX should be Bip32Path but that fails
address_n = ... # type: List[int] address_n: list[int] = ...
script_type = ... # type: EnumTypeInputScriptType script_type: EnumTypeInputScriptType = ...
MsgIn = TypeVar("MsgIn", bound=MsgWithCoinName) MsgIn = TypeVar("MsgIn", bound=MsgWithCoinName)
HandlerWithCoinInfo = Callable[..., Awaitable[MsgOut]] 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( def validate_path_against_script_type(
coin: coininfo.CoinInfo, coin: coininfo.CoinInfo,
msg: Optional[MsgWithAddressScriptType] = None, msg: MsgWithAddressScriptType | None = None,
address_n: Optional[Bip32Path] = None, address_n: Bip32Path | None = None,
script_type: Optional[EnumTypeInputScriptType] = None, script_type: EnumTypeInputScriptType | None = None,
multisig: bool = False, multisig: bool = False,
) -> bool: ) -> bool:
patterns = [] patterns = []
@ -162,7 +162,7 @@ def get_schemas_for_coin(coin: coininfo.CoinInfo) -> Iterable[PathSchema]:
return schemas 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: if coin_name is None:
coin_name = "Bitcoin" coin_name = "Bitcoin"
@ -173,8 +173,8 @@ def get_coin_by_name(coin_name: Optional[str]) -> coininfo.CoinInfo:
async def get_keychain_for_coin( async def get_keychain_for_coin(
ctx: wire.Context, coin_name: Optional[str] ctx: wire.Context, coin_name: str | None
) -> Tuple[Keychain, coininfo.CoinInfo]: ) -> tuple[Keychain, coininfo.CoinInfo]:
coin = get_coin_by_name(coin_name) coin = get_coin_by_name(coin_name)
schemas = get_schemas_for_coin(coin) schemas = get_schemas_for_coin(coin)
slip21_namespaces = [[b"SLIP-0019"]] slip21_namespaces = [[b"SLIP-0019"]]
@ -186,7 +186,7 @@ def with_keychain(func: HandlerWithCoinInfo[MsgOut]) -> Handler[MsgIn, MsgOut]:
async def wrapper( async def wrapper(
ctx: wire.Context, ctx: wire.Context,
msg: MsgIn, msg: MsgIn,
authorization: Optional[CoinJoinAuthorization] = None, authorization: CoinJoinAuthorization | None = None,
) -> MsgOut: ) -> MsgOut:
if authorization: if authorization:
keychain = authorization.keychain keychain = authorization.keychain

@ -9,9 +9,6 @@ from apps.common import paths
from .writers import write_bytes_fixed, write_uint32 from .writers import write_bytes_fixed, write_uint32
if False:
from typing import List
def multisig_fingerprint(multisig: MultisigRedeemScriptType) -> bytes: def multisig_fingerprint(multisig: MultisigRedeemScriptType) -> bytes:
if multisig.nodes: if multisig.nodes:
@ -78,7 +75,7 @@ def multisig_get_pubkey(n: HDNodeType, p: paths.Bip32Path) -> bytes:
return node.public_key() return node.public_key()
def multisig_get_pubkeys(multisig: MultisigRedeemScriptType) -> List[bytes]: def multisig_get_pubkeys(multisig: MultisigRedeemScriptType) -> list[bytes]:
validate_multisig(multisig) validate_multisig(multisig)
if multisig.nodes: if multisig.nodes:
return [multisig_get_pubkey(hd, multisig.address_n) for hd in multisig.nodes] return [multisig_get_pubkey(hd, multisig.address_n) for hd in multisig.nodes]

@ -15,7 +15,6 @@ from .scripts import read_bip322_signature_proof, write_bip322_signature_proof
from .verification import SignatureVerifier from .verification import SignatureVerifier
if False: if False:
from typing import List, Optional, Tuple
from trezor.messages.MultisigRedeemScriptType import MultisigRedeemScriptType from trezor.messages.MultisigRedeemScriptType import MultisigRedeemScriptType
from trezor.messages.TxInputType import EnumTypeInputScriptType from trezor.messages.TxInputType import EnumTypeInputScriptType
from apps.common.coininfo import CoinInfo from apps.common.coininfo import CoinInfo
@ -33,13 +32,13 @@ _OWNERSHIP_ID_KEY_PATH = [b"SLIP-0019", b"Ownership identification key"]
def generate_proof( def generate_proof(
node: bip32.HDNode, node: bip32.HDNode,
script_type: EnumTypeInputScriptType, script_type: EnumTypeInputScriptType,
multisig: Optional[MultisigRedeemScriptType], multisig: MultisigRedeemScriptType | None,
coin: CoinInfo, coin: CoinInfo,
user_confirmed: bool, user_confirmed: bool,
ownership_ids: List[bytes], ownership_ids: list[bytes],
script_pubkey: bytes, script_pubkey: bytes,
commitment_data: bytes, commitment_data: bytes,
) -> Tuple[bytes, bytes]: ) -> tuple[bytes, bytes]:
flags = 0 flags = 0
if user_confirmed: if user_confirmed:
flags |= _FLAG_USER_CONFIRMED flags |= _FLAG_USER_CONFIRMED
@ -67,7 +66,7 @@ def generate_proof(
def verify_nonownership( def verify_nonownership(
proof: bytes, proof: bytes,
script_pubkey: bytes, script_pubkey: bytes,
commitment_data: Optional[bytes], commitment_data: bytes | None,
keychain: Keychain, keychain: Keychain,
coin: CoinInfo, coin: CoinInfo,
) -> bool: ) -> bool:

@ -22,8 +22,6 @@ from .writers import (
) )
if False: if False:
from typing import List, Optional, Tuple
from trezor.messages.MultisigRedeemScriptType import MultisigRedeemScriptType from trezor.messages.MultisigRedeemScriptType import MultisigRedeemScriptType
from trezor.messages.TxInput import TxInput from trezor.messages.TxInput import TxInput
from trezor.messages.TxInput import EnumTypeInputScriptType from trezor.messages.TxInput import EnumTypeInputScriptType
@ -35,7 +33,7 @@ if False:
def input_derive_script( def input_derive_script(
script_type: EnumTypeInputScriptType, script_type: EnumTypeInputScriptType,
multisig: Optional[MultisigRedeemScriptType], multisig: MultisigRedeemScriptType | None,
coin: CoinInfo, coin: CoinInfo,
hash_type: int, hash_type: int,
pubkey: bytes, 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 # see https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki#specification
# item 5 for details # item 5 for details
def bip143_derive_script_code( 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: ) -> bytearray:
if len(public_keys) > 1: if len(public_keys) > 1:
return output_script_multisig(public_keys, threshold) return output_script_multisig(public_keys, threshold)
@ -149,7 +147,7 @@ def input_script_p2pkh_or_p2sh(
return w 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: try:
r = utils.BufferReader(script_sig) r = utils.BufferReader(script_sig)
n = read_op_push(r) n = read_op_push(r)
@ -276,7 +274,7 @@ def witness_p2wpkh(signature: bytes, pubkey: bytes, hash_type: int) -> bytearray
return w return w
def parse_witness_p2wpkh(witness: bytes) -> Tuple[bytes, bytes, int]: def parse_witness_p2wpkh(witness: bytes) -> tuple[bytes, bytes, int]:
try: try:
r = utils.BufferReader(witness) r = utils.BufferReader(witness)
@ -346,7 +344,7 @@ def witness_multisig(
return w 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: try:
r = utils.BufferReader(witness) r = utils.BufferReader(witness)
@ -421,7 +419,7 @@ def input_script_multisig(
def parse_input_script_multisig( def parse_input_script_multisig(
script_sig: bytes, script_sig: bytes,
) -> Tuple[bytes, List[Tuple[bytes, int]]]: ) -> tuple[bytes, list[tuple[bytes, int]]]:
try: try:
r = utils.BufferReader(script_sig) r = utils.BufferReader(script_sig)
@ -446,13 +444,13 @@ def parse_input_script_multisig(
return script, signatures 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)) w = empty_bytearray(output_script_multisig_length(pubkeys, m))
write_output_script_multisig(w, pubkeys, m) write_output_script_multisig(w, pubkeys, m)
return w 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) n = len(pubkeys)
if n < 1 or n > 15 or m < 1 or m > 15 or m > n: if n < 1 or n > 15 or m < 1 or m > 15 or m > n:
raise wire.DataError("Invalid multisig parameters") 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 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 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: try:
r = utils.BufferReader(script) r = utils.BufferReader(script)
@ -524,7 +522,7 @@ def output_script_paytoopreturn(data: bytes) -> bytearray:
def write_bip322_signature_proof( def write_bip322_signature_proof(
w: Writer, w: Writer,
script_type: EnumTypeInputScriptType, script_type: EnumTypeInputScriptType,
multisig: Optional[MultisigRedeemScriptType], multisig: MultisigRedeemScriptType | None,
coin: CoinInfo, coin: CoinInfo,
public_key: bytes, public_key: bytes,
signature: bytes, signature: bytes,
@ -549,7 +547,7 @@ def write_bip322_signature_proof(
w.extend(witness) 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) script_sig = read_bytes_prefixed(r)
witness = r.read() witness = r.read()
return script_sig, witness return script_sig, witness

@ -15,8 +15,6 @@ from .scripts import ( # noqa: F401
from .writers import write_op_push from .writers import write_op_push
if False: if False:
from typing import Optional
from trezor.messages.MultisigRedeemScriptType import MultisigRedeemScriptType from trezor.messages.MultisigRedeemScriptType import MultisigRedeemScriptType
from trezor.messages.TxInput import EnumTypeInputScriptType from trezor.messages.TxInput import EnumTypeInputScriptType
@ -25,7 +23,7 @@ if False:
def input_derive_script( def input_derive_script(
script_type: EnumTypeInputScriptType, script_type: EnumTypeInputScriptType,
multisig: Optional[MultisigRedeemScriptType], multisig: MultisigRedeemScriptType | None,
coin: CoinInfo, coin: CoinInfo,
hash_type: int, hash_type: int,
pubkey: bytes, pubkey: bytes,

@ -10,7 +10,7 @@ if not utils.BITCOIN_ONLY:
from . import bitcoinlike, decred, zcash from . import bitcoinlike, decred, zcash
if False: if False:
from typing import Protocol, Optional, Type, Union from typing import Protocol, Union
from protobuf import FieldCache from protobuf import FieldCache
@ -42,7 +42,7 @@ if False:
tx: SignTx, tx: SignTx,
keychain: Keychain, keychain: Keychain,
coin: CoinInfo, coin: CoinInfo,
approver: Optional[approvers.Approver], approver: approvers.Approver | None,
) -> None: ) -> None:
... ...
@ -56,14 +56,14 @@ async def sign_tx(
msg: SignTx, msg: SignTx,
keychain: Keychain, keychain: Keychain,
coin: CoinInfo, coin: CoinInfo,
authorization: Optional[CoinJoinAuthorization] = None, authorization: CoinJoinAuthorization | None = None,
) -> TxRequest: ) -> TxRequest:
approver: Optional[approvers.Approver] = None approver: approvers.Approver | None = None
if authorization: if authorization:
approver = approvers.CoinJoinApprover(msg, coin, authorization) approver = approvers.CoinJoinApprover(msg, coin, authorization)
if utils.BITCOIN_ONLY or coin.coin_name in BITCOIN_NAMES: if utils.BITCOIN_ONLY or coin.coin_name in BITCOIN_NAMES:
signer_class: Type[SignerClass] = bitcoin.Bitcoin signer_class: type[SignerClass] = bitcoin.Bitcoin
else: else:
if coin.decred: if coin.decred:
signer_class = decred.Decred signer_class = decred.Decred
@ -74,7 +74,7 @@ async def sign_tx(
signer = signer_class(msg, keychain, coin, approver).signer() signer = signer_class(msg, keychain, coin, approver).signer()
res: Union[TxAckType, bool, None] = None res: TxAckType | bool | None = None
field_cache: FieldCache = {} field_cache: FieldCache = {}
while True: while True:
req = signer.send(res) req = signer.send(res)

@ -11,7 +11,6 @@ from . import helpers, tx_weight
from .tx_info import OriginalTxInfo, TxInfo from .tx_info import OriginalTxInfo, TxInfo
if False: if False:
from typing import List, Optional
from trezor.messages.SignTx import SignTx from trezor.messages.SignTx import SignTx
from trezor.messages.TxInput import TxInput from trezor.messages.TxInput import TxInput
from trezor.messages.TxOutput import TxOutput from trezor.messages.TxOutput import TxOutput
@ -77,7 +76,7 @@ class Approver:
self, self,
txo: TxOutput, txo: TxOutput,
script_pubkey: bytes, script_pubkey: bytes,
orig_txo: Optional[TxOutput] = None, orig_txo: TxOutput | None = None,
) -> None: ) -> None:
self.weight.add_output(script_pubkey) self.weight.add_output(script_pubkey)
self.total_out += txo.amount self.total_out += txo.amount
@ -86,11 +85,11 @@ class Approver:
self.orig_total_out += txo.amount self.orig_total_out += txo.amount
async def approve_orig_txids( async def approve_orig_txids(
self, tx_info: TxInfo, orig_txs: List[OriginalTxInfo] self, tx_info: TxInfo, orig_txs: list[OriginalTxInfo]
) -> None: ) -> None:
raise NotImplementedError 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 raise NotImplementedError
@ -116,7 +115,7 @@ class BasicApprover(Approver):
self, self,
txo: TxOutput, txo: TxOutput,
script_pubkey: bytes, script_pubkey: bytes,
orig_txo: Optional[TxOutput] = None, orig_txo: TxOutput | None = None,
) -> None: ) -> None:
await super().add_external_output(txo, script_pubkey, orig_txo) 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) await helpers.confirm_output(txo, self.coin, self.amount_unit)
async def approve_orig_txids( async def approve_orig_txids(
self, tx_info: TxInfo, orig_txs: List[OriginalTxInfo] self, tx_info: TxInfo, orig_txs: list[OriginalTxInfo]
) -> None: ) -> None:
if not orig_txs: if not orig_txs:
return return
@ -173,7 +172,7 @@ class BasicApprover(Approver):
for orig in orig_txs: for orig in orig_txs:
await helpers.confirm_replacement(description, orig.orig_hash) 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 fee = self.total_in - self.total_out
# some coins require negative fees for reward TX # some coins require negative fees for reward TX
@ -301,17 +300,17 @@ class CoinJoinApprover(Approver):
self, self,
txo: TxOutput, txo: TxOutput,
script_pubkey: bytes, script_pubkey: bytes,
orig_txo: Optional[TxOutput] = None, orig_txo: TxOutput | None = None,
) -> None: ) -> None:
await super().add_external_output(txo, script_pubkey, orig_txo) await super().add_external_output(txo, script_pubkey, orig_txo)
self._add_output(txo, script_pubkey) self._add_output(txo, script_pubkey)
async def approve_orig_txids( async def approve_orig_txids(
self, tx_info: TxInfo, orig_txs: List[OriginalTxInfo] self, tx_info: TxInfo, orig_txs: list[OriginalTxInfo]
) -> None: ) -> None:
pass 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. # The mining fee of the transaction as a whole.
mining_fee = self.total_in - self.total_out mining_fee = self.total_in - self.total_out

@ -19,7 +19,6 @@ from .hash143 import Bip143Hash
from .tx_info import OriginalTxInfo, TxInfo from .tx_info import OriginalTxInfo, TxInfo
if False: if False:
from typing import List, Optional, Set, Tuple, Union
from trezor.crypto import bip32 from trezor.crypto import bip32
from trezor.messages.SignTx import SignTx from trezor.messages.SignTx import SignTx
@ -76,7 +75,7 @@ class Bitcoin:
tx: SignTx, tx: SignTx,
keychain: Keychain, keychain: Keychain,
coin: CoinInfo, coin: CoinInfo,
approver: Optional[approvers.Approver], approver: approvers.Approver | None,
) -> None: ) -> None:
self.tx_info = TxInfo(self, helpers.sanitize_sign_tx(tx, coin)) self.tx_info = TxInfo(self, helpers.sanitize_sign_tx(tx, coin))
self.keychain = keychain self.keychain = keychain
@ -88,10 +87,10 @@ class Bitcoin:
self.approver = approvers.BasicApprover(tx, coin) self.approver = approvers.BasicApprover(tx, coin)
# set of indices of inputs which are segwit # 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 # set of indices of inputs which are external
self.external: Set[int] = set() self.external: set[int] = set()
# transaction and signature serialization # transaction and signature serialization
self.serialized_tx = writers.empty_bytearray(_MAX_SERIALIZED_CHUNK_SIZE) 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 # 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 # undefined so we would need to convert to a sorted list in several places to ensure
# stable device tests. # 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 # 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 # is used to ensure that the inputs streamed for verification in Step 3 are
# the same as those in Step 1. # 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) progress.init(tx.inputs_count, tx.outputs_count)
@ -152,7 +151,7 @@ class Bitcoin:
# STAGE_REQUEST_2_OUTPUT in legacy # STAGE_REQUEST_2_OUTPUT in legacy
txo = await helpers.request_tx_output(self.tx_req, i, self.coin) txo = await helpers.request_tx_output(self.tx_req, i, self.coin)
script_pubkey = self.output_derive_script(txo) script_pubkey = self.output_derive_script(txo)
orig_txo = None # type: Optional[TxOutput] orig_txo: TxOutput | None = None
if txo.orig_hash: if txo.orig_hash:
orig_txo = await self.get_original_output(txo, script_pubkey) orig_txo = await self.get_original_output(txo, script_pubkey)
await self.approve_output(txo, script_pubkey, orig_txo) await self.approve_output(txo, script_pubkey, orig_txo)
@ -378,7 +377,7 @@ class Bitcoin:
self, self,
txo: TxOutput, txo: TxOutput,
script_pubkey: bytes, script_pubkey: bytes,
orig_txo: Optional[TxOutput], orig_txo: TxOutput | None,
) -> None: ) -> None:
if self.tx_info.output_is_change(txo): if self.tx_info.output_is_change(txo):
# Output is change and does not need approval. # Output is change and does not need approval.
@ -392,8 +391,8 @@ class Bitcoin:
self, self,
i: int, i: int,
txi: TxInput, txi: TxInput,
tx_info: Union[TxInfo, OriginalTxInfo], tx_info: TxInfo | OriginalTxInfo,
public_keys: List[bytes], public_keys: list[bytes],
threshold: int, threshold: int,
script_pubkey: bytes, script_pubkey: bytes,
) -> bytes: ) -> bytes:
@ -459,7 +458,7 @@ class Bitcoin:
script_sig = self.input_derive_script(txi, key_sign_pub, b"") script_sig = self.input_derive_script(txi, key_sign_pub, b"")
self.write_tx_input(self.serialized_tx, txi, script_sig) 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) self.tx_info.check_input(txi)
node = self.keychain.derive(txi.address_n) node = self.keychain.derive(txi.address_n)
@ -510,9 +509,9 @@ class Bitcoin:
async def get_legacy_tx_digest( async def get_legacy_tx_digest(
self, self,
index: int, index: int,
tx_info: Union[TxInfo, OriginalTxInfo], tx_info: TxInfo | OriginalTxInfo,
script_pubkey: Optional[bytes] = None, script_pubkey: bytes | None = None,
) -> Tuple[bytes, TxInput, Optional[bip32.HDNode]]: ) -> tuple[bytes, TxInput, bip32.HDNode | None]:
tx_hash = tx_info.orig_hash if isinstance(tx_info, OriginalTxInfo) else None tx_hash = tx_info.orig_hash if isinstance(tx_info, OriginalTxInfo) else None
# the transaction digest which gets signed for this input # the transaction digest which gets signed for this input
@ -594,7 +593,7 @@ class Bitcoin:
async def get_prevtx_output( async def get_prevtx_output(
self, prev_hash: bytes, prev_index: int self, prev_hash: bytes, prev_index: int
) -> Tuple[int, bytes]: ) -> tuple[int, bytes]:
amount_out = 0 # output amount amount_out = 0 # output amount
# STAGE_REQUEST_3_PREV_META in legacy # STAGE_REQUEST_3_PREV_META in legacy
@ -659,7 +658,7 @@ class Bitcoin:
@staticmethod @staticmethod
def write_tx_input( def write_tx_input(
w: writers.Writer, w: writers.Writer,
txi: Union[TxInput, PrevInput], txi: TxInput | PrevInput,
script: bytes, script: bytes,
) -> None: ) -> None:
writers.write_tx_input(w, txi, script) writers.write_tx_input(w, txi, script)
@ -667,7 +666,7 @@ class Bitcoin:
@staticmethod @staticmethod
def write_tx_output( def write_tx_output(
w: writers.Writer, w: writers.Writer,
txo: Union[TxOutput, PrevOutput], txo: TxOutput | PrevOutput,
script_pubkey: bytes, script_pubkey: bytes,
) -> None: ) -> None:
writers.write_tx_output(w, txo, script_pubkey) writers.write_tx_output(w, txo, script_pubkey)
@ -675,7 +674,7 @@ class Bitcoin:
def write_tx_header( def write_tx_header(
self, self,
w: writers.Writer, w: writers.Writer,
tx: Union[SignTx, PrevTx], tx: SignTx | PrevTx,
witness_marker: bool, witness_marker: bool,
) -> None: ) -> None:
writers.write_uint32(w, tx.version) # nVersion 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, 0x00) # segwit witness marker
write_bitcoin_varint(w, 0x01) # segwit witness flag 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) writers.write_uint32(w, tx.lock_time)
async def write_prev_tx_footer( async def write_prev_tx_footer(

@ -13,7 +13,6 @@ from . import helpers
from .bitcoin import Bitcoin from .bitcoin import Bitcoin
if False: if False:
from typing import List, Optional, Union
from .tx_info import OriginalTxInfo, TxInfo from .tx_info import OriginalTxInfo, TxInfo
_SIGHASH_FORKID = const(0x40) _SIGHASH_FORKID = const(0x40)
@ -46,11 +45,11 @@ class Bitcoinlike(Bitcoin):
self, self,
i: int, i: int,
txi: TxInput, txi: TxInput,
tx_info: Union[TxInfo, OriginalTxInfo], tx_info: TxInfo | OriginalTxInfo,
public_keys: List[bytes], public_keys: list[bytes],
threshold: int, threshold: int,
script_pubkey: bytes, script_pubkey: bytes,
tx_hash: Optional[bytes] = None, tx_hash: bytes | None = None,
) -> bytes: ) -> bytes:
if self.coin.force_bip143: if self.coin.force_bip143:
return tx_info.hash143.preimage_hash( return tx_info.hash143.preimage_hash(
@ -75,7 +74,7 @@ class Bitcoinlike(Bitcoin):
def write_tx_header( def write_tx_header(
self, self,
w: writers.Writer, w: writers.Writer,
tx: Union[SignTx, PrevTx], tx: SignTx | PrevTx,
witness_marker: bool, witness_marker: bool,
) -> None: ) -> None:
writers.write_uint32(w, tx.version) # nVersion writers.write_uint32(w, tx.version) # nVersion

@ -24,8 +24,6 @@ OUTPUT_SCRIPT_NULL_SSTXCHANGE = (
) )
if False: if False:
from typing import Optional, Union, List
from trezor.messages.SignTx import SignTx from trezor.messages.SignTx import SignTx
from trezor.messages.TxInput import TxInput from trezor.messages.TxInput import TxInput
from trezor.messages.TxOutput import TxOutput from trezor.messages.TxOutput import TxOutput
@ -61,9 +59,9 @@ class DecredHash:
def preimage_hash( def preimage_hash(
self, self,
txi: TxInput, txi: TxInput,
public_keys: List[bytes], public_keys: list[bytes],
threshold: int, threshold: int,
tx: Union[SignTx, PrevTx], tx: SignTx | PrevTx,
coin: CoinInfo, coin: CoinInfo,
sighash_type: int, sighash_type: int,
) -> bytes: ) -> bytes:
@ -76,7 +74,7 @@ class Decred(Bitcoin):
tx: SignTx, tx: SignTx,
keychain: Keychain, keychain: Keychain,
coin: CoinInfo, coin: CoinInfo,
approver: Optional[approvers.Approver], approver: approvers.Approver | None,
) -> None: ) -> None:
ensure(coin.decred) ensure(coin.decred)
self.h_prefix = HashWriter(blake256()) self.h_prefix = HashWriter(blake256())
@ -127,7 +125,7 @@ class Decred(Bitcoin):
self, self,
txo: TxOutput, txo: TxOutput,
script_pubkey: bytes, script_pubkey: bytes,
orig_txo: Optional[TxOutput], orig_txo: TxOutput | None,
) -> None: ) -> None:
await super().approve_output(txo, script_pubkey, orig_txo) await super().approve_output(txo, script_pubkey, orig_txo)
self.write_tx_output(self.serialized_tx, txo, script_pubkey) self.write_tx_output(self.serialized_tx, txo, script_pubkey)
@ -213,7 +211,7 @@ class Decred(Bitcoin):
@staticmethod @staticmethod
def write_tx_input( def write_tx_input(
w: writers.Writer, w: writers.Writer,
txi: Union[TxInput, PrevInput], txi: TxInput | PrevInput,
script: bytes, script: bytes,
) -> None: ) -> None:
writers.write_bytes_reversed(w, txi.prev_hash, writers.TX_HASH_SIZE) writers.write_bytes_reversed(w, txi.prev_hash, writers.TX_HASH_SIZE)
@ -224,7 +222,7 @@ class Decred(Bitcoin):
@staticmethod @staticmethod
def write_tx_output( def write_tx_output(
w: writers.Writer, w: writers.Writer,
txo: Union[TxOutput, PrevOutput], txo: TxOutput | PrevOutput,
script_pubkey: bytes, script_pubkey: bytes,
) -> None: ) -> None:
writers.write_uint64(w, txo.amount) writers.write_uint64(w, txo.amount)
@ -288,7 +286,7 @@ class Decred(Bitcoin):
def write_tx_header( def write_tx_header(
self, self,
w: writers.Writer, w: writers.Writer,
tx: Union[SignTx, PrevTx], tx: SignTx | PrevTx,
witness_marker: bool, witness_marker: bool,
) -> None: ) -> None:
# The upper 16 bits of the transaction version specify the serialization # The upper 16 bits of the transaction version specify the serialization
@ -300,7 +298,7 @@ class Decred(Bitcoin):
writers.write_uint32(w, version) 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_* assert tx.expiry is not None # checked in sanitize_*
writers.write_uint32(w, tx.lock_time) writers.write_uint32(w, tx.lock_time)
writers.write_uint32(w, tx.expiry) writers.write_uint32(w, tx.expiry)

@ -10,7 +10,7 @@ from apps.common import coininfo
from .. import scripts, writers from .. import scripts, writers
if False: if False:
from typing import List, Union, Protocol from typing import Protocol
class Hash143(Protocol): class Hash143(Protocol):
def add_input(self, txi: TxInput) -> None: def add_input(self, txi: TxInput) -> None:
@ -22,9 +22,9 @@ if False:
def preimage_hash( def preimage_hash(
self, self,
txi: TxInput, txi: TxInput,
public_keys: List[bytes], public_keys: list[bytes],
threshold: int, threshold: int,
tx: Union[SignTx, PrevTx], tx: SignTx | PrevTx,
coin: coininfo.CoinInfo, coin: coininfo.CoinInfo,
sighash_type: int, sighash_type: int,
) -> bytes: ) -> bytes:
@ -51,9 +51,9 @@ class Bip143Hash:
def preimage_hash( def preimage_hash(
self, self,
txi: TxInput, txi: TxInput,
public_keys: List[bytes], public_keys: list[bytes],
threshold: int, threshold: int,
tx: Union[SignTx, PrevTx], tx: SignTx | PrevTx,
coin: coininfo.CoinInfo, coin: coininfo.CoinInfo,
sighash_type: int, sighash_type: int,
) -> bytes: ) -> bytes:

@ -31,7 +31,7 @@ from ..writers import TX_HASH_SIZE
from . import layout from . import layout
if False: if False:
from typing import Any, Awaitable, Optional from typing import Any, Awaitable
from trezor.messages.SignTx import EnumTypeAmountUnit 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)) 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 assert tx_req.details is not None
tx_req.request_type = TXMETA tx_req.request_type = TXMETA
tx_req.details.tx_hash = tx_hash 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 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]: ) -> Awaitable[bytearray]:
assert tx_req.details is not None assert tx_req.details is not None
tx_req.request_type = TXEXTRADATA tx_req.request_type = TXEXTRADATA
@ -274,7 +274,7 @@ def request_tx_extra_data( # type: ignore
return ack.tx.extra_data_chunk 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 assert tx_req.details is not None
if tx_hash: if tx_hash:
tx_req.request_type = TXORIGINPUT 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) 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 assert tx_req.details is not None
tx_req.request_type = TXINPUT tx_req.request_type = TXINPUT
tx_req.details.request_index = i 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) 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 assert tx_req.details is not None
if tx_hash: if tx_hash:
tx_req.request_type = TXORIGOUTPUT 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) 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 assert tx_req.details is not None
tx_req.request_type = TXOUTPUT tx_req.request_type = TXOUTPUT
tx_req.details.request_index = i tx_req.details.request_index = i

@ -9,8 +9,6 @@ from .. import addresses
from . import omni from . import omni
if False: if False:
from typing import Optional
from trezor import wire from trezor import wire
from trezor.messages.SignTx import EnumTypeAmountUnit from trezor.messages.SignTx import EnumTypeAmountUnit
from trezor.messages.TxOutput import TxOutput from trezor.messages.TxOutput import TxOutput
@ -186,7 +184,7 @@ async def confirm_nondefault_locktime(
if lock_time_disabled: if lock_time_disabled:
title = "Warning" title = "Warning"
text = "Locktime is set but will\nhave no effect.\n" 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: elif lock_time < _LOCKTIME_TIMESTAMP_MIN_VALUE:
title = "Confirm locktime" title = "Confirm locktime"
text = "Locktime for this\ntransaction is set to\nblockheight:\n{}" text = "Locktime for this\ntransaction is set to\nblockheight:\n{}"

@ -5,7 +5,7 @@ from .. import multisig
from ..common import BIP32_WALLET_DEPTH from ..common import BIP32_WALLET_DEPTH
if False: if False:
from typing import Any, Union, Generic, TypeVar from typing import Any, Generic, TypeVar
from trezor.messages.TxInput import TxInput from trezor.messages.TxInput import TxInput
from trezor.messages.TxOutput import TxOutput from trezor.messages.TxOutput import TxOutput
@ -43,10 +43,10 @@ class MatchChecker(Generic[T]):
UNDEFINED = object() UNDEFINED = object()
def __init__(self) -> None: 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(). 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. # 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 # If the txio is invalid for matching, then return an object which
# evaluates as a boolean False. # evaluates as a boolean False.
@ -85,14 +85,14 @@ class MatchChecker(Generic[T]):
class WalletPathChecker(MatchChecker): 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: if len(txio.address_n) < BIP32_WALLET_DEPTH:
return None return None
return txio.address_n[:-BIP32_WALLET_DEPTH] return txio.address_n[:-BIP32_WALLET_DEPTH]
class MultisigFingerprintChecker(MatchChecker): 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: if not txio.multisig:
return None return None
return multisig.multisig_fingerprint(txio.multisig) return multisig.multisig_fingerprint(txio.multisig)

@ -9,7 +9,7 @@ from ..common import BIP32_WALLET_DEPTH, input_is_external
from .matchcheck import MultisigFingerprintChecker, WalletPathChecker from .matchcheck import MultisigFingerprintChecker, WalletPathChecker
if False: if False:
from typing import Optional, Protocol, Union from typing import Protocol
from trezor.messages.SignTx import SignTx from trezor.messages.SignTx import SignTx
from trezor.messages.PrevTx import PrevTx from trezor.messages.PrevTx import PrevTx
from trezor.messages.TxInput import TxInput from trezor.messages.TxInput import TxInput
@ -32,7 +32,7 @@ if False:
def write_tx_header( def write_tx_header(
self, self,
w: writers.Writer, w: writers.Writer,
tx: Union[SignTx, PrevTx], tx: SignTx | PrevTx,
witness_marker: bool, witness_marker: bool,
) -> None: ) -> None:
... ...
@ -40,7 +40,7 @@ if False:
@staticmethod @staticmethod
def write_tx_input( def write_tx_input(
w: writers.Writer, w: writers.Writer,
txi: Union[TxInput, PrevInput], txi: TxInput | PrevInput,
script: bytes, script: bytes,
) -> None: ) -> None:
... ...
@ -48,7 +48,7 @@ if False:
@staticmethod @staticmethod
def write_tx_output( def write_tx_output(
w: writers.Writer, w: writers.Writer,
txo: Union[TxOutput, PrevOutput], txo: TxOutput | PrevOutput,
script_pubkey: bytes, script_pubkey: bytes,
) -> None: ) -> None:
... ...
@ -160,8 +160,8 @@ class OriginalTxInfo(TxInfoBase):
writers.write_bitcoin_varint(self.h_tx, tx.inputs_count) 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. # The input which will be used for verification and its index in the original transaction.
self.verification_input = None # type: Optional[TxInput] self.verification_input: TxInput | None = None
self.verification_index = None # type: Optional[int] self.verification_index: int | None = None
def add_input(self, txi: TxInput) -> None: def add_input(self, txi: TxInput) -> None:
super().add_input(txi) super().add_input(txi)

@ -31,7 +31,6 @@ from .bitcoinlike import Bitcoinlike
if False: if False:
from apps.common import coininfo from apps.common import coininfo
from typing import List, Optional, Union
from .hash143 import Hash143 from .hash143 import Hash143
from .tx_info import OriginalTxInfo, TxInfo from .tx_info import OriginalTxInfo, TxInfo
from ..writers import Writer from ..writers import Writer
@ -56,9 +55,9 @@ class Zip243Hash:
def preimage_hash( def preimage_hash(
self, self,
txi: TxInput, txi: TxInput,
public_keys: List[bytes], public_keys: list[bytes],
threshold: int, threshold: int,
tx: Union[SignTx, PrevTx], tx: SignTx | PrevTx,
coin: coininfo.CoinInfo, coin: coininfo.CoinInfo,
sighash_type: int, sighash_type: int,
) -> bytes: ) -> bytes:
@ -145,11 +144,11 @@ class Zcashlike(Bitcoinlike):
self, self,
i: int, i: int,
txi: TxInput, txi: TxInput,
tx_info: Union[TxInfo, OriginalTxInfo], tx_info: TxInfo | OriginalTxInfo,
public_keys: List[bytes], public_keys: list[bytes],
threshold: int, threshold: int,
script_pubkey: bytes, script_pubkey: bytes,
tx_hash: Optional[bytes] = None, tx_hash: bytes | None = None,
) -> bytes: ) -> bytes:
return tx_info.hash143.preimage_hash( return tx_info.hash143.preimage_hash(
txi, txi,
@ -161,7 +160,7 @@ class Zcashlike(Bitcoinlike):
) )
def write_tx_header( def write_tx_header(
self, w: Writer, tx: Union[SignTx, PrevTx], witness_marker: bool self, w: Writer, tx: SignTx | PrevTx, witness_marker: bool
) -> None: ) -> None:
if tx.version < 3: if tx.version < 3:
# pre-overwinter # pre-overwinter
@ -173,7 +172,7 @@ class Zcashlike(Bitcoinlike):
write_uint32(w, tx.version | OVERWINTERED) write_uint32(w, tx.version | OVERWINTERED)
write_uint32(w, tx.version_group_id) # nVersionGroupId 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_* assert tx.expiry is not None # checked in sanitize_*
write_uint32(w, tx.lock_time) write_uint32(w, tx.lock_time)
if tx.version >= 3: if tx.version >= 3:
@ -181,7 +180,7 @@ class Zcashlike(Bitcoinlike):
def derive_script_code( 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: ) -> bytearray:
if len(public_keys) > 1: if len(public_keys) > 1:
return output_script_multisig(public_keys, threshold) return output_script_multisig(public_keys, threshold)

@ -18,7 +18,6 @@ from .scripts import (
) )
if False: if False:
from typing import List, Optional, Tuple
from apps.common.coininfo import CoinInfo from apps.common.coininfo import CoinInfo
@ -26,13 +25,13 @@ class SignatureVerifier:
def __init__( def __init__(
self, self,
script_pubkey: bytes, script_pubkey: bytes,
script_sig: Optional[bytes], script_sig: bytes | None,
witness: Optional[bytes], witness: bytes | None,
coin: CoinInfo, coin: CoinInfo,
): ):
self.threshold = 1 self.threshold = 1
self.public_keys: List[bytes] = [] self.public_keys: list[bytes] = []
self.signatures: List[Tuple[bytes, int]] = [] self.signatures: list[tuple[bytes, int]] = []
if not script_sig: if not script_sig:
if not witness: if not witness:

@ -16,8 +16,6 @@ from apps.common.writers import ( # noqa: F401
) )
if False: if False:
from typing import Union
from trezor.messages.TxInput import TxInput from trezor.messages.TxInput import TxInput
from trezor.messages.TxOutput import TxOutput from trezor.messages.TxOutput import TxOutput
from trezor.messages.PrevInput import PrevInput from trezor.messages.PrevInput import PrevInput
@ -38,7 +36,7 @@ def write_bytes_prefixed(w: Writer, b: bytes) -> None:
write_bytes_unchecked(w, b) 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_bytes_reversed(w, i.prev_hash, TX_HASH_SIZE)
write_uint32(w, i.prev_index) write_uint32(w, i.prev_index)
write_bytes_prefixed(w, script) 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) write_uint64(w, i.amount or 0)
def write_tx_output( def write_tx_output(w: Writer, o: TxOutput | PrevOutput, script_pubkey: bytes) -> None:
w: Writer, o: Union[TxOutput, PrevOutput], script_pubkey: bytes
) -> None:
write_uint64(w, o.amount) write_uint64(w, o.amount)
write_bytes_prefixed(w, script_pubkey) write_bytes_prefixed(w, script_pubkey)

@ -11,7 +11,6 @@ from .helpers.utils import variable_length_encode
from .seed import is_byron_path, is_shelley_path from .seed import is_byron_path, is_shelley_path
if False: if False:
from typing import List, Optional
from trezor.messages.CardanoBlockchainPointerType import ( from trezor.messages.CardanoBlockchainPointerType import (
CardanoBlockchainPointerType, CardanoBlockchainPointerType,
) )
@ -146,7 +145,7 @@ def _get_address_network_id(address: bytes) -> int:
return address[0] & 0x0F 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) node = keychain.derive(path)
public_key = remove_ed25519_prefix(node.public_key()) public_key = remove_ed25519_prefix(node.public_key())
return hashlib.blake2b(data=public_key, outlen=28).digest() return hashlib.blake2b(data=public_key, outlen=28).digest()
@ -195,7 +194,7 @@ def derive_address_bytes(
def _derive_byron_address( def _derive_byron_address(
keychain: seed.Keychain, path: List[int], protocol_magic: int keychain: seed.Keychain, path: list[int], protocol_magic: int
) -> bytes: ) -> bytes:
if not is_byron_path(path): if not is_byron_path(path):
raise wire.DataError("Invalid path for byron address!") raise wire.DataError("Invalid path for byron address!")
@ -248,9 +247,9 @@ def _create_address_header(
def _derive_base_address( def _derive_base_address(
keychain: seed.Keychain, keychain: seed.Keychain,
path: List[int], path: list[int],
staking_path: List[int], staking_path: list[int],
staking_key_hash: Optional[bytes], staking_key_hash: bytes | None,
network_id: int, network_id: int,
) -> bytes: ) -> bytes:
header = _create_address_header(CardanoAddressType.BASE, network_id) header = _create_address_header(CardanoAddressType.BASE, network_id)
@ -265,8 +264,8 @@ def _derive_base_address(
def _validate_base_address_staking_info( def _validate_base_address_staking_info(
staking_path: List[int], staking_path: list[int],
staking_key_hash: Optional[bytes], staking_key_hash: bytes | None,
) -> None: ) -> None:
if (staking_key_hash is None) == (not staking_path): if (staking_key_hash is None) == (not staking_path):
raise wire.DataError( raise wire.DataError(
@ -279,7 +278,7 @@ def _validate_base_address_staking_info(
def _derive_pointer_address( def _derive_pointer_address(
keychain: seed.Keychain, keychain: seed.Keychain,
path: List[int], path: list[int],
pointer: CardanoBlockchainPointerType, pointer: CardanoBlockchainPointerType,
network_id: int, network_id: int,
) -> bytes: ) -> bytes:
@ -300,7 +299,7 @@ def _encode_certificate_pointer(pointer: CardanoBlockchainPointerType) -> bytes:
def _derive_enterprise_address( def _derive_enterprise_address(
keychain: seed.Keychain, keychain: seed.Keychain,
path: List[int], path: list[int],
network_id: int, network_id: int,
) -> bytes: ) -> bytes:
header = _create_address_header(CardanoAddressType.ENTERPRISE, network_id) header = _create_address_header(CardanoAddressType.ENTERPRISE, network_id)
@ -311,7 +310,7 @@ def _derive_enterprise_address(
def _derive_reward_address( def _derive_reward_address(
keychain: seed.Keychain, keychain: seed.Keychain,
path: List[int], path: list[int],
network_id: int, network_id: int,
) -> bytes: ) -> bytes:
if not SCHEMA_STAKING_ANY_ACCOUNT.match(path): if not SCHEMA_STAKING_ANY_ACCOUNT.match(path):

@ -11,8 +11,6 @@ from .helpers import INVALID_CERTIFICATE, LOVELACE_MAX_SUPPLY
from .helpers.paths import SCHEMA_STAKING_ANY_ACCOUNT from .helpers.paths import SCHEMA_STAKING_ANY_ACCOUNT
if False: if False:
from typing import List, Optional
from trezor.messages.CardanoTxCertificateType import CardanoTxCertificateType from trezor.messages.CardanoTxCertificateType import CardanoTxCertificateType
from trezor.messages.CardanoPoolParametersType import CardanoPoolParametersType from trezor.messages.CardanoPoolParametersType import CardanoPoolParametersType
from trezor.messages.CardanoPoolRelayParametersType import ( from trezor.messages.CardanoPoolRelayParametersType import (
@ -135,7 +133,7 @@ def _validate_pool_parameters(
_validate_pool_metadata(pool_parameters.metadata) _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 owners_as_path_count = 0
for owner in owners: for owner in owners:
assert_certificate_cond( assert_certificate_cond(
@ -190,8 +188,8 @@ def _validate_pool_metadata(pool_metadata: CardanoPoolMetadataType) -> None:
def _cborize_pool_owners( def _cborize_pool_owners(
keychain: seed.Keychain, pool_owners: List[CardanoPoolOwnerType] keychain: seed.Keychain, pool_owners: list[CardanoPoolOwnerType]
) -> List[bytes]: ) -> list[bytes]:
result = [] result = []
for pool_owner in pool_owners: for pool_owner in pool_owners:
@ -205,7 +203,7 @@ def _cborize_pool_owners(
return result 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: if ipv6_address is None:
return None return None
@ -220,9 +218,9 @@ def _cborize_ipv6_address(ipv6_address: Optional[bytes]) -> Optional[bytes]:
def _cborize_pool_relays( def _cborize_pool_relays(
pool_relays: List[CardanoPoolRelayParametersType], pool_relays: list[CardanoPoolRelayParametersType],
) -> List[CborSequence]: ) -> list[CborSequence]:
result: List[CborSequence] = [] result: list[CborSequence] = []
for pool_relay in pool_relays: for pool_relay in pool_relays:
if pool_relay.type == CardanoPoolRelayType.SINGLE_HOST_IP: if pool_relay.type == CardanoPoolRelayType.SINGLE_HOST_IP:
@ -254,8 +252,8 @@ def _cborize_pool_relays(
def _cborize_pool_metadata( def _cborize_pool_metadata(
pool_metadata: Optional[CardanoPoolMetadataType], pool_metadata: CardanoPoolMetadataType | None,
) -> Optional[CborSequence]: ) -> CborSequence | None:
if not pool_metadata: if not pool_metadata:
return None return None

@ -12,7 +12,6 @@ from . import seed
from .helpers.paths import SCHEMA_PUBKEY from .helpers.paths import SCHEMA_PUBKEY
if False: if False:
from typing import List
from trezor.messages.CardanoGetPublicKey import CardanoGetPublicKey from trezor.messages.CardanoGetPublicKey import CardanoGetPublicKey
@ -41,7 +40,7 @@ async def get_public_key(
def _get_public_key( def _get_public_key(
keychain: seed.Keychain, derivation_path: List[int] keychain: seed.Keychain, derivation_path: list[int]
) -> CardanoPublicKey: ) -> CardanoPublicKey:
node = keychain.derive(derivation_path) node = keychain.derive(derivation_path)

@ -5,7 +5,6 @@ from ..seed import is_shelley_path
from .utils import to_account_path from .utils import to_account_path
if False: if False:
from typing import List
from trezor.messages.CardanoAddressParametersType import ( from trezor.messages.CardanoAddressParametersType import (
CardanoAddressParametersType, CardanoAddressParametersType,
) )
@ -53,5 +52,5 @@ def get(keychain: Keychain, address_parameters: CardanoAddressParametersType) ->
return NO_STAKING 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] return to_account_path(path) + [2, 0]

@ -4,9 +4,6 @@ from apps.cardano.helpers.paths import ACCOUNT_PATH_INDEX, unharden
from . import bech32 from . import bech32
if False:
from typing import List, Optional
def variable_length_encode(number: int) -> bytes: def variable_length_encode(number: int) -> bytes:
""" """
@ -30,18 +27,18 @@ def variable_length_encode(number: int) -> bytes:
return bytes(encoded) 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] 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: if len(path) <= ACCOUNT_PATH_INDEX:
raise ValueError("Path is too short.") raise ValueError("Path is too short.")
return "#%d" % (unharden(path[ACCOUNT_PATH_INDEX]) + 1) 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: if number is None:
return "n/a" return "n/a"

@ -32,7 +32,6 @@ from .helpers.utils import (
) )
if False: if False:
from typing import List, Optional
from trezor import wire from trezor import wire
from trezor.messages.CardanoBlockchainPointerType import ( from trezor.messages.CardanoBlockchainPointerType import (
CardanoBlockchainPointerType, CardanoBlockchainPointerType,
@ -76,7 +75,7 @@ def is_printable_ascii_bytestring(bytestr: bytes) -> bool:
async def confirm_sending( async def confirm_sending(
ctx: wire.Context, ctx: wire.Context,
ada_amount: int, ada_amount: int,
token_bundle: List[CardanoAssetGroupType], token_bundle: list[CardanoAssetGroupType],
to: str, to: str,
) -> None: ) -> None:
await confirm_sending_token_bundle(ctx, token_bundle) await confirm_sending_token_bundle(ctx, token_bundle)
@ -96,7 +95,7 @@ async def confirm_sending(
async def confirm_sending_token_bundle( async def confirm_sending_token_bundle(
ctx: wire.Context, token_bundle: List[CardanoAssetGroupType] ctx: wire.Context, token_bundle: list[CardanoAssetGroupType]
) -> None: ) -> None:
for token_group in token_bundle: for token_group in token_bundle:
for token in token_group.tokens: 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) 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 = Text("Confirm path", ui.ICON_WRONG, ui.RED)
page1.normal(title) page1.normal(title)
page1.bold(address_n_to_str(path)) 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( async def show_warning_tx_different_staking_account(
ctx: wire.Context, ctx: wire.Context,
staking_account_path: List[int], staking_account_path: list[int],
amount: int, amount: int,
) -> None: ) -> None:
page1 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN) page1 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN)
@ -214,12 +213,12 @@ async def confirm_transaction(
amount: int, amount: int,
fee: int, fee: int,
protocol_magic: int, protocol_magic: int,
ttl: Optional[int], ttl: int | None,
validity_interval_start: Optional[int], validity_interval_start: int | None,
has_metadata: bool, has_metadata: bool,
is_network_id_verifiable: bool, is_network_id_verifiable: bool,
) -> None: ) -> None:
pages: List[ui.Component] = [] pages: list[ui.Component] = []
page1 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN) page1 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN)
page1.normal("Transaction amount:") page1.normal("Transaction amount:")
@ -252,7 +251,7 @@ async def confirm_certificate(
# in this call # in this call
assert certificate.type != CardanoCertificateType.STAKE_POOL_REGISTRATION 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 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN)
page1.normal("Confirm:") page1.normal("Confirm:")
@ -301,10 +300,10 @@ async def confirm_stake_pool_parameters(
async def confirm_stake_pool_owners( async def confirm_stake_pool_owners(
ctx: wire.Context, ctx: wire.Context,
keychain: seed.Keychain, keychain: seed.Keychain,
owners: List[CardanoPoolOwnerType], owners: list[CardanoPoolOwnerType],
network_id: int, network_id: int,
) -> None: ) -> None:
pages: List[ui.Component] = [] pages: list[ui.Component] = []
for index, owner in enumerate(owners, 1): for index, owner in enumerate(owners, 1):
page = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN) page = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN)
page.normal("Pool owner #%d:" % (index)) page.normal("Pool owner #%d:" % (index))
@ -334,7 +333,7 @@ async def confirm_stake_pool_owners(
async def confirm_stake_pool_metadata( async def confirm_stake_pool_metadata(
ctx: wire.Context, ctx: wire.Context,
metadata: Optional[CardanoPoolMetadataType], metadata: CardanoPoolMetadataType | None,
) -> None: ) -> None:
if metadata is None: if metadata is None:
@ -359,8 +358,8 @@ async def confirm_stake_pool_metadata(
async def confirm_transaction_network_ttl( async def confirm_transaction_network_ttl(
ctx: wire.Context, ctx: wire.Context,
protocol_magic: int, protocol_magic: int,
ttl: Optional[int], ttl: int | None,
validity_interval_start: Optional[int], validity_interval_start: int | None,
) -> None: ) -> None:
page1 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN) page1 = Text("Confirm transaction", ui.ICON_SEND, ui.GREEN)
page1.normal("Network:") page1.normal("Network:")
@ -398,8 +397,8 @@ async def show_address(
ctx: wire.Context, ctx: wire.Context,
address: str, address: str,
address_type: EnumTypeCardanoAddressType, address_type: EnumTypeCardanoAddressType,
path: List[int], path: list[int],
network: Optional[str] = None, network: str | None = None,
) -> bool: ) -> bool:
""" """
Custom show_address function is needed because cardano addresses don't 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]: for address_line in address_lines[: lines_per_page - lines_used_on_first_page]:
page1.bold(address_line) page1.bold(address_line)
pages: List[ui.Component] = [] pages: list[ui.Component] = []
pages.append(page1) pages.append(page1)
# append remaining pages containing the rest of the address # append remaining pages containing the rest of the address
pages.extend( pages.extend(
@ -451,9 +450,9 @@ async def show_address(
def _paginate_lines( def _paginate_lines(
lines: List[str], offset: int, desc: str, icon: str, lines_per_page: int = 4 lines: list[str], offset: int, desc: str, icon: str, lines_per_page: int = 4
) -> List[ui.Component]: ) -> list[ui.Component]:
pages: List[ui.Component] = [] pages: list[ui.Component] = []
if len(lines) > offset: if len(lines) > offset:
to_pages = list(chunks(lines[offset:], lines_per_page)) to_pages = list(chunks(lines[offset:], lines_per_page))
for page in to_pages: for page in to_pages:
@ -467,9 +466,9 @@ def _paginate_lines(
async def show_warning_address_foreign_staking_key( async def show_warning_address_foreign_staking_key(
ctx: wire.Context, ctx: wire.Context,
account_path: List[int], account_path: list[int],
staking_account_path: List[int], staking_account_path: list[int],
staking_key_hash: Optional[bytes], staking_key_hash: bytes | None,
) -> None: ) -> None:
page1 = Text("Warning", ui.ICON_WRONG, ui.RED) page1 = Text("Warning", ui.ICON_WRONG, ui.RED)
page1.normal("Stake rights associated") page1.normal("Stake rights associated")

@ -66,7 +66,7 @@ from .layout import (
from .seed import is_byron_path, is_shelley_path from .seed import is_byron_path, is_shelley_path
if False: 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.CardanoSignTx import CardanoSignTx
from trezor.messages.CardanoTxCertificateType import CardanoTxCertificateType from trezor.messages.CardanoTxCertificateType import CardanoTxCertificateType
@ -78,9 +78,9 @@ if False:
from apps.common.cbor import CborSequence from apps.common.cbor import CborSequence
from apps.common.paths import PathSchema from apps.common.paths import PathSchema
CborizedTokenBundle = Dict[bytes, Dict[bytes, int]] CborizedTokenBundle = dict[bytes, dict[bytes, int]]
CborizedTxOutput = Tuple[bytes, Union[int, Tuple[int, CborizedTokenBundle]]] CborizedTxOutput = tuple[bytes, Union[int, tuple[int, CborizedTokenBundle]]]
CborizedSignedTx = Tuple[Dict, Dict, Optional[cbor.Raw]] CborizedSignedTx = tuple[dict, dict, Optional[cbor.Raw]]
TxHash = bytes TxHash = bytes
METADATA_HASH_SIZE = 32 METADATA_HASH_SIZE = 32
@ -123,7 +123,7 @@ async def sign_tx(
async def _sign_ordinary_tx( async def _sign_ordinary_tx(
ctx: wire.Context, msg: CardanoSignTx, keychain: seed.Keychain ctx: wire.Context, msg: CardanoSignTx, keychain: seed.Keychain
) -> Tuple[CborizedSignedTx, TxHash]: ) -> tuple[CborizedSignedTx, TxHash]:
for i in msg.inputs: for i in msg.inputs:
await validate_path( await validate_path(
ctx, keychain, i.address_n, SCHEMA_ADDRESS.match(i.address_n) 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( async def _sign_stake_pool_registration_tx(
ctx: wire.Context, msg: CardanoSignTx, keychain: seed.Keychain 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 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.) 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( def _validate_outputs(
keychain: seed.Keychain, keychain: seed.Keychain,
outputs: List[CardanoTxOutputType], outputs: list[CardanoTxOutputType],
protocol_magic: int, protocol_magic: int,
network_id: int, network_id: int,
) -> None: ) -> None:
@ -225,7 +225,7 @@ def _validate_outputs(
raise wire.ProcessError("Total transaction amount is out of range!") 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() seen_policy_ids = set()
for token_group in token_bundle: for token_group in token_bundle:
policy_id = bytes(token_group.policy_id) 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) 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): if any(i.address_n for i in inputs):
raise INVALID_STAKEPOOL_REGISTRATION_TX_INPUTS raise INVALID_STAKEPOOL_REGISTRATION_TX_INPUTS
def _validate_certificates( def _validate_certificates(
certificates: List[CardanoTxCertificateType], protocol_magic: int, network_id: int certificates: list[CardanoTxCertificateType], protocol_magic: int, network_id: int
) -> None: ) -> None:
for certificate in certificates: for certificate in certificates:
validate_certificate(certificate, protocol_magic, network_id) 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: for withdrawal in withdrawals:
if not SCHEMA_STAKING_ANY_ACCOUNT.match(withdrawal.path): if not SCHEMA_STAKING_ANY_ACCOUNT.match(withdrawal.path):
raise INVALID_WITHDRAWAL raise INVALID_WITHDRAWAL
@ -274,7 +274,7 @@ def _validate_withdrawals(withdrawals: List[CardanoTxWithdrawalType]) -> None:
raise INVALID_WITHDRAWAL raise INVALID_WITHDRAWAL
def _validate_metadata(metadata: Optional[bytes]) -> None: def _validate_metadata(metadata: bytes | None) -> None:
if not metadata: if not metadata:
return return
@ -293,7 +293,7 @@ def _validate_metadata(metadata: Optional[bytes]) -> None:
def _cborize_signed_tx( def _cborize_signed_tx(
keychain: seed.Keychain, msg: CardanoSignTx keychain: seed.Keychain, msg: CardanoSignTx
) -> Tuple[CborizedSignedTx, TxHash]: ) -> tuple[CborizedSignedTx, TxHash]:
tx_body = _cborize_tx_body(keychain, msg) tx_body = _cborize_tx_body(keychain, msg)
tx_hash = _hash_tx_body(tx_body) tx_hash = _hash_tx_body(tx_body)
@ -313,7 +313,7 @@ def _cborize_signed_tx(
return (tx_body, witnesses, metadata), tx_hash 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) inputs_for_cbor = _cborize_inputs(msg.inputs)
outputs_for_cbor = _cborize_outputs( outputs_for_cbor = _cborize_outputs(
keychain, msg.outputs, msg.protocol_magic, msg.network_id 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 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] return [(tx_input.prev_hash, tx_input.prev_index) for tx_input in inputs]
def _cborize_outputs( def _cborize_outputs(
keychain: seed.Keychain, keychain: seed.Keychain,
outputs: List[CardanoTxOutputType], outputs: list[CardanoTxOutputType],
protocol_magic: int, protocol_magic: int,
network_id: int, network_id: int,
) -> List[CborizedTxOutput]: ) -> list[CborizedTxOutput]:
return [ return [
_cborize_output(keychain, output, protocol_magic, network_id) _cborize_output(keychain, output, protocol_magic, network_id)
for output in outputs for output in outputs
@ -387,7 +387,7 @@ def _cborize_output(
def _cborize_token_bundle( def _cborize_token_bundle(
token_bundle: List[CardanoAssetGroupType], token_bundle: list[CardanoAssetGroupType],
) -> CborizedTokenBundle: ) -> CborizedTokenBundle:
result: CborizedTokenBundle = {} result: CborizedTokenBundle = {}
@ -404,17 +404,17 @@ def _cborize_token_bundle(
def _cborize_certificates( def _cborize_certificates(
keychain: seed.Keychain, keychain: seed.Keychain,
certificates: List[CardanoTxCertificateType], certificates: list[CardanoTxCertificateType],
) -> List[CborSequence]: ) -> list[CborSequence]:
return [cborize_certificate(keychain, cert) for cert in certificates] return [cborize_certificate(keychain, cert) for cert in certificates]
def _cborize_withdrawals( def _cborize_withdrawals(
keychain: seed.Keychain, keychain: seed.Keychain,
withdrawals: List[CardanoTxWithdrawalType], withdrawals: list[CardanoTxWithdrawalType],
protocol_magic: int, protocol_magic: int,
network_id: int, network_id: int,
) -> Dict[bytes, int]: ) -> dict[bytes, int]:
result = {} result = {}
for withdrawal in withdrawals: for withdrawal in withdrawals:
reward_address = derive_address_bytes( 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() 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) tx_body_cbor_chunks = cbor.encode_streamed(tx_body)
hashfn = hashlib.blake2b(outlen=32) hashfn = hashlib.blake2b(outlen=32)
@ -448,12 +448,12 @@ def _hash_tx_body(tx_body: Dict) -> bytes:
def _cborize_witnesses( def _cborize_witnesses(
keychain: seed.Keychain, keychain: seed.Keychain,
inputs: List[CardanoTxInputType], inputs: list[CardanoTxInputType],
certificates: List[CardanoTxCertificateType], certificates: list[CardanoTxCertificateType],
withdrawals: List[CardanoTxWithdrawalType], withdrawals: list[CardanoTxWithdrawalType],
tx_body_hash: bytes, tx_body_hash: bytes,
protocol_magic: int, protocol_magic: int,
) -> Dict: ) -> dict:
shelley_witnesses = _cborize_shelley_witnesses( shelley_witnesses = _cborize_shelley_witnesses(
keychain, inputs, certificates, withdrawals, tx_body_hash 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 # use key 0 for shelley witnesses and key 2 for byron witnesses
# according to the spec in shelley.cddl in cardano-ledger-specs # according to the spec in shelley.cddl in cardano-ledger-specs
witnesses: Dict[Any, Any] = {} witnesses: dict[Any, Any] = {}
if shelley_witnesses: if shelley_witnesses:
witnesses[0] = shelley_witnesses witnesses[0] = shelley_witnesses
if byron_witnesses: if byron_witnesses:
@ -474,11 +474,11 @@ def _cborize_witnesses(
def _cborize_shelley_witnesses( def _cborize_shelley_witnesses(
keychain: seed.Keychain, keychain: seed.Keychain,
inputs: List[CardanoTxInputType], inputs: list[CardanoTxInputType],
certificates: List[CardanoTxCertificateType], certificates: list[CardanoTxCertificateType],
withdrawals: List[CardanoTxWithdrawalType], withdrawals: list[CardanoTxWithdrawalType],
tx_body_hash: bytes, tx_body_hash: bytes,
) -> List[Tuple[bytes, bytes]]: ) -> list[tuple[bytes, bytes]]:
shelley_witnesses = [] shelley_witnesses = []
# include only one witness for each path # include only one witness for each path
@ -511,8 +511,8 @@ def _cborize_shelley_witnesses(
def _cborize_shelley_witness( def _cborize_shelley_witness(
keychain: seed.Keychain, tx_body_hash: bytes, path: List[int] keychain: seed.Keychain, tx_body_hash: bytes, path: list[int]
) -> Tuple[bytes, bytes]: ) -> tuple[bytes, bytes]:
node = keychain.derive(path) node = keychain.derive(path)
signature = ed25519.sign_ext( signature = ed25519.sign_ext(
@ -525,10 +525,10 @@ def _cborize_shelley_witness(
def _cborize_byron_witnesses( def _cborize_byron_witnesses(
keychain: seed.Keychain, keychain: seed.Keychain,
inputs: List[CardanoTxInputType], inputs: list[CardanoTxInputType],
tx_body_hash: bytes, tx_body_hash: bytes,
protocol_magic: int, protocol_magic: int,
) -> List[Tuple[bytes, bytes, bytes, bytes]]: ) -> list[tuple[bytes, bytes, bytes, bytes]]:
byron_witnesses = [] byron_witnesses = []
# include only one witness for each path # 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 # 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: for tx_input in inputs:
inp = tx_input.address_n inp = tx_input.address_n
if ( if (
@ -732,7 +732,7 @@ def _is_network_id_verifiable(msg: CardanoSignTx) -> bool:
async def _fail_or_warn_if_invalid_path( 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: ) -> None:
if not schema.match(path): if not schema.match(path):
if safety_checks.is_strict(): if safety_checks.is_strict():

@ -10,10 +10,10 @@ from trezor import log, utils
from . import readers, writers from . import readers, writers
if False: if False:
from typing import Any, List, Tuple, Union, Iterator from typing import Any, Union, Iterator, Tuple
Value = Any Value = Any
CborSequence = Union[List[Value], Tuple[Value, ...]] CborSequence = Union[list[Value], Tuple[Value, ...]]
_CBOR_TYPE_MASK = const(0xE0) _CBOR_TYPE_MASK = const(0xE0)
_CBOR_INFO_BITS = const(0x1F) _CBOR_INFO_BITS = const(0x1F)
@ -214,7 +214,7 @@ class Raw:
class IndefiniteLengthArray: class IndefiniteLengthArray:
def __init__(self, array: List[Value]) -> None: def __init__(self, array: list[Value]) -> None:
self.array = array self.array = array
def __eq__(self, other: object) -> bool: def __eq__(self, other: object) -> bool:

@ -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 from trezor.crypto.scripts import blake256_ripemd160_digest, sha256_ripemd160_digest
if False: if False:
from typing import Any, Dict, Optional from typing import Any
# flake8: noqa # flake8: noqa
@ -21,15 +21,15 @@ class CoinInfo:
maxfee_kb: int, maxfee_kb: int,
signed_message_header: str, signed_message_header: str,
xpub_magic: int, xpub_magic: int,
xpub_magic_segwit_p2sh: Optional[int], xpub_magic_segwit_p2sh: int | None,
xpub_magic_segwit_native: Optional[int], xpub_magic_segwit_native: int | None,
xpub_magic_multisig_segwit_p2sh: Optional[int], xpub_magic_multisig_segwit_p2sh: int | None,
xpub_magic_multisig_segwit_native: Optional[int], xpub_magic_multisig_segwit_native: int | None,
bech32_prefix: Optional[str], bech32_prefix: str | None,
cashaddr_prefix: Optional[str], cashaddr_prefix: str | None,
slip44: int, slip44: int,
segwit: bool, segwit: bool,
fork_id: Optional[int], fork_id: int | None,
force_bip143: bool, force_bip143: bool,
decred: bool, decred: bool,
negative_fee: bool, negative_fee: bool,
@ -37,7 +37,7 @@ class CoinInfo:
extra_data: bool, extra_data: bool,
timestamp: bool, timestamp: bool,
overwintered: bool, overwintered: bool,
confidential_assets: Optional[Dict[str, Any]], confidential_assets: dict[str, Any] | None,
) -> None: ) -> None:
self.coin_name = coin_name self.coin_name = coin_name
self.coin_shortcut = coin_shortcut self.coin_shortcut = coin_shortcut

@ -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 from trezor.crypto.scripts import blake256_ripemd160_digest, sha256_ripemd160_digest
if False: if False:
from typing import Any, Dict, Optional from typing import Any
# flake8: noqa # flake8: noqa
@ -21,15 +21,15 @@ class CoinInfo:
maxfee_kb: int, maxfee_kb: int,
signed_message_header: str, signed_message_header: str,
xpub_magic: int, xpub_magic: int,
xpub_magic_segwit_p2sh: Optional[int], xpub_magic_segwit_p2sh: int | None,
xpub_magic_segwit_native: Optional[int], xpub_magic_segwit_native: int | None,
xpub_magic_multisig_segwit_p2sh: Optional[int], xpub_magic_multisig_segwit_p2sh: int | None,
xpub_magic_multisig_segwit_native: Optional[int], xpub_magic_multisig_segwit_native: int | None,
bech32_prefix: Optional[str], bech32_prefix: str | None,
cashaddr_prefix: Optional[str], cashaddr_prefix: str | None,
slip44: int, slip44: int,
segwit: bool, segwit: bool,
fork_id: Optional[int], fork_id: int | None,
force_bip143: bool, force_bip143: bool,
decred: bool, decred: bool,
negative_fee: bool, negative_fee: bool,
@ -37,7 +37,7 @@ class CoinInfo:
extra_data: bool, extra_data: bool,
timestamp: bool, timestamp: bool,
overwintered: bool, overwintered: bool,
confidential_assets: Optional[Dict[str, Any]], confidential_assets: dict[str, Any] | None,
) -> None: ) -> None:
self.coin_name = coin_name self.coin_name = coin_name
self.coin_shortcut = coin_shortcut self.coin_shortcut = coin_shortcut

@ -15,7 +15,7 @@ if __debug__:
if False: if False:
from typing import Any, Callable, Optional from typing import Any, Callable
from trezor import ui from trezor import ui
from trezor.ui.components.tt.confirm import ButtonContent, ButtonStyleType from trezor.ui.components.tt.confirm import ButtonContent, ButtonStyleType
from trezor.ui.loader import LoaderStyleType from trezor.ui.loader import LoaderStyleType
@ -26,9 +26,9 @@ async def confirm(
ctx: wire.GenericContext, ctx: wire.GenericContext,
content: ui.Component, content: ui.Component,
code: EnumTypeButtonRequestType = ButtonRequestType.Other, code: EnumTypeButtonRequestType = ButtonRequestType.Other,
confirm: Optional[ButtonContent] = Confirm.DEFAULT_CONFIRM, confirm: ButtonContent | None = Confirm.DEFAULT_CONFIRM,
confirm_style: ButtonStyleType = Confirm.DEFAULT_CONFIRM_STYLE, 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, cancel_style: ButtonStyleType = Confirm.DEFAULT_CANCEL_STYLE,
major_confirm: bool = False, major_confirm: bool = False,
) -> bool: ) -> bool:

@ -11,13 +11,8 @@ if False:
Any, Any,
Awaitable, Awaitable,
Callable, Callable,
Dict,
Iterable, Iterable,
List,
Optional,
Tuple,
TypeVar, TypeVar,
Union,
) )
from typing_extensions import Protocol from typing_extensions import Protocol
@ -54,8 +49,8 @@ FORBIDDEN_KEY_PATH = wire.DataError("Forbidden key path")
class LRUCache: class LRUCache:
def __init__(self, size: int) -> None: def __init__(self, size: int) -> None:
self.size = size self.size = size
self.cache_keys: List[Any] = [] self.cache_keys: list[Any] = []
self.cache: Dict[Any, Deletable] = {} self.cache: dict[Any, Deletable] = {}
def insert(self, key: Any, value: Deletable) -> None: def insert(self, key: Any, value: Deletable) -> None:
if key in self.cache_keys: if key in self.cache_keys:
@ -98,7 +93,7 @@ class Keychain:
self.slip21_namespaces = tuple(slip21_namespaces) self.slip21_namespaces = tuple(slip21_namespaces)
self._cache = LRUCache(10) self._cache = LRUCache(10)
self._root_fingerprint: Optional[int] = None self._root_fingerprint: int | None = None
def __del__(self) -> None: def __del__(self) -> None:
self._cache.__del__() self._cache.__del__()
@ -127,7 +122,7 @@ class Keychain:
new_root: Callable[[], NodeType], new_root: Callable[[], NodeType],
) -> NodeType: ) -> NodeType:
cached_prefix = tuple(path[:prefix_len]) 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: if cached_root is None:
cached_root = new_root() cached_root = new_root()
cached_root.derive_path(cached_prefix) cached_root.derive_path(cached_prefix)
@ -196,7 +191,7 @@ def with_slip44_keychain(
raise ValueError # specify a pattern raise ValueError # specify a pattern
if allow_testnet: if allow_testnet:
slip44_ids: Union[int, Tuple[int, int]] = (slip44_id, 1) slip44_ids: int | tuple[int, int] = (slip44_id, 1)
else: else:
slip44_ids = slip44_id slip44_ids = slip44_id

@ -5,15 +5,14 @@ from trezor.messages import BackupType
from trezor.ui.components.tt.text import Text from trezor.ui.components.tt.text import Text
if False: if False:
from typing import Optional, Tuple
from trezor.messages.ResetDevice import EnumTypeBackupType from trezor.messages.ResetDevice import EnumTypeBackupType
def get() -> Tuple[Optional[bytes], int]: def get() -> tuple[bytes | None, int]:
return get_secret(), get_type() return get_secret(), get_type()
def get_secret() -> Optional[bytes]: def get_secret() -> bytes | None:
return storage.device.get_mnemonic_secret() return storage.device.get_mnemonic_secret()

@ -11,10 +11,8 @@ if False:
Collection, Collection,
Container, Container,
Iterable, Iterable,
List,
Sequence, Sequence,
TypeVar, TypeVar,
Union,
) )
from typing_extensions import Protocol from typing_extensions import Protocol
from trezor import wire from trezor import wire
@ -106,7 +104,7 @@ class PathSchema:
"**": Interval(0, 0xFFFF_FFFF), "**": 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/"): if not pattern.startswith("m/"):
raise ValueError # unsupported path template raise ValueError # unsupported path template
components = pattern[2:].split("/") components = pattern[2:].split("/")
@ -114,7 +112,7 @@ class PathSchema:
if isinstance(slip44_id, int): if isinstance(slip44_id, int):
slip44_id = (slip44_id,) slip44_id = (slip44_id,)
self.schema: List[Container[int]] = [] self.schema: list[Container[int]] = []
self.trailing_components: Container[int] = () self.trailing_components: Container[int] = ()
for component in components: 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) 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 = [] lines = []
path_str = address_n_to_str(address_n) path_str = address_n_to_str(address_n)

@ -11,7 +11,7 @@ from . import button_request
from .sdcard import SdCardUnavailable, request_sd_salt from .sdcard import SdCardUnavailable, request_sd_salt
if False: if False:
from typing import Any, NoReturn, Optional, Tuple from typing import Any, NoReturn
_last_successful_unlock = 0 _last_successful_unlock = 0
@ -25,7 +25,7 @@ def can_lock_device() -> bool:
async def request_pin( async def request_pin(
ctx: wire.GenericContext, ctx: wire.GenericContext,
prompt: str = "Enter your PIN", prompt: str = "Enter your PIN",
attempts_remaining: Optional[int] = None, attempts_remaining: int | None = None,
allow_cancel: bool = True, allow_cancel: bool = True,
) -> str: ) -> str:
await button_request(ctx, code=ButtonRequestType.PinEntry) await button_request(ctx, code=ButtonRequestType.PinEntry)
@ -67,7 +67,7 @@ async def pin_mismatch() -> None:
async def request_pin_and_sd_salt( async def request_pin_and_sd_salt(
ctx: wire.Context, prompt: str = "Enter your PIN", allow_cancel: bool = True ctx: wire.Context, prompt: str = "Enter your PIN", allow_cancel: bool = True
) -> Tuple[str, Optional[bytearray]]: ) -> tuple[str, bytearray | None]:
if config.has_pin(): if config.has_pin():
pin = await request_pin(ctx, prompt, config.get_pin_rem(), allow_cancel) pin = await request_pin(ctx, prompt, config.get_pin_rem(), allow_cancel)
config.ensure_not_wipe_code(pin) config.ensure_not_wipe_code(pin)

@ -5,7 +5,6 @@ from storage.device import SAFETY_CHECK_LEVEL_PROMPT, SAFETY_CHECK_LEVEL_STRICT
from trezor.messages import SafetyCheckLevel from trezor.messages import SafetyCheckLevel
if False: if False:
from typing import Optional
from trezor.messages.ApplySettings import EnumTypeSafetyCheckLevel from trezor.messages.ApplySettings import EnumTypeSafetyCheckLevel
@ -13,9 +12,9 @@ def read_setting() -> EnumTypeSafetyCheckLevel:
""" """
Returns the effective safety check level. Returns the effective safety check level.
""" """
temporary_safety_check_level: Optional[ temporary_safety_check_level: EnumTypeSafetyCheckLevel | None = storage.cache.get(
EnumTypeSafetyCheckLevel APP_COMMON_SAFETY_CHECKS_TEMPORARY
] = storage.cache.get(APP_COMMON_SAFETY_CHECKS_TEMPORARY) )
if temporary_safety_check_level is not None: if temporary_safety_check_level is not None:
return temporary_safety_check_level return temporary_safety_check_level
else: else:

@ -3,9 +3,6 @@ from storage.sd_salt import SD_CARD_HOT_SWAPPABLE
from trezor import fatfs, sdcard, ui, wire from trezor import fatfs, sdcard, ui, wire
from trezor.ui.layouts import confirm_action, show_error_and_raise from trezor.ui.layouts import confirm_action, show_error_and_raise
if False:
from typing import Optional
class SdCardUnavailable(wire.ProcessError): class SdCardUnavailable(wire.ProcessError):
pass pass
@ -160,7 +157,7 @@ async def ensure_sdcard(
async def request_sd_salt( async def request_sd_salt(
ctx: wire.GenericContext = wire.DUMMY_CONTEXT, ctx: wire.GenericContext = wire.DUMMY_CONTEXT,
) -> Optional[bytearray]: ) -> bytearray | None:
if not storage.sd_salt.is_enabled(): if not storage.sd_salt.is_enabled():
return None return None

@ -6,8 +6,6 @@ from . import mnemonic
from .passphrase import get as get_passphrase from .passphrase import get as get_passphrase
if False: if False:
from typing import Optional
from .paths import Bip32Path, Slip21Path from .paths import Bip32Path, Slip21Path
@ -17,9 +15,7 @@ class Slip21Node:
https://github.com/satoshilabs/slips/blob/master/slip-0021.md. https://github.com/satoshilabs/slips/blob/master/slip-0021.md.
""" """
def __init__( def __init__(self, seed: bytes | None = None, data: bytes | None = None) -> None:
self, seed: Optional[bytes] = None, data: Optional[bytes] = None
) -> None:
assert seed is None or data is None, "Specify exactly one of: seed, data" assert seed is None or data is None, "Specify exactly one of: seed, data"
if data is not None: if data is not None:
self.data = data self.data = data

@ -11,7 +11,6 @@ if __debug__:
from trezor.messages.Success import Success from trezor.messages.Success import Success
if False: if False:
from typing import List, Optional
from trezor.messages.DebugLinkDecision import DebugLinkDecision from trezor.messages.DebugLinkDecision import DebugLinkDecision
from trezor.messages.DebugLinkGetState import DebugLinkGetState from trezor.messages.DebugLinkGetState import DebugLinkGetState
from trezor.messages.DebugLinkRecordScreen import DebugLinkRecordScreen from trezor.messages.DebugLinkRecordScreen import DebugLinkRecordScreen
@ -23,7 +22,7 @@ if __debug__:
save_screen = False save_screen = False
save_screen_directory = "." save_screen_directory = "."
reset_internal_entropy: Optional[bytes] = None reset_internal_entropy: bytes | None = None
reset_current_words = loop.chan() reset_current_words = loop.chan()
reset_word_index = loop.chan() reset_word_index = loop.chan()
@ -37,7 +36,7 @@ if __debug__:
debuglink_decision_chan = loop.chan() debuglink_decision_chan = loop.chan()
layout_change_chan = loop.chan() layout_change_chan = loop.chan()
current_content: List[str] = [] current_content: list[str] = []
watch_layout_changes = False watch_layout_changes = False
def screenshot() -> bool: def screenshot() -> bool:

@ -11,7 +11,6 @@ from .. import helpers
from ..layout import require_confirm from ..layout import require_confirm
if False: if False:
from typing import List
from trezor import wire from trezor import wire
from trezor.messages.EosAuthorization import EosAuthorization from trezor.messages.EosAuthorization import EosAuthorization
from trezor.messages.EosActionBuyRam import EosActionBuyRam from trezor.messages.EosActionBuyRam import EosActionBuyRam
@ -39,7 +38,7 @@ _FIVE_FIELDS_PER_PAGE = const(5)
async def _require_confirm_paginated( 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: ) -> None:
pages = [] pages = []
for page in chunks(fields, per_page): 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) 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 = []
fields.append("Threshold:") fields.append("Threshold:")
@ -311,7 +310,7 @@ def authorization_fields(auth: EosAuthorization) -> List[str]:
return fields return fields
def split_data(data: str) -> List[str]: def split_data(data: str) -> list[str]:
lines = [] lines = []
while data: while data:
lines.append("{} ".format(data[:_LINE_LENGTH])) lines.append("{} ".format(data[:_LINE_LENGTH]))

@ -10,11 +10,10 @@ from .helpers import public_key_to_wif
from .layout import require_get_public_key from .layout import require_get_public_key
if False: if False:
from typing import Tuple
from trezor.crypto import bip32 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() seckey = node.private_key()
public_key = secp256k1.publickey(seckey, True) public_key = secp256k1.publickey(seckey, True)
wif = public_key_to_wif(public_key) wif = public_key_to_wif(public_key)

@ -9,7 +9,7 @@ SLIP44_WANCHAIN = const(5718350)
SLIP44_ETHEREUM = const(60) SLIP44_ETHEREUM = const(60)
if False: if False:
from typing import Iterator, Optional from typing import Iterator
def is_wanchain(chain_id: int, tx_type: int) -> bool: 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" 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(): for n in _networks_iterator():
if n.chain_id == chain_id: if n.chain_id == chain_id:
return n return n
return None return None
def by_slip44(slip44: int) -> Optional["NetworkInfo"]: def by_slip44(slip44: int) -> "NetworkInfo" | None:
if slip44 == SLIP44_WANCHAIN: if slip44 == SLIP44_WANCHAIN:
# Coerce to Ethereum # Coerce to Ethereum
slip44 = SLIP44_ETHEREUM slip44 = SLIP44_ETHEREUM

@ -9,7 +9,7 @@ SLIP44_WANCHAIN = const(5718350)
SLIP44_ETHEREUM = const(60) SLIP44_ETHEREUM = const(60)
if False: if False:
from typing import Iterator, Optional from typing import Iterator
def is_wanchain(chain_id: int, tx_type: int) -> bool: 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" 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(): for n in _networks_iterator():
if n.chain_id == chain_id: if n.chain_id == chain_id:
return n return n
return None return None
def by_slip44(slip44: int) -> Optional["NetworkInfo"]: def by_slip44(slip44: int) -> "NetworkInfo" | None:
if slip44 == SLIP44_WANCHAIN: if slip44 == SLIP44_WANCHAIN:
# Coerce to Ethereum # Coerce to Ethereum
slip44 = SLIP44_ETHEREUM slip44 = SLIP44_ETHEREUM

@ -10,9 +10,6 @@ from apps.base import lock_device
from . import HomescreenBase from . import HomescreenBase
if False:
from typing import Optional
_LOADER_DELAY_MS = const(500) _LOADER_DELAY_MS = const(500)
_LOADER_TOTAL_MS = const(2500) _LOADER_TOTAL_MS = const(2500)
@ -34,7 +31,7 @@ class Homescreen(HomescreenBase):
offset_y=-10, offset_y=-10,
reverse_speedup=3, reverse_speedup=3,
) )
self.touch_ms: Optional[int] = None self.touch_ms: int | None = None
def on_render(self) -> None: def on_render(self) -> None:
if not self.repaint: if not self.repaint:

@ -2,8 +2,6 @@ from trezor.crypto.slip39 import Share
from trezor.messages import BackupType from trezor.messages import BackupType
if False: if False:
from typing import Optional
from trezor.messages.ResetDevice import EnumTypeBackupType from trezor.messages.ResetDevice import EnumTypeBackupType
@ -29,7 +27,7 @@ def is_slip39_backup_type(backup_type: EnumTypeBackupType) -> bool:
def infer_backup_type( def infer_backup_type(
is_slip39: bool, share: Optional[Share] = None is_slip39: bool, share: Share | None = None
) -> EnumTypeBackupType: ) -> EnumTypeBackupType:
if not is_slip39: # BIP-39 if not is_slip39: # BIP-39
return BackupType.Bip39 return BackupType.Bip39

@ -17,7 +17,6 @@ from .. import backup_types
from . import layout, recover from . import layout, recover
if False: if False:
from typing import Optional, Tuple
from trezor.messages.ResetDevice import EnumTypeBackupType 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( async def _process_words(
ctx: wire.GenericContext, words: str ctx: wire.GenericContext, words: str
) -> Tuple[Optional[bytes], EnumTypeBackupType]: ) -> tuple[bytes | None, EnumTypeBackupType]:
word_count = len(words.split(" ")) word_count = len(words.split(" "))
is_slip39 = backup_types.is_slip39_word_count(word_count) is_slip39 = backup_types.is_slip39_word_count(word_count)
share = None share = None
if not is_slip39: # BIP-39 if not is_slip39: # BIP-39
secret: Optional[bytes] = recover.process_bip39(words) secret: bytes | None = recover.process_bip39(words)
else: else:
secret, share = recover.process_slip39(words) secret, share = recover.process_slip39(words)

@ -9,7 +9,6 @@ from trezor.ui.components.tt.button import (
) )
if False: if False:
from typing import Optional, Tuple
from trezor.ui.components.tt.button import ButtonContent, ButtonStyleStateType 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") ("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 self.pending_index = 0
def dispatch(self, event: int, x: int, y: int) -> None: def dispatch(self, event: int, x: int, y: int) -> None:
@ -172,7 +171,7 @@ class Bip39Keyboard(ui.Layout):
# Word was confirmed by the user. # Word was confirmed by the user.
raise ui.Result(word) 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_button = button
self.pending_index = index self.pending_index = index
@ -217,7 +216,7 @@ class Bip39Keyboard(ui.Layout):
if __debug__: if __debug__:
def create_tasks(self) -> Tuple[loop.Task, ...]: def create_tasks(self) -> tuple[loop.Task, ...]:
from apps.debug import input_signal from apps.debug import input_signal
return super().create_tasks() + (input_signal(),) return super().create_tasks() + (input_signal(),)

@ -9,7 +9,6 @@ from trezor.ui.components.tt.button import (
) )
if False: if False:
from typing import Optional, Tuple
from trezor.ui.components.tt.button import ButtonContent, ButtonStyleStateType 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: def __init__(self, area: ui.Area, keyboard: "Slip39Keyboard") -> None:
super().__init__(area, "") super().__init__(area, "")
self.word = "" self.word = ""
self.pending_button: Optional[Button] = None self.pending_button: Button | None = None
self.pending_index: Optional[int] = None self.pending_index: int | None = None
self.keyboard = keyboard self.keyboard = keyboard
self.disable() self.disable()
@ -42,8 +41,8 @@ class InputButton(Button):
self, self,
text: str, text: str,
word: str, word: str,
pending_button: Optional[Button], pending_button: Button | None,
pending_index: Optional[int], pending_index: int | None,
) -> None: ) -> None:
self.word = word self.word = word
self.text = text self.text = text
@ -123,7 +122,7 @@ class Slip39Keyboard(ui.Layout):
("ab", "cd", "ef", "ghij", "klm", "nopq", "rs", "tuv", "wxyz") ("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.pending_index = 0
self.button_sequence = "" self.button_sequence = ""
self.mask = slip39.KEYBOARD_FULL_MASK self.mask = slip39.KEYBOARD_FULL_MASK
@ -170,7 +169,7 @@ class Slip39Keyboard(ui.Layout):
# Word was confirmed by the user. # Word was confirmed by the user.
raise ui.Result(word) 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_button = button
self.pending_index = index self.pending_index = index
@ -227,7 +226,7 @@ class Slip39Keyboard(ui.Layout):
if __debug__: if __debug__:
def create_tasks(self) -> Tuple[loop.Task, ...]: def create_tasks(self) -> tuple[loop.Task, ...]:
from apps.debug import input_signal from apps.debug import input_signal
return super().create_tasks() + (input_signal(),) return super().create_tasks() + (input_signal(),)

@ -17,7 +17,7 @@ from .keyboard_slip39 import Slip39Keyboard
from .recover import RecoveryAborted from .recover import RecoveryAborted
if False: if False:
from typing import List, Optional, Callable, Iterable, Tuple, Union from typing import Callable, Iterable
from trezor.messages.ResetDevice import EnumTypeBackupType 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( async def request_mnemonic(
ctx: wire.GenericContext, word_count: int, backup_type: Optional[EnumTypeBackupType] ctx: wire.GenericContext, word_count: int, backup_type: EnumTypeBackupType | None
) -> Optional[str]: ) -> str | None:
await button_request(ctx, code=ButtonRequestType.MnemonicInput) await button_request(ctx, code=ButtonRequestType.MnemonicInput)
words: List[str] = [] words: list[str] = []
for i in range(word_count): for i in range(word_count):
if backup_types.is_slip39_word_count(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) "Type word %s of %s:" % (i + 1, word_count)
) )
else: else:
@ -94,11 +94,11 @@ async def request_mnemonic(
async def show_remaining_shares( async def show_remaining_shares(
ctx: wire.GenericContext, ctx: wire.GenericContext,
groups: Iterable[Tuple[int, Tuple[str, ...]]], # remaining + list 3 words groups: Iterable[tuple[int, tuple[str, ...]]], # remaining + list 3 words
shares_remaining: List[int], shares_remaining: list[int],
group_threshold: int, group_threshold: int,
) -> None: ) -> None:
pages: List[ui.Component] = [] pages: list[ui.Component] = []
for remaining, group in groups: for remaining, group in groups:
if 0 < remaining < MAX_SHARE_COUNT: if 0 < remaining < MAX_SHARE_COUNT:
text = Text("Remaining Shares") text = Text("Remaining Shares")
@ -205,7 +205,7 @@ async def show_group_threshold_reached(ctx: wire.GenericContext) -> None:
class RecoveryHomescreen(ui.Component): class RecoveryHomescreen(ui.Component):
def __init__(self, text: str, subtext: Optional[str] = None): def __init__(self, text: str, subtext: str | None = None):
super().__init__() super().__init__()
self.text = text self.text = text
self.subtext = subtext self.subtext = subtext
@ -240,7 +240,7 @@ class RecoveryHomescreen(ui.Component):
if __debug__: if __debug__:
def read_content(self) -> List[str]: def read_content(self) -> list[str]:
return [self.__class__.__name__, self.text, self.subtext or ""] return [self.__class__.__name__, self.text, self.subtext or ""]
@ -248,7 +248,7 @@ async def homescreen_dialog(
ctx: wire.GenericContext, ctx: wire.GenericContext,
homepage: RecoveryHomescreen, homepage: RecoveryHomescreen,
button_label: str, button_label: str,
info_func: Optional[Callable] = None, info_func: Callable | None = None,
) -> None: ) -> None:
while True: while True:
if info_func: if info_func:

@ -7,7 +7,7 @@ from .. import backup_types
if False: if False:
from trezor.messages.ResetDevice import EnumTypeBackupType from trezor.messages.ResetDevice import EnumTypeBackupType
from typing import Optional, Tuple, List, Union from typing import Union
class RecoveryAborted(Exception): class RecoveryAborted(Exception):
@ -24,7 +24,7 @@ def process_bip39(words: str) -> bytes:
return words.encode() 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 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. (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: if False:
Slip39State = Union[Tuple[int, EnumTypeBackupType], Tuple[None, None]] Slip39State = Union[tuple[int, EnumTypeBackupType], tuple[None, None]]
def load_slip39_state() -> Slip39State: def load_slip39_state() -> Slip39State:
@ -106,7 +106,7 @@ def load_slip39_state() -> Slip39State:
return word_count, backup_types.infer_backup_type(True, share) 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 = [] mnemonics = []
if not storage.recovery.get_slip39_group_count(): if not storage.recovery.get_slip39_group_count():
return None return None

@ -4,7 +4,6 @@ from trezor.messages import BackupType
from . import recover from . import recover
if False: if False:
from typing import List, Optional
from trezor.messages.ResetDevice import EnumTypeBackupType from trezor.messages.ResetDevice import EnumTypeBackupType
@ -24,9 +23,7 @@ class ThresholdReached(WordValidityResult):
pass pass
def check( def check(backup_type: EnumTypeBackupType | None, partial_mnemonic: list[str]) -> None:
backup_type: Optional[EnumTypeBackupType], partial_mnemonic: List[str]
) -> None:
# we can't perform any checks if the backup type was not yet decided # we can't perform any checks if the backup type was not yet decided
if backup_type is None: if backup_type is None:
return return
@ -49,7 +46,7 @@ def check(
def check_slip39_basic( def check_slip39_basic(
partial_mnemonic: List[str], previous_mnemonics: List[List[str]] partial_mnemonic: list[str], previous_mnemonics: list[list[str]]
) -> None: ) -> None:
# check if first 3 words of mnemonic match # check if first 3 words of mnemonic match
# we can check against the first one, others were checked already # we can check against the first one, others were checked already
@ -68,7 +65,7 @@ def check_slip39_basic(
def check_slip39_advanced( def check_slip39_advanced(
partial_mnemonic: List[str], previous_mnemonics: List[List[str]] partial_mnemonic: list[str], previous_mnemonics: list[list[str]]
) -> None: ) -> None:
current_index = len(partial_mnemonic) - 1 current_index = len(partial_mnemonic) - 1
current_word = partial_mnemonic[-1] current_word = partial_mnemonic[-1]

@ -15,7 +15,6 @@ from apps.common.confirm import confirm, require_hold_to_confirm
if False: if False:
from trezor import loop from trezor import loop
from typing import List, Tuple
if __debug__: if __debug__:
from apps import debug from apps import debug
@ -596,8 +595,8 @@ class MnemonicWordSelect(ui.Layout):
if __debug__: 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] 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(),) return super().create_tasks() + (debug.input_signal(),)

@ -14,11 +14,11 @@ from apps.common.request_pin import (
from apps.common.sdcard import confirm_retry_sd, ensure_sdcard from apps.common.sdcard import confirm_retry_sd, ensure_sdcard
if False: if False:
from typing import Awaitable, Tuple from typing import Awaitable
from trezor.messages.SdProtect import SdProtect 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) salt = random.bytes(storage.sd_salt.SD_SALT_LEN_BYTES)
auth_key = random.bytes(storage.device.SD_SALT_AUTH_KEY_LEN_BYTES) auth_key = random.bytes(storage.device.SD_SALT_AUTH_KEY_LEN_BYTES)
tag = storage.sd_salt.compute_auth_tag(salt, auth_key) tag = storage.sd_salt.compute_auth_tag(salt, auth_key)

@ -10,8 +10,6 @@ from apps.common.keychain import get_keychain
from apps.common.paths import AlwaysMatchingSchema from apps.common.paths import AlwaysMatchingSchema
if False: if False:
from typing import Optional, Union
from trezor.messages.IdentityType import IdentityType from trezor.messages.IdentityType import IdentityType
from trezor.messages.SignIdentity import SignIdentity 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") coin = coininfo.by_name("Bitcoin")
if msg.ecdsa_curve_name == "secp256k1": if msg.ecdsa_curve_name == "secp256k1":
# hardcoded bitcoin address type # hardcoded bitcoin address type
address: Optional[str] = node.address(coin.address_type) address: str | None = node.address(coin.address_type)
else: else:
address = None address = None
pubkey = node.public_key() pubkey = node.public_key()
@ -81,7 +79,7 @@ async def sign_identity(ctx: wire.Context, msg: SignIdentity) -> SignedIdentity:
async def require_confirm_sign_identity( 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: ) -> None:
proto = identity.proto.upper() if identity.proto else "identity" proto = identity.proto.upper() if identity.proto else "identity"
await confirm_sign_identity( await confirm_sign_identity(
@ -124,7 +122,7 @@ def sign_challenge(
seckey: bytes, seckey: bytes,
challenge_hidden: bytes, challenge_hidden: bytes,
challenge_visual: str, challenge_visual: str,
sigtype: Union[str, coininfo.CoinInfo], sigtype: str | coininfo.CoinInfo,
curve: str, curve: str,
) -> bytes: ) -> bytes:
from trezor.crypto.hashlib import sha256 from trezor.crypto.hashlib import sha256

@ -14,7 +14,6 @@ DUMMY_PAYMENT_ID = b"\x00\x00\x00\x00\x00\x00\x00\x00"
if False: if False:
from typing import Optional
from apps.monero.signing.state import State from apps.monero.signing.state import State
from trezor.messages.MoneroTransactionData import MoneroTransactionData from trezor.messages.MoneroTransactionData import MoneroTransactionData
from trezor.messages.MoneroTransactionDestinationEntry import ( 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: if step == 0:
info = ["Signing..."] info = ["Signing..."]
elif step == state.STEP_INP: elif step == state.STEP_INP:

@ -1,5 +1,4 @@
if False: if False:
from typing import Tuple
from apps.monero.xmr.types import Sc25519 from apps.monero.xmr.types import Sc25519
@ -32,7 +31,7 @@ def compute_tx_key(
def compute_enc_key_host( def compute_enc_key_host(
view_key_private: Sc25519, tx_prefix_hash: bytes view_key_private: Sc25519, tx_prefix_hash: bytes
) -> Tuple[bytes, bytes]: ) -> tuple[bytes, bytes]:
from apps.monero.xmr import crypto from apps.monero.xmr import crypto
salt = crypto.random_bytes(32) salt = crypto.random_bytes(32)

@ -6,11 +6,10 @@ from trezor import log
from apps.monero.xmr import crypto from apps.monero.xmr import crypto
if False: if False:
from typing import Dict, List, Optional, Tuple
from apps.monero.xmr.types import Ge25519, Sc25519 from apps.monero.xmr.types import Ge25519, Sc25519
from apps.monero.xmr.credentials import AccountCreds from apps.monero.xmr.credentials import AccountCreds
Subaddresses = Dict[bytes, Tuple[int, int]] Subaddresses = dict[bytes, tuple[int, int]]
class State: class State:
@ -37,11 +36,11 @@ class State:
- spend private/public key - spend private/public key
- and its corresponding address - and its corresponding address
""" """
self.creds: Optional[AccountCreds] = None self.creds: AccountCreds | None = None
# HMAC/encryption keys used to protect offloaded data # HMAC/encryption keys used to protect offloaded data
self.key_hmac: Optional[bytes] = None self.key_hmac: bytes | None = None
self.key_enc: Optional[bytes] = None self.key_enc: bytes | None = None
""" """
Transaction keys Transaction keys
@ -77,8 +76,8 @@ class State:
self.account_idx = 0 self.account_idx = 0
# contains additional tx keys if need_additional_tx_keys is True # contains additional tx keys if need_additional_tx_keys is True
self.additional_tx_private_keys: List[Sc25519] = [] self.additional_tx_private_keys: list[Sc25519] = []
self.additional_tx_public_keys: List[bytes] = [] self.additional_tx_public_keys: list[bytes] = []
# currently processed input/output index # currently processed input/output index
self.current_input_index = -1 self.current_input_index = -1
@ -92,14 +91,14 @@ class State:
self.summary_outs_money = 0 self.summary_outs_money = 0
# output commitments # 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. # 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 # 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 # is range proof computing offloaded or not
self.rsig_offload = False self.rsig_offload = False
@ -115,13 +114,13 @@ class State:
# contains an array where each item denotes the input's position # contains an array where each item denotes the input's position
# (inputs are sorted by key images) # (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 # 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 # 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 # Step transition automaton
self.last_step = self.STEP_INIT self.last_step = self.STEP_INIT
@ -132,7 +131,7 @@ class State:
See Monero-Trezor documentation section 3.3 for more details. See Monero-Trezor documentation section 3.3 for more details.
""" """
self.tx_prefix_hasher = KeccakXmrArchive() 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. 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. See Monero-Trezor documentation section 3.3 for more details.
""" """
self.full_message_hasher = PreMlsagHasher() 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): def mem_trace(self, x=None, collect=False):
if __debug__: if __debug__:

@ -10,7 +10,6 @@ from apps.monero.signing.state import State
from apps.monero.xmr import crypto, monero from apps.monero.xmr import crypto, monero
if False: if False:
from typing import List
from apps.monero.xmr.types import Sc25519, Ge25519 from apps.monero.xmr.types import Sc25519, Ge25519
from trezor.messages.MoneroTransactionData import MoneroTransactionData from trezor.messages.MoneroTransactionData import MoneroTransactionData
from trezor.messages.MoneroTransactionRsigData import MoneroTransactionRsigData from trezor.messages.MoneroTransactionRsigData import MoneroTransactionRsigData
@ -122,7 +121,7 @@ async def init_transaction(
return MoneroTransactionInitAck(hmacs=hmacs, rsig_data=rsig_data) 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. Using subaddresses leads to a few poorly documented exceptions.
@ -221,7 +220,7 @@ def _check_grouping(state: State):
raise ValueError("Invalid grouping") 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 Check if the change address in state.output_change (from `tsx_data.outputs`) is
a) among tx outputs 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) 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) Precomputes subaddresses for account (major) and list of indices (minors)
Subaddresses have to be stored in encoded form - unique representation. Subaddresses have to be stored in encoded form - unique representation.

@ -17,7 +17,6 @@ from apps.monero.xmr import crypto, monero, serialize
from .state import State from .state import State
if False: if False:
from typing import List, Tuple, Optional
from apps.monero.xmr.types import Sc25519, Ge25519 from apps.monero.xmr.types import Sc25519, Ge25519
from trezor.messages.MoneroTransactionSourceEntry import ( from trezor.messages.MoneroTransactionSourceEntry import (
MoneroTransactionSourceEntry, 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 Computes Pedersen commitment - pseudo outs
Here is slight deviation from the original protocol. 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) 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 Mixin outputs are specified in relative numbers. First index is absolute
and the rest is an offset of a previous one. 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( def _get_additional_public_key(
src_entr: MoneroTransactionSourceEntry, src_entr: MoneroTransactionSourceEntry,
) -> Optional[Ge25519]: ) -> Ge25519 | None:
additional_tx_pub_key = None additional_tx_pub_key = None
if len(src_entr.real_out_additional_tx_keys) == 1: # compression if len(src_entr.real_out_additional_tx_keys) == 1: # compression
additional_tx_pub_key = crypto.decodepoint( additional_tx_pub_key = crypto.decodepoint(

@ -21,14 +21,13 @@ from apps.monero.layout.confirms import transaction_step
from .state import State from .state import State
if False: if False:
from typing import List
from trezor.messages.MoneroTransactionInputsPermutationAck import ( from trezor.messages.MoneroTransactionInputsPermutationAck import (
MoneroTransactionInputsPermutationAck, MoneroTransactionInputsPermutationAck,
) )
async def tsx_inputs_permutation( async def tsx_inputs_permutation(
state: State, permutation: List[int] state: State, permutation: list[int]
) -> MoneroTransactionInputsPermutationAck: ) -> MoneroTransactionInputsPermutationAck:
from trezor.messages.MoneroTransactionInputsPermutationAck import ( from trezor.messages.MoneroTransactionInputsPermutationAck import (
MoneroTransactionInputsPermutationAck, MoneroTransactionInputsPermutationAck,
@ -54,7 +53,7 @@ async def tsx_inputs_permutation(
return MoneroTransactionInputsPermutationAck() return MoneroTransactionInputsPermutationAck()
def _check_permutation(permutation: List[int]): def _check_permutation(permutation: list[int]):
for n in range(len(permutation)): for n in range(len(permutation)):
if n not in permutation: if n not in permutation:
raise ValueError("Invalid permutation") raise ValueError("Invalid permutation")

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save