1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-11-22 15:38:11 +00:00

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
This commit is contained in:
Martin Milata 2021-03-18 10:48:50 +01:00 committed by matejcik
parent 0278998f72
commit ac711fb8ee
157 changed files with 843 additions and 1013 deletions

View File

@ -47,7 +47,7 @@ STATIC secbool wrapped_ui_wait_callback(uint32_t wait, uint32_t progress,
}
/// def init(
/// ui_wait_callback: Optional[Callable[[int, int, str], bool]] = None
/// ui_wait_callback: Callable[[int, int, str], bool] | None = None
/// ) -> None:
/// """
/// Initializes the storage. Must be called before any other method is
@ -66,7 +66,7 @@ STATIC mp_obj_t mod_trezorconfig_init(size_t n_args, const mp_obj_t *args) {
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorconfig_init_obj, 0, 1,
mod_trezorconfig_init);
/// def unlock(pin: str, ext_salt: Optional[bytes]) -> bool:
/// def unlock(pin: str, ext_salt: bytes | None) -> bool:
/// """
/// Attempts to unlock the storage with the given PIN and external salt.
/// Returns True on success, False on failure.
@ -91,7 +91,7 @@ STATIC mp_obj_t mod_trezorconfig_unlock(mp_obj_t pin, mp_obj_t ext_salt) {
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorconfig_unlock_obj,
mod_trezorconfig_unlock);
/// def check_pin(pin: str, ext_salt: Optional[bytes]) -> bool:
/// def check_pin(pin: str, ext_salt: bytes | None) -> bool:
/// """
/// Check the given PIN with the given external salt.
/// Returns True on success, False on failure.
@ -152,8 +152,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorconfig_get_pin_rem_obj,
/// def change_pin(
/// oldpin: str,
/// newpin: str,
/// old_ext_salt: Optional[bytes],
/// new_ext_salt: Optional[bytes],
/// old_ext_salt: bytes | None,
/// new_ext_salt: bytes | None,
/// ) -> bool:
/// """
/// Change PIN and external salt. Returns True on success, False on failure.
@ -219,7 +219,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorconfig_has_wipe_code_obj,
/// def change_wipe_code(
/// pin: str,
/// ext_salt: Optional[bytes],
/// ext_salt: bytes | None,
/// wipe_code: str,
/// ) -> bool:
/// """
@ -252,7 +252,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorconfig_change_wipe_code_obj, 3, 3,
mod_trezorconfig_change_wipe_code);
/// def get(app: int, key: int, public: bool = False) -> Optional[bytes]:
/// def get(app: int, key: int, public: bool = False) -> bytes | None:
/// """
/// Gets the value of the given key for the given app (or None if not set).
/// Raises a RuntimeError if decryption or authentication of the stored

View File

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

View File

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

View File

@ -25,7 +25,7 @@
/// package: trezorcrypto.bip39
/// def complete_word(prefix: str) -> Optional[str]:
/// def complete_word(prefix: str) -> str | None:
/// """
/// Return the first word from the wordlist starting with prefix.
/// """
@ -125,7 +125,7 @@ STATIC void wrapped_ui_wait_callback(uint32_t current, uint32_t total) {
/// def seed(
/// mnemonic: str,
/// passphrase: str,
/// callback: Optional[Callable[[int, int], None]] = None,
/// callback: Callable[[int, int], None] | None = None,
/// ) -> bytes:
/// """
/// Generate seed from mnemonic and passphrase.

View File

@ -37,7 +37,7 @@ typedef struct _mp_obj_Blake256_t {
STATIC mp_obj_t mod_trezorcrypto_Blake256_update(mp_obj_t self, mp_obj_t data);
/// def __init__(self, data: Optional[bytes] = None) -> None:
/// def __init__(self, data: bytes | None = None) -> None:
/// """
/// Creates a hash context object.
/// """

View File

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

View File

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

View File

@ -174,7 +174,7 @@ STATIC mp_obj_t mod_trezorcrypto_ed25519_verify(mp_obj_t public_key,
STATIC MP_DEFINE_CONST_FUN_OBJ_3(mod_trezorcrypto_ed25519_verify_obj,
mod_trezorcrypto_ed25519_verify);
/// def cosi_combine_publickeys(public_keys: List[bytes]) -> bytes:
/// def cosi_combine_publickeys(public_keys: list[bytes]) -> bytes:
/// """
/// Combines a list of public keys used in COSI cosigning scheme.
/// """
@ -209,7 +209,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(
mod_trezorcrypto_ed25519_cosi_combine_publickeys_obj,
mod_trezorcrypto_ed25519_cosi_combine_publickeys);
/// def cosi_combine_signatures(R: bytes, signatures: List[bytes]) -> bytes:
/// def cosi_combine_signatures(R: bytes, signatures: list[bytes]) -> bytes:
/// """
/// Combines a list of signatures used in COSI cosigning scheme.
/// """

View File

@ -41,7 +41,7 @@ typedef struct _mp_obj_Groestl512_t {
STATIC mp_obj_t mod_trezorcrypto_Groestl512_update(mp_obj_t self,
mp_obj_t data);
/// def __init__(self, data: Optional[bytes] = None) -> None:
/// def __init__(self, data: bytes | None = None) -> None:
/// """
/// Creates a hash context object.
/// """

View File

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

View File

@ -180,7 +180,7 @@ STATIC void mp_unpack_scalar(bignum256modm r, const mp_obj_t arg,
/// EC point on ED25519
/// """
///
/// def __init__(self, x: Optional[Union[Ge25519, bytes]] = None):
/// def __init__(self, x: Ge25519 | bytes | None = None):
/// """
/// Constructor
/// """
@ -218,7 +218,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_monero_ge25519___del___obj,
/// EC scalar on SC25519
/// """
///
/// def __init__(self, x: Optional[Union[Sc25519, bytes, int]] = None):
/// def __init__(self, x: Sc25519 | bytes | int | None = None):
/// """
/// Constructor
/// """
@ -261,7 +261,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(
/// XMR hasher
/// """
///
/// def __init__(self, x: Optional[bytes] = None):
/// def __init__(self, x: bytes | None = None):
/// """
/// Constructor
/// """
@ -314,7 +314,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_monero_hasher___del___obj,
/// mock:global
/// def init256_modm(
/// dst: Optional[Sc25519], val: Union[int, bytes, Sc25519]
/// dst: Sc25519 | None, val: int | bytes | Sc25519
/// ) -> Sc25519:
/// """
/// Initializes Sc25519 scalar
@ -399,7 +399,7 @@ STATIC mp_obj_t mod_trezorcrypto_monero_get256_modm(const mp_obj_t arg) {
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_monero_get256_modm_obj,
mod_trezorcrypto_monero_get256_modm);
/// def add256_modm(r: Optional[Sc25519], a: Sc25519, b: Sc25519) -> Sc25519:
/// def add256_modm(r: Sc25519 | None, a: Sc25519, b: Sc25519) -> Sc25519:
/// """
/// Scalar addition
/// """
@ -419,7 +419,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_add256_modm_obj, 2, 3,
mod_trezorcrypto_monero_add256_modm);
/// def sub256_modm(r: Optional[Sc25519], a: Sc25519, b: Sc25519) -> Sc25519:
/// def sub256_modm(r: Sc25519 | None, a: Sc25519, b: Sc25519) -> Sc25519:
/// """
/// Scalar subtraction
/// """
@ -439,7 +439,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_sub256_modm_obj, 2, 3,
mod_trezorcrypto_monero_sub256_modm);
/// def mul256_modm(r: Optional[Sc25519], a: Sc25519, b: Sc25519) -> Sc25519:
/// def mul256_modm(r: Sc25519 | None, a: Sc25519, b: Sc25519) -> Sc25519:
/// """
/// Scalar multiplication
/// """
@ -460,7 +460,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_mul256_modm);
/// def mulsub256_modm(
/// r: Optional[Sc25519], a: Sc25519, b: Sc25519, c: Sc25519
/// r: Sc25519 | None, a: Sc25519, b: Sc25519, c: Sc25519
/// ) -> Sc25519:
/// """
/// c - a*b
@ -484,7 +484,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_mulsub256_modm);
/// def muladd256_modm(
/// r: Optional[Sc25519], a: Sc25519, b: Sc25519, c: Sc25519
/// r: Sc25519 | None, a: Sc25519, b: Sc25519, c: Sc25519
/// ) -> Sc25519:
/// """
/// c + a*b
@ -507,7 +507,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_muladd256_modm_obj, 3, 4,
mod_trezorcrypto_monero_muladd256_modm);
/// def inv256_modm(r: Optional[Sc25519], a: Sc25519) -> Sc25519:
/// def inv256_modm(r: Sc25519 | None, a: Sc25519) -> Sc25519:
/// """
/// Scalar modular inversion
/// """
@ -542,7 +542,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_inv256_modm);
/// def pack256_modm(
/// r: Optional[bytes], a: Sc25519, offset: Optional[int] = 0
/// r: bytes | None, a: Sc25519, offset: int | None = 0
/// ) -> bytes:
/// """
/// Scalar compression
@ -572,7 +572,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_pack256_modm);
/// def unpack256_modm(
/// r: Optional[Sc25519], a: bytes, offset: int = 0
/// r: Sc25519 | None, a: bytes, offset: int = 0
/// ) -> Sc25519:
/// """
/// Scalar decompression
@ -591,7 +591,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_unpack256_modm);
/// def unpack256_modm_noreduce(
/// r: Optional[Sc25519], a: bytes, offset: int = 0
/// r: Sc25519 | None, a: bytes, offset: int = 0
/// ) -> Sc25519:
/// """
/// Scalar decompression, raw, without modular reduction
@ -620,7 +620,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
// GE25519 Defs
//
/// def ge25519_set_neutral(r: Optional[Ge25519]) -> Ge25519:
/// def ge25519_set_neutral(r: Ge25519 | None) -> Ge25519:
/// """
/// Sets neutral point
/// """
@ -634,7 +634,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_set_neutral_obj, 0, 1,
mod_trezorcrypto_monero_ge25519_set_neutral);
/// def ge25519_set_xmr_h(r: Optional[Ge25519]) -> Ge25519:
/// def ge25519_set_xmr_h(r: Ge25519 | None) -> Ge25519:
/// """
/// Sets H point
/// """
@ -676,7 +676,7 @@ STATIC mp_obj_t mod_trezorcrypto_monero_ge25519_eq(const mp_obj_t a,
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_monero_ge25519_eq_obj,
mod_trezorcrypto_monero_ge25519_eq);
/// def ge25519_add(r: Optional[Ge25519], a: Ge25519, b: Ge25519) -> Ge25519:
/// def ge25519_add(r: Ge25519 | None, a: Ge25519, b: Ge25519) -> Ge25519:
/// """
/// Adds EC points
/// """
@ -696,7 +696,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_add_obj, 2, 3,
mod_trezorcrypto_monero_ge25519_add);
/// def ge25519_sub(r: Optional[Ge25519], a: Ge25519, b: Ge25519) -> Ge25519:
/// def ge25519_sub(r: Ge25519 | None, a: Ge25519, b: Ge25519) -> Ge25519:
/// """
/// Subtracts EC points
/// """
@ -716,7 +716,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_sub_obj, 2, 3,
mod_trezorcrypto_monero_ge25519_sub);
/// def ge25519_double(r: Optional[Ge25519], p: Ge25519) -> Ge25519:
/// def ge25519_double(r: Ge25519 | None, p: Ge25519) -> Ge25519:
/// """
/// EC point doubling
/// """
@ -733,7 +733,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_double_obj, 1, 2,
mod_trezorcrypto_monero_ge25519_double);
/// def ge25519_mul8(r: Optional[Ge25519], p: Ge25519) -> Ge25519:
/// def ge25519_mul8(r: Ge25519 | None, p: Ge25519) -> Ge25519:
/// """
/// EC point * 8
/// """
@ -751,7 +751,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_mul8);
/// def ge25519_double_scalarmult_vartime(
/// r: Optional[Ge25519], p1: Ge25519, s1: Sc25519, s2: Sc25519
/// r: Ge25519 | None, p1: Ge25519, s1: Sc25519, s2: Sc25519
/// ) -> Ge25519:
/// """
/// s1 * G + s2 * p1
@ -775,7 +775,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_double_scalarmult_vartime);
/// def ge25519_double_scalarmult_vartime2(
/// r: Optional[Ge25519],
/// r: Ge25519 | None,
/// p1: Ge25519,
/// s1: Sc25519,
/// p2: Ge25519,
@ -806,7 +806,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_double_scalarmult_vartime2);
/// def ge25519_scalarmult_base(
/// r: Optional[Ge25519], s: Union[Sc25519, int]
/// r: Ge25519 | None, s: Sc25519 | int
/// ) -> Ge25519:
/// """
/// s * G
@ -835,7 +835,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_scalarmult_base);
/// def ge25519_scalarmult(
/// r: Optional[Ge25519], p: Ge25519, s: Union[Sc25519, int]
/// r: Ge25519 | None, p: Ge25519, s: Sc25519 | int
/// ) -> Ge25519:
/// """
/// s * p
@ -894,7 +894,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_ge25519_pack);
/// def ge25519_unpack_vartime(
/// r: Optional[Ge25519], buff: bytes, offset: int = 0
/// r: Ge25519 | None, buff: bytes, offset: int = 0
/// ) -> Ge25519:
/// """
/// Point decompression
@ -941,7 +941,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_base58_addr_encode_check_obj, 2, 2,
mod_trezorcrypto_monero_xmr_base58_addr_encode_check);
/// def base58_addr_decode_check(buff: bytes) -> Tuple[bytes, int]:
/// def base58_addr_decode_check(buff: bytes) -> tuple[bytes, int]:
/// """
/// Monero block base 58 decoding, returning (decoded, tag) or raising on
/// error.
@ -972,7 +972,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_base58_addr_decode_check_obj, 1, 1,
mod_trezorcrypto_monero_xmr_base58_addr_decode_check);
/// def xmr_random_scalar(r: Optional[Sc25519] = None) -> Sc25519:
/// def xmr_random_scalar(r: Sc25519 | None = None) -> Sc25519:
/// """
/// Generates a random scalar
/// """
@ -987,7 +987,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_random_scalar);
// clang-format off
/// def xmr_fast_hash(r: Optional[bytes], buff: bytes, length: int, offset: int) -> bytes:
/// def xmr_fast_hash(r: bytes | None, buff: bytes, length: int, offset: int) -> bytes:
// clang-format on
/// """
/// XMR fast hash
@ -1027,7 +1027,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_fast_hash);
// clang-format off
/// def xmr_hash_to_ec(r: Optional[Ge25519], buff: bytes, length: int, offset:
/// def xmr_hash_to_ec(r: Ge25519 | None, buff: bytes, length: int, offset:
/// int) -> Ge25519:
// clang-format on
/// """
@ -1056,7 +1056,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_hash_to_ec);
// clang-format off
/// def xmr_hash_to_scalar(r: Optional[Sc25519], buff: bytes, length: int,
/// def xmr_hash_to_scalar(r: Sc25519 | None, buff: bytes, length: int,
/// offset: int) -> Sc25519:
// clang-format on
/// """
@ -1085,7 +1085,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_hash_to_scalar);
/// def xmr_derivation_to_scalar(
/// r: Optional[Sc25519], p: Ge25519, output_index: int
/// r: Sc25519 | None, p: Ge25519, output_index: int
/// ) -> Sc25519:
/// """
/// H_s(derivation || varint(output_index))
@ -1105,7 +1105,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_derivation_to_scalar);
/// def xmr_generate_key_derivation(
/// r: Optional[Ge25519], A: Ge25519, b: Sc25519
/// r: Ge25519 | None, A: Ge25519, b: Sc25519
/// ) -> Ge25519:
/// """
/// 8*(key2*key1)
@ -1127,7 +1127,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_generate_key_derivation);
/// def xmr_derive_private_key(
/// r: Optional[Sc25519], deriv: Ge25519, idx: int, base: Sc25519
/// r: Sc25519 | None, deriv: Ge25519, idx: int, base: Sc25519
/// ) -> Sc25519:
/// """
/// base + H_s(derivation || varint(output_index))
@ -1149,7 +1149,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_derive_private_key);
/// def xmr_derive_public_key(
/// r: Optional[Ge25519], deriv: Ge25519, idx: int, base: Ge25519
/// r: Ge25519 | None, deriv: Ge25519, idx: int, base: Ge25519
/// ) -> Ge25519:
/// """
/// H_s(derivation || varint(output_index))G + base
@ -1171,7 +1171,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_derive_public_key);
/// def xmr_add_keys2(
/// r: Optional[Ge25519], a: Sc25519, b: Sc25519, B: Ge25519
/// r: Ge25519 | None, a: Sc25519, b: Sc25519, B: Ge25519
/// ) -> Ge25519:
/// """
/// aG + bB, G is basepoint
@ -1193,7 +1193,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_add_keys2);
/// def xmr_add_keys2_vartime(
/// r: Optional[Ge25519], a: Sc25519, b: Sc25519, B: Ge25519
/// r: Ge25519 | None, a: Sc25519, b: Sc25519, B: Ge25519
/// ) -> Ge25519:
/// """
/// aG + bB, G is basepoint
@ -1216,7 +1216,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_add_keys2_vartime);
/// def xmr_add_keys3(
/// r: Optional[Ge25519], a: Sc25519, A: Ge25519, b: Sc25519, B: Ge25519
/// r: Ge25519 | None, a: Sc25519, A: Ge25519, b: Sc25519, B: Ge25519
/// ) -> Ge25519:
/// """
/// aA + bB
@ -1240,7 +1240,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_add_keys3);
/// def xmr_add_keys3_vartime(
/// r: Optional[Ge25519], a: Sc25519, A: Ge25519, b: Sc25519, B: Ge25519
/// r: Ge25519 | None, a: Sc25519, A: Ge25519, b: Sc25519, B: Ge25519
/// ) -> Ge25519:
/// """
/// aA + bB
@ -1265,7 +1265,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_add_keys3_vartime);
/// def xmr_get_subaddress_secret_key(
/// r: Optional[Sc25519], major: int, minor: int, m: Sc25519
/// r: Sc25519 | None, major: int, minor: int, m: Sc25519
/// ) -> Sc25519:
/// """
/// Hs(SubAddr || a || index_major || index_minor)
@ -1285,7 +1285,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_xmr_get_subaddress_secret_key_obj, 3, 4,
mod_trezorcrypto_monero_xmr_get_subaddress_secret_key);
/// def xmr_gen_c(r: Optional[Ge25519], a: Sc25519, amount: int) -> Ge25519:
/// def xmr_gen_c(r: Ge25519 | None, a: Sc25519, amount: int) -> Ge25519:
/// """
/// aG + amount * H
/// """

View File

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

View File

@ -37,7 +37,7 @@ typedef struct _mp_obj_Ripemd160_t {
STATIC mp_obj_t mod_trezorcrypto_Ripemd160_update(mp_obj_t self, mp_obj_t data);
/// def __init__(self, data: Optional[bytes] = None) -> None:
/// def __init__(self, data: bytes | None = None) -> None:
/// """
/// Creates a hash context object.
/// """

View File

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

View File

@ -37,7 +37,7 @@ typedef struct _mp_obj_Sha1_t {
STATIC mp_obj_t mod_trezorcrypto_Sha1_update(mp_obj_t self, mp_obj_t data);
/// def __init__(self, data: Optional[bytes] = None) -> None:
/// def __init__(self, data: bytes | None = None) -> None:
/// """
/// Creates a hash context object.
/// """

View File

@ -37,7 +37,7 @@ typedef struct _mp_obj_Sha256_t {
STATIC mp_obj_t mod_trezorcrypto_Sha256_update(mp_obj_t self, mp_obj_t data);
/// def __init__(self, data: Optional[bytes] = None) -> None:
/// def __init__(self, data: bytes | None = None) -> None:
/// """
/// Creates a hash context object.
/// """

View File

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

View File

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

View File

@ -37,7 +37,7 @@ typedef struct _mp_obj_Sha512_t {
STATIC mp_obj_t mod_trezorcrypto_Sha512_update(mp_obj_t self, mp_obj_t data);
/// def __init__(self, data: Optional[bytes] = None) -> None:
/// def __init__(self, data: bytes | None = None) -> None:
/// """
/// Creates a hash context object.
/// """

View File

@ -27,7 +27,7 @@
/// package: trezorcrypto.shamir
/// def interpolate(shares: List[Tuple[int, bytes]], x: int) -> bytes:
/// def interpolate(shares: list[tuple[int, bytes]], x: int) -> bytes:
/// """
/// Returns f(x) given the Shamir shares (x_1, f(x_1)), ... , (x_k, f(x_k)).
/// :param shares: The Shamir shares.

View File

@ -170,9 +170,9 @@ typedef struct _mp_obj_FatFSFile_t {
/// from types import TracebackType
/// def __exit__(
/// self, type: Optional[Type[BaseException]],
/// value: Optional[BaseException],
/// traceback: Optional[TracebackType],
/// self, type: type[BaseException] | None,
/// value: BaseException | None,
/// traceback: TracebackType | None,
/// ) -> None:
/// """
/// Close an open file object
@ -223,7 +223,7 @@ STATIC mp_obj_t mod_trezorio_FatFSFile_read(mp_obj_t self, mp_obj_t data) {
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorio_FatFSFile_read_obj,
mod_trezorio_FatFSFile_read);
/// def write(self, data: Union[bytes, bytearray]) -> int:
/// def write(self, data: bytes | bytearray) -> int:
/// """
/// Write data to the file
/// """
@ -312,7 +312,7 @@ STATIC const mp_obj_type_t mod_trezorio_FatFSFile_type = {
.locals_dict = (void *)&mod_trezorio_FatFSFile_locals_dict,
};
/// class FatFSDir(Iterator[Tuple[int, str, str]]):
/// class FatFSDir(Iterator[tuple[int, str, str]]):
/// """
/// Class encapsulating directory
/// """
@ -321,7 +321,7 @@ typedef struct _mp_obj_FatFSDir_t {
DIR dp;
} mp_obj_FatFSDir_t;
/// def __next__(self) -> Tuple[int, str, str]:
/// def __next__(self) -> tuple[int, str, str]:
/// """
/// Read an entry in the directory
/// """
@ -453,7 +453,7 @@ STATIC mp_obj_t mod_trezorio_fatfs_unlink(mp_obj_t path) {
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorio_fatfs_unlink_obj,
mod_trezorio_fatfs_unlink);
/// def stat(path: str) -> Tuple[int, str, str]:
/// def stat(path: str) -> tuple[int, str, str]:
/// """
/// Get file status
/// """

View File

@ -28,7 +28,7 @@
/// package: trezorio.__init__
/// def poll(ifaces: Iterable[int], list_ref: List, timeout_ms: int) -> bool:
/// def poll(ifaces: Iterable[int], list_ref: list, timeout_ms: int) -> bool:
/// """
/// Wait until one of `ifaces` is ready to read or write (using masks
// `io.POLL_READ` and `io.POLL_WRITE`) and assign the result into

View File

@ -158,7 +158,7 @@ STATIC mp_obj_t mod_trezorio_USB_make_new(const mp_obj_type_t *type,
return MP_OBJ_FROM_PTR(o);
}
/// def add(self, iface: Union[HID, VCP, WebUSB]) -> None:
/// def add(self, iface: HID | VCP | WebUSB) -> None:
/// """
/// Registers passed interface into the USB stack.
/// """

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -40,14 +40,14 @@ def verify(public_key: bytes, signature: bytes, message: bytes) -> bool:
# extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h
def cosi_combine_publickeys(public_keys: List[bytes]) -> bytes:
def cosi_combine_publickeys(public_keys: list[bytes]) -> bytes:
"""
Combines a list of public keys used in COSI cosigning scheme.
"""
# extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h
def cosi_combine_signatures(R: bytes, signatures: List[bytes]) -> bytes:
def cosi_combine_signatures(R: bytes, signatures: list[bytes]) -> bytes:
"""
Combines a list of signatures used in COSI cosigning scheme.
"""

View File

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

View File

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

View File

@ -2,7 +2,7 @@ from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-shamir.h
def interpolate(shares: List[Tuple[int, bytes]], x: int) -> bytes:
def interpolate(shares: list[tuple[int, bytes]], x: int) -> bytes:
"""
Returns f(x) given the Shamir shares (x_1, f(x_1)), ... , (x_k, f(x_k)).
:param shares: The Shamir shares.

View File

@ -69,7 +69,7 @@ class HID:
# extmod/modtrezorio/modtrezorio-poll.h
def poll(ifaces: Iterable[int], list_ref: List, timeout_ms: int) -> bool:
def poll(ifaces: Iterable[int], list_ref: list, timeout_ms: int) -> bool:
"""
Wait until one of `ifaces` is ready to read or write (using masks
`list_ref`:
@ -120,7 +120,7 @@ class USB:
"""
"""
def add(self, iface: Union[HID, VCP, WebUSB]) -> None:
def add(self, iface: HID | VCP | WebUSB) -> None:
"""
Registers passed interface into the USB stack.
"""

View File

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

View File

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

View File

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

View File

@ -14,7 +14,7 @@ from apps.common.request_pin import verify_user_pin
if False:
import protobuf
from typing import Iterable, NoReturn, Optional, Protocol
from typing import Iterable, NoReturn, Protocol
from trezor.messages.Initialize import Initialize
from trezor.messages.EndSession import EndSession
from trezor.messages.GetFeatures import GetFeatures
@ -235,7 +235,7 @@ async def unlock_device(ctx: wire.GenericContext = wire.DUMMY_CONTEXT) -> None:
def get_pinlocked_handler(
iface: wire.WireInterface, msg_type: int
) -> Optional[wire.Handler[wire.Msg]]:
) -> wire.Handler[wire.Msg] | None:
orig_handler = wire.find_registered_workflow_handler(iface, msg_type)
if orig_handler is None:
return None

View File

@ -12,7 +12,6 @@ from .multisig import multisig_get_pubkeys, multisig_pubkey_index
from .scripts import output_script_multisig, output_script_native_p2wpkh_or_p2wsh
if False:
from typing import List, Optional
from trezor.crypto import bip32
from trezor.messages.TxInputType import EnumTypeInputScriptType
@ -21,7 +20,7 @@ def get_address(
script_type: EnumTypeInputScriptType,
coin: CoinInfo,
node: bip32.HDNode,
multisig: Optional[MultisigRedeemScriptType] = None,
multisig: MultisigRedeemScriptType | None = None,
) -> str:
if multisig:
# Ensure that our public key is included in the multisig.
@ -74,7 +73,7 @@ def get_address(
raise wire.ProcessError("Invalid script type")
def address_multisig_p2sh(pubkeys: List[bytes], m: int, coin: CoinInfo) -> str:
def address_multisig_p2sh(pubkeys: list[bytes], m: int, coin: CoinInfo) -> str:
if coin.address_type_p2sh is None:
raise wire.ProcessError("Multisig not enabled on this coin")
redeem_script = output_script_multisig(pubkeys, m)
@ -82,7 +81,7 @@ def address_multisig_p2sh(pubkeys: List[bytes], m: int, coin: CoinInfo) -> str:
return address_p2sh(redeem_script_hash, coin)
def address_multisig_p2wsh_in_p2sh(pubkeys: List[bytes], m: int, coin: CoinInfo) -> str:
def address_multisig_p2wsh_in_p2sh(pubkeys: list[bytes], m: int, coin: CoinInfo) -> str:
if coin.address_type_p2sh is None:
raise wire.ProcessError("Multisig not enabled on this coin")
witness_script = output_script_multisig(pubkeys, m)
@ -90,7 +89,7 @@ def address_multisig_p2wsh_in_p2sh(pubkeys: List[bytes], m: int, coin: CoinInfo)
return address_p2wsh_in_p2sh(witness_script_hash, coin)
def address_multisig_p2wsh(pubkeys: List[bytes], m: int, hrp: str) -> str:
def address_multisig_p2wsh(pubkeys: list[bytes], m: int, hrp: str) -> str:
if not hrp:
raise wire.ProcessError("Multisig not enabled on this coin")
witness_script = output_script_multisig(pubkeys, m)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -31,7 +31,7 @@ from ..writers import TX_HASH_SIZE
from . import layout
if False:
from typing import Any, Awaitable, Optional
from typing import Any, Awaitable
from trezor.messages.SignTx import EnumTypeAmountUnit
@ -252,7 +252,7 @@ def confirm_nondefault_locktime(lock_time: int, lock_time_disabled: bool) -> Awa
return (yield UiConfirmNonDefaultLocktime(lock_time, lock_time_disabled))
def request_tx_meta(tx_req: TxRequest, coin: CoinInfo, tx_hash: Optional[bytes] = None) -> Awaitable[PrevTx]: # type: ignore
def request_tx_meta(tx_req: TxRequest, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[PrevTx]: # type: ignore
assert tx_req.details is not None
tx_req.request_type = TXMETA
tx_req.details.tx_hash = tx_hash
@ -262,7 +262,7 @@ def request_tx_meta(tx_req: TxRequest, coin: CoinInfo, tx_hash: Optional[bytes]
def request_tx_extra_data( # type: ignore
tx_req: TxRequest, offset: int, size: int, tx_hash: Optional[bytes] = None
tx_req: TxRequest, offset: int, size: int, tx_hash: bytes | None = None
) -> Awaitable[bytearray]:
assert tx_req.details is not None
tx_req.request_type = TXEXTRADATA
@ -274,7 +274,7 @@ def request_tx_extra_data( # type: ignore
return ack.tx.extra_data_chunk
def request_tx_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Optional[bytes] = None) -> Awaitable[TxInput]: # type: ignore
def request_tx_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[TxInput]: # type: ignore
assert tx_req.details is not None
if tx_hash:
tx_req.request_type = TXORIGINPUT
@ -287,7 +287,7 @@ def request_tx_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Optiona
return sanitize_tx_input(ack.tx.input, coin)
def request_tx_prev_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Optional[bytes] = None) -> Awaitable[PrevInput]: # type: ignore
def request_tx_prev_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[PrevInput]: # type: ignore
assert tx_req.details is not None
tx_req.request_type = TXINPUT
tx_req.details.request_index = i
@ -297,7 +297,7 @@ def request_tx_prev_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Op
return sanitize_tx_prev_input(ack.tx.input, coin)
def request_tx_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Optional[bytes] = None) -> Awaitable[TxOutput]: # type: ignore
def request_tx_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[TxOutput]: # type: ignore
assert tx_req.details is not None
if tx_hash:
tx_req.request_type = TXORIGOUTPUT
@ -310,7 +310,7 @@ def request_tx_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Option
return sanitize_tx_output(ack.tx.output, coin)
def request_tx_prev_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: Optional[bytes] = None) -> Awaitable[PrevOutput]: # type: ignore
def request_tx_prev_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[PrevOutput]: # type: ignore
assert tx_req.details is not None
tx_req.request_type = TXOUTPUT
tx_req.details.request_index = i

View File

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

View File

@ -5,7 +5,7 @@ from .. import multisig
from ..common import BIP32_WALLET_DEPTH
if False:
from typing import Any, Union, Generic, TypeVar
from typing import Any, Generic, TypeVar
from trezor.messages.TxInput import TxInput
from trezor.messages.TxOutput import TxOutput
@ -43,10 +43,10 @@ class MatchChecker(Generic[T]):
UNDEFINED = object()
def __init__(self) -> None:
self.attribute: Union[object, T] = self.UNDEFINED
self.attribute: object | T = self.UNDEFINED
self.read_only = False # Failsafe to ensure that add_input() is not accidentally called after output_matches().
def attribute_from_tx(self, txio: Union[TxInput, TxOutput]) -> T:
def attribute_from_tx(self, txio: TxInput | TxOutput) -> T:
# Return the attribute from the txio, which is to be used for matching.
# If the txio is invalid for matching, then return an object which
# evaluates as a boolean False.
@ -85,14 +85,14 @@ class MatchChecker(Generic[T]):
class WalletPathChecker(MatchChecker):
def attribute_from_tx(self, txio: Union[TxInput, TxOutput]) -> Any:
def attribute_from_tx(self, txio: TxInput | TxOutput) -> Any:
if len(txio.address_n) < BIP32_WALLET_DEPTH:
return None
return txio.address_n[:-BIP32_WALLET_DEPTH]
class MultisigFingerprintChecker(MatchChecker):
def attribute_from_tx(self, txio: Union[TxInput, TxOutput]) -> Any:
def attribute_from_tx(self, txio: TxInput | TxOutput) -> Any:
if not txio.multisig:
return None
return multisig.multisig_fingerprint(txio.multisig)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -66,7 +66,7 @@ from .layout import (
from .seed import is_byron_path, is_shelley_path
if False:
from typing import Any, Dict, List, Optional, Tuple, Union
from typing import Any, Optional, Union
from trezor.messages.CardanoSignTx import CardanoSignTx
from trezor.messages.CardanoTxCertificateType import CardanoTxCertificateType
@ -78,9 +78,9 @@ if False:
from apps.common.cbor import CborSequence
from apps.common.paths import PathSchema
CborizedTokenBundle = Dict[bytes, Dict[bytes, int]]
CborizedTxOutput = Tuple[bytes, Union[int, Tuple[int, CborizedTokenBundle]]]
CborizedSignedTx = Tuple[Dict, Dict, Optional[cbor.Raw]]
CborizedTokenBundle = dict[bytes, dict[bytes, int]]
CborizedTxOutput = tuple[bytes, Union[int, tuple[int, CborizedTokenBundle]]]
CborizedSignedTx = tuple[dict, dict, Optional[cbor.Raw]]
TxHash = bytes
METADATA_HASH_SIZE = 32
@ -123,7 +123,7 @@ async def sign_tx(
async def _sign_ordinary_tx(
ctx: wire.Context, msg: CardanoSignTx, keychain: seed.Keychain
) -> Tuple[CborizedSignedTx, TxHash]:
) -> tuple[CborizedSignedTx, TxHash]:
for i in msg.inputs:
await validate_path(
ctx, keychain, i.address_n, SCHEMA_ADDRESS.match(i.address_n)
@ -142,7 +142,7 @@ async def _sign_ordinary_tx(
async def _sign_stake_pool_registration_tx(
ctx: wire.Context, msg: CardanoSignTx, keychain: seed.Keychain
) -> Tuple[CborizedSignedTx, TxHash]:
) -> tuple[CborizedSignedTx, TxHash]:
"""
We have a separate tx signing flow for stake pool registration because it's a
transaction where the witnessable entries (i.e. inputs, withdrawals, etc.)
@ -200,7 +200,7 @@ def _validate_stake_pool_registration_tx_structure(msg: CardanoSignTx) -> None:
def _validate_outputs(
keychain: seed.Keychain,
outputs: List[CardanoTxOutputType],
outputs: list[CardanoTxOutputType],
protocol_magic: int,
network_id: int,
) -> None:
@ -225,7 +225,7 @@ def _validate_outputs(
raise wire.ProcessError("Total transaction amount is out of range!")
def _validate_token_bundle(token_bundle: List[CardanoAssetGroupType]) -> None:
def _validate_token_bundle(token_bundle: list[CardanoAssetGroupType]) -> None:
seen_policy_ids = set()
for token_group in token_bundle:
policy_id = bytes(token_group.policy_id)
@ -253,19 +253,19 @@ def _validate_token_bundle(token_bundle: List[CardanoAssetGroupType]) -> None:
seen_asset_name_bytes.add(asset_name_bytes)
def _ensure_no_signing_inputs(inputs: List[CardanoTxInputType]) -> None:
def _ensure_no_signing_inputs(inputs: list[CardanoTxInputType]) -> None:
if any(i.address_n for i in inputs):
raise INVALID_STAKEPOOL_REGISTRATION_TX_INPUTS
def _validate_certificates(
certificates: List[CardanoTxCertificateType], protocol_magic: int, network_id: int
certificates: list[CardanoTxCertificateType], protocol_magic: int, network_id: int
) -> None:
for certificate in certificates:
validate_certificate(certificate, protocol_magic, network_id)
def _validate_withdrawals(withdrawals: List[CardanoTxWithdrawalType]) -> None:
def _validate_withdrawals(withdrawals: list[CardanoTxWithdrawalType]) -> None:
for withdrawal in withdrawals:
if not SCHEMA_STAKING_ANY_ACCOUNT.match(withdrawal.path):
raise INVALID_WITHDRAWAL
@ -274,7 +274,7 @@ def _validate_withdrawals(withdrawals: List[CardanoTxWithdrawalType]) -> None:
raise INVALID_WITHDRAWAL
def _validate_metadata(metadata: Optional[bytes]) -> None:
def _validate_metadata(metadata: bytes | None) -> None:
if not metadata:
return
@ -293,7 +293,7 @@ def _validate_metadata(metadata: Optional[bytes]) -> None:
def _cborize_signed_tx(
keychain: seed.Keychain, msg: CardanoSignTx
) -> Tuple[CborizedSignedTx, TxHash]:
) -> tuple[CborizedSignedTx, TxHash]:
tx_body = _cborize_tx_body(keychain, msg)
tx_hash = _hash_tx_body(tx_body)
@ -313,7 +313,7 @@ def _cborize_signed_tx(
return (tx_body, witnesses, metadata), tx_hash
def _cborize_tx_body(keychain: seed.Keychain, msg: CardanoSignTx) -> Dict:
def _cborize_tx_body(keychain: seed.Keychain, msg: CardanoSignTx) -> dict:
inputs_for_cbor = _cborize_inputs(msg.inputs)
outputs_for_cbor = _cborize_outputs(
keychain, msg.outputs, msg.protocol_magic, msg.network_id
@ -349,16 +349,16 @@ def _cborize_tx_body(keychain: seed.Keychain, msg: CardanoSignTx) -> Dict:
return tx_body
def _cborize_inputs(inputs: List[CardanoTxInputType]) -> List[Tuple[bytes, int]]:
def _cborize_inputs(inputs: list[CardanoTxInputType]) -> list[tuple[bytes, int]]:
return [(tx_input.prev_hash, tx_input.prev_index) for tx_input in inputs]
def _cborize_outputs(
keychain: seed.Keychain,
outputs: List[CardanoTxOutputType],
outputs: list[CardanoTxOutputType],
protocol_magic: int,
network_id: int,
) -> List[CborizedTxOutput]:
) -> list[CborizedTxOutput]:
return [
_cborize_output(keychain, output, protocol_magic, network_id)
for output in outputs
@ -387,7 +387,7 @@ def _cborize_output(
def _cborize_token_bundle(
token_bundle: List[CardanoAssetGroupType],
token_bundle: list[CardanoAssetGroupType],
) -> CborizedTokenBundle:
result: CborizedTokenBundle = {}
@ -404,17 +404,17 @@ def _cborize_token_bundle(
def _cborize_certificates(
keychain: seed.Keychain,
certificates: List[CardanoTxCertificateType],
) -> List[CborSequence]:
certificates: list[CardanoTxCertificateType],
) -> list[CborSequence]:
return [cborize_certificate(keychain, cert) for cert in certificates]
def _cborize_withdrawals(
keychain: seed.Keychain,
withdrawals: List[CardanoTxWithdrawalType],
withdrawals: list[CardanoTxWithdrawalType],
protocol_magic: int,
network_id: int,
) -> Dict[bytes, int]:
) -> dict[bytes, int]:
result = {}
for withdrawal in withdrawals:
reward_address = derive_address_bytes(
@ -436,7 +436,7 @@ def _hash_metadata(metadata: bytes) -> bytes:
return hashlib.blake2b(data=metadata, outlen=METADATA_HASH_SIZE).digest()
def _hash_tx_body(tx_body: Dict) -> bytes:
def _hash_tx_body(tx_body: dict) -> bytes:
tx_body_cbor_chunks = cbor.encode_streamed(tx_body)
hashfn = hashlib.blake2b(outlen=32)
@ -448,12 +448,12 @@ def _hash_tx_body(tx_body: Dict) -> bytes:
def _cborize_witnesses(
keychain: seed.Keychain,
inputs: List[CardanoTxInputType],
certificates: List[CardanoTxCertificateType],
withdrawals: List[CardanoTxWithdrawalType],
inputs: list[CardanoTxInputType],
certificates: list[CardanoTxCertificateType],
withdrawals: list[CardanoTxWithdrawalType],
tx_body_hash: bytes,
protocol_magic: int,
) -> Dict:
) -> dict:
shelley_witnesses = _cborize_shelley_witnesses(
keychain, inputs, certificates, withdrawals, tx_body_hash
)
@ -463,7 +463,7 @@ def _cborize_witnesses(
# use key 0 for shelley witnesses and key 2 for byron witnesses
# according to the spec in shelley.cddl in cardano-ledger-specs
witnesses: Dict[Any, Any] = {}
witnesses: dict[Any, Any] = {}
if shelley_witnesses:
witnesses[0] = shelley_witnesses
if byron_witnesses:
@ -474,11 +474,11 @@ def _cborize_witnesses(
def _cborize_shelley_witnesses(
keychain: seed.Keychain,
inputs: List[CardanoTxInputType],
certificates: List[CardanoTxCertificateType],
withdrawals: List[CardanoTxWithdrawalType],
inputs: list[CardanoTxInputType],
certificates: list[CardanoTxCertificateType],
withdrawals: list[CardanoTxWithdrawalType],
tx_body_hash: bytes,
) -> List[Tuple[bytes, bytes]]:
) -> list[tuple[bytes, bytes]]:
shelley_witnesses = []
# include only one witness for each path
@ -511,8 +511,8 @@ def _cborize_shelley_witnesses(
def _cborize_shelley_witness(
keychain: seed.Keychain, tx_body_hash: bytes, path: List[int]
) -> Tuple[bytes, bytes]:
keychain: seed.Keychain, tx_body_hash: bytes, path: list[int]
) -> tuple[bytes, bytes]:
node = keychain.derive(path)
signature = ed25519.sign_ext(
@ -525,10 +525,10 @@ def _cborize_shelley_witness(
def _cborize_byron_witnesses(
keychain: seed.Keychain,
inputs: List[CardanoTxInputType],
inputs: list[CardanoTxInputType],
tx_body_hash: bytes,
protocol_magic: int,
) -> List[Tuple[bytes, bytes, bytes, bytes]]:
) -> list[tuple[bytes, bytes, bytes, bytes]]:
byron_witnesses = []
# include only one witness for each path
@ -704,7 +704,7 @@ async def _show_change_output_staking_warnings(
# addresses from the same account as inputs should be hidden
def _should_hide_output(output: List[int], inputs: List[CardanoTxInputType]) -> bool:
def _should_hide_output(output: list[int], inputs: list[CardanoTxInputType]) -> bool:
for tx_input in inputs:
inp = tx_input.address_n
if (
@ -732,7 +732,7 @@ def _is_network_id_verifiable(msg: CardanoSignTx) -> bool:
async def _fail_or_warn_if_invalid_path(
ctx: wire.Context, schema: PathSchema, path: List[int], path_name: str
ctx: wire.Context, schema: PathSchema, path: list[int], path_name: str
) -> None:
if not schema.match(path):
if safety_checks.is_strict():

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -11,10 +11,8 @@ if False:
Collection,
Container,
Iterable,
List,
Sequence,
TypeVar,
Union,
)
from typing_extensions import Protocol
from trezor import wire
@ -106,7 +104,7 @@ class PathSchema:
"**": Interval(0, 0xFFFF_FFFF),
}
def __init__(self, pattern: str, slip44_id: Union[int, Iterable[int]]) -> None:
def __init__(self, pattern: str, slip44_id: int | Iterable[int]) -> None:
if not pattern.startswith("m/"):
raise ValueError # unsupported path template
components = pattern[2:].split("/")
@ -114,7 +112,7 @@ class PathSchema:
if isinstance(slip44_id, int):
slip44_id = (slip44_id,)
self.schema: List[Container[int]] = []
self.schema: list[Container[int]] = []
self.trailing_components: Container[int] = ()
for component in components:
@ -270,7 +268,7 @@ def path_is_hardened(address_n: Bip32Path) -> bool:
return all(is_hardened(n) for n in address_n)
def break_address_n_to_lines(address_n: Bip32Path) -> List[str]:
def break_address_n_to_lines(address_n: Bip32Path) -> list[str]:
lines = []
path_str = address_n_to_str(address_n)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -10,11 +10,10 @@ from .helpers import public_key_to_wif
from .layout import require_get_public_key
if False:
from typing import Tuple
from trezor.crypto import bip32
def _get_public_key(node: bip32.HDNode) -> Tuple[str, bytes]:
def _get_public_key(node: bip32.HDNode) -> tuple[str, bytes]:
seckey = node.private_key()
public_key = secp256k1.publickey(seckey, True)
wif = public_key_to_wif(public_key)

View File

@ -9,7 +9,7 @@ SLIP44_WANCHAIN = const(5718350)
SLIP44_ETHEREUM = const(60)
if False:
from typing import Iterator, Optional
from typing import Iterator
def is_wanchain(chain_id: int, tx_type: int) -> bool:
@ -24,14 +24,14 @@ def shortcut_by_chain_id(chain_id: int, tx_type: int = None) -> str:
return n.shortcut if n is not None else "UNKN"
def by_chain_id(chain_id: int) -> Optional["NetworkInfo"]:
def by_chain_id(chain_id: int) -> "NetworkInfo" | None:
for n in _networks_iterator():
if n.chain_id == chain_id:
return n
return None
def by_slip44(slip44: int) -> Optional["NetworkInfo"]:
def by_slip44(slip44: int) -> "NetworkInfo" | None:
if slip44 == SLIP44_WANCHAIN:
# Coerce to Ethereum
slip44 = SLIP44_ETHEREUM

View File

@ -9,7 +9,7 @@ SLIP44_WANCHAIN = const(5718350)
SLIP44_ETHEREUM = const(60)
if False:
from typing import Iterator, Optional
from typing import Iterator
def is_wanchain(chain_id: int, tx_type: int) -> bool:
@ -24,14 +24,14 @@ def shortcut_by_chain_id(chain_id: int, tx_type: int = None) -> str:
return n.shortcut if n is not None else "UNKN"
def by_chain_id(chain_id: int) -> Optional["NetworkInfo"]:
def by_chain_id(chain_id: int) -> "NetworkInfo" | None:
for n in _networks_iterator():
if n.chain_id == chain_id:
return n
return None
def by_slip44(slip44: int) -> Optional["NetworkInfo"]:
def by_slip44(slip44: int) -> "NetworkInfo" | None:
if slip44 == SLIP44_WANCHAIN:
# Coerce to Ethereum
slip44 = SLIP44_ETHEREUM

View File

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

View File

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

View File

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

View File

@ -9,7 +9,6 @@ from trezor.ui.components.tt.button import (
)
if False:
from typing import Optional, Tuple
from trezor.ui.components.tt.button import ButtonContent, ButtonStyleStateType
@ -120,7 +119,7 @@ class Bip39Keyboard(ui.Layout):
("abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz")
)
]
self.pending_button: Optional[Button] = None
self.pending_button: Button | None = None
self.pending_index = 0
def dispatch(self, event: int, x: int, y: int) -> None:
@ -172,7 +171,7 @@ class Bip39Keyboard(ui.Layout):
# Word was confirmed by the user.
raise ui.Result(word)
def edit(self, text: str, button: Optional[Button] = None, index: int = 0) -> None:
def edit(self, text: str, button: Button | None = None, index: int = 0) -> None:
self.pending_button = button
self.pending_index = index
@ -217,7 +216,7 @@ class Bip39Keyboard(ui.Layout):
if __debug__:
def create_tasks(self) -> Tuple[loop.Task, ...]:
def create_tasks(self) -> tuple[loop.Task, ...]:
from apps.debug import input_signal
return super().create_tasks() + (input_signal(),)

View File

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

View File

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

View File

@ -7,7 +7,7 @@ from .. import backup_types
if False:
from trezor.messages.ResetDevice import EnumTypeBackupType
from typing import Optional, Tuple, List, Union
from typing import Union
class RecoveryAborted(Exception):
@ -24,7 +24,7 @@ def process_bip39(words: str) -> bytes:
return words.encode()
def process_slip39(words: str) -> Tuple[Optional[bytes], slip39.Share]:
def process_slip39(words: str) -> tuple[bytes | None, slip39.Share]:
"""
Processes a single mnemonic share. Returns the encrypted master secret
(or None if more shares are needed) and the share's group index and member index.
@ -92,7 +92,7 @@ def process_slip39(words: str) -> Tuple[Optional[bytes], slip39.Share]:
if False:
Slip39State = Union[Tuple[int, EnumTypeBackupType], Tuple[None, None]]
Slip39State = Union[tuple[int, EnumTypeBackupType], tuple[None, None]]
def load_slip39_state() -> Slip39State:
@ -106,7 +106,7 @@ def load_slip39_state() -> Slip39State:
return word_count, backup_types.infer_backup_type(True, share)
def fetch_previous_mnemonics() -> Optional[List[List[str]]]:
def fetch_previous_mnemonics() -> list[list[str]] | None:
mnemonics = []
if not storage.recovery.get_slip39_group_count():
return None

View File

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

View File

@ -15,7 +15,6 @@ from apps.common.confirm import confirm, require_hold_to_confirm
if False:
from trezor import loop
from typing import List, Tuple
if __debug__:
from apps import debug
@ -596,8 +595,8 @@ class MnemonicWordSelect(ui.Layout):
if __debug__:
def read_content(self) -> List[str]:
def read_content(self) -> list[str]:
return self.text.read_content() + [b.text for b in self.buttons]
def create_tasks(self) -> Tuple[loop.Task, ...]:
def create_tasks(self) -> tuple[loop.Task, ...]:
return super().create_tasks() + (debug.input_signal(),)

View File

@ -14,11 +14,11 @@ from apps.common.request_pin import (
from apps.common.sdcard import confirm_retry_sd, ensure_sdcard
if False:
from typing import Awaitable, Tuple
from typing import Awaitable
from trezor.messages.SdProtect import SdProtect
def _make_salt() -> Tuple[bytes, bytes, bytes]:
def _make_salt() -> tuple[bytes, bytes, bytes]:
salt = random.bytes(storage.sd_salt.SD_SALT_LEN_BYTES)
auth_key = random.bytes(storage.device.SD_SALT_AUTH_KEY_LEN_BYTES)
tag = storage.sd_salt.compute_auth_tag(salt, auth_key)

View File

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

View File

@ -14,7 +14,6 @@ DUMMY_PAYMENT_ID = b"\x00\x00\x00\x00\x00\x00\x00\x00"
if False:
from typing import Optional
from apps.monero.signing.state import State
from trezor.messages.MoneroTransactionData import MoneroTransactionData
from trezor.messages.MoneroTransactionDestinationEntry import (
@ -209,7 +208,7 @@ class LiveRefreshStep(ui.Component):
)
async def transaction_step(state: State, step: int, sub_step: Optional[int] = None):
async def transaction_step(state: State, step: int, sub_step: int | None = None):
if step == 0:
info = ["Signing..."]
elif step == state.STEP_INP:

View File

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

View File

@ -6,11 +6,10 @@ from trezor import log
from apps.monero.xmr import crypto
if False:
from typing import Dict, List, Optional, Tuple
from apps.monero.xmr.types import Ge25519, Sc25519
from apps.monero.xmr.credentials import AccountCreds
Subaddresses = Dict[bytes, Tuple[int, int]]
Subaddresses = dict[bytes, tuple[int, int]]
class State:
@ -37,11 +36,11 @@ class State:
- spend private/public key
- and its corresponding address
"""
self.creds: Optional[AccountCreds] = None
self.creds: AccountCreds | None = None
# HMAC/encryption keys used to protect offloaded data
self.key_hmac: Optional[bytes] = None
self.key_enc: Optional[bytes] = None
self.key_hmac: bytes | None = None
self.key_enc: bytes | None = None
"""
Transaction keys
@ -77,8 +76,8 @@ class State:
self.account_idx = 0
# contains additional tx keys if need_additional_tx_keys is True
self.additional_tx_private_keys: List[Sc25519] = []
self.additional_tx_public_keys: List[bytes] = []
self.additional_tx_private_keys: list[Sc25519] = []
self.additional_tx_public_keys: list[bytes] = []
# currently processed input/output index
self.current_input_index = -1
@ -92,14 +91,14 @@ class State:
self.summary_outs_money = 0
# output commitments
self.output_pk_commitments: List[bytes] = []
self.output_pk_commitments: list[bytes] = []
self.output_amounts: List[int] = []
self.output_amounts: list[int] = []
# output *range proof* masks. HP10+ makes them deterministic.
self.output_masks: List[Sc25519] = []
self.output_masks: list[Sc25519] = []
# the range proofs are calculated in batches, this denotes the grouping
self.rsig_grouping: List[int] = []
self.rsig_grouping: list[int] = []
# is range proof computing offloaded or not
self.rsig_offload = False
@ -115,13 +114,13 @@ class State:
# contains an array where each item denotes the input's position
# (inputs are sorted by key images)
self.source_permutation: List[int] = []
self.source_permutation: list[int] = []
# Last key image seen. Used for input permutation correctness check
self.last_ki: Optional[bytes] = None
self.last_ki: bytes | None = None
# Encryption key to release to host after protocol ends without error
self.opening_key: Optional[bytes] = None
self.opening_key: bytes | None = None
# Step transition automaton
self.last_step = self.STEP_INIT
@ -132,7 +131,7 @@ class State:
See Monero-Trezor documentation section 3.3 for more details.
"""
self.tx_prefix_hasher = KeccakXmrArchive()
self.tx_prefix_hash: Optional[bytes] = None
self.tx_prefix_hash: bytes | None = None
"""
Full message hasher/hash that is to be signed using MLSAG.
@ -140,7 +139,7 @@ class State:
See Monero-Trezor documentation section 3.3 for more details.
"""
self.full_message_hasher = PreMlsagHasher()
self.full_message: Optional[bytes] = None
self.full_message: bytes | None = None
def mem_trace(self, x=None, collect=False):
if __debug__:

View File

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

View File

@ -17,7 +17,6 @@ from apps.monero.xmr import crypto, monero, serialize
from .state import State
if False:
from typing import List, Tuple, Optional
from apps.monero.xmr.types import Sc25519, Ge25519
from trezor.messages.MoneroTransactionSourceEntry import (
MoneroTransactionSourceEntry,
@ -139,7 +138,7 @@ async def set_input(
)
def _gen_commitment(state: State, in_amount: int) -> Tuple[Sc25519, Ge25519]:
def _gen_commitment(state: State, in_amount: int) -> tuple[Sc25519, Ge25519]:
"""
Computes Pedersen commitment - pseudo outs
Here is slight deviation from the original protocol.
@ -155,7 +154,7 @@ def _gen_commitment(state: State, in_amount: int) -> Tuple[Sc25519, Ge25519]:
return alpha, crypto.gen_commitment(alpha, in_amount)
def _absolute_output_offsets_to_relative(off: List[int]) -> List[int]:
def _absolute_output_offsets_to_relative(off: list[int]) -> list[int]:
"""
Mixin outputs are specified in relative numbers. First index is absolute
and the rest is an offset of a previous one.
@ -173,7 +172,7 @@ def _absolute_output_offsets_to_relative(off: List[int]) -> List[int]:
def _get_additional_public_key(
src_entr: MoneroTransactionSourceEntry,
) -> Optional[Ge25519]:
) -> Ge25519 | None:
additional_tx_pub_key = None
if len(src_entr.real_out_additional_tx_keys) == 1: # compression
additional_tx_pub_key = crypto.decodepoint(

View File

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

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