style(core): update types to pyright 1.1.404
What changed, and why it matters
This is a large code-style and type-annotation cleanup. It replaces concrete type hints like `bytes` with broader aliases such as `AnyBytes`, `AnyBuffer`, and `StrOrBytes`, and fixes a few minor type-checker warnings (for example adding an `assert ... is not None` and wrapping a value with `bytes(...)`). There are no runtime logic changes, no security fixes, and no behavior changes visible in the diff.
No security action required. Treat as a normal development/style commit. If reviewing, verify that the type aliases are correctly defined and that the generated mocks stay in sync, but no runtime hardening or incident response is indicated.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The commit updates Python type annotations across the Trezor Core codebase to satisfy pyright 1.1.404. It introduces core/mocks/buffer_types.pyi defining AnyBuffer, AnyBytes, and StrOrBytes, imports that stub into many generated .pyi files, and replaces bytes, bytearray | memoryview, str | bytes, AnyStr, and concrete collection types like list[...] with these aliases or more abstract types (Sequence, Iterable). A handful of runtime Python files receive minor annotation-only or type-narrowing changes (assert req.MESSAGE_WIRE_TYPE is not None, bytes(msg.commitment_data).startswith(...), Sequence[AnyBytes] annotations). The C and Rust source changes are limited to docstring/comment type annotations (/// def ...) that feed the mock generator; no implementation code is altered.
Changed components
core/embed/rust/src/protobuf/obj.rscore/embed/rust/src/translations/obj.rscore/embed/rust/src/trezorhal/ble/micropython.rscore/embed/rust/src/ui/api/firmware_micropython.rscore/embed/upymod/modtrezorconfig/modtrezorconfig.ccore/embed/upymod/modtrezorcrypto/*.hcore/embed/upymod/modtrezorio/*.hcore/embed/upymod/modtrezorui/modtrezorui-display.hcore/embed/upymod/modtrezorutils/modtrezorutils.ccore/mocks/buffer_types.pyicore/mocks/generated/*.pyicore/src/apps/base.pycore/src/apps/bitcoin/addresses.pycore/src/apps/bitcoin/authorization.pycore/src/apps/bitcoin/common.pycore/src/apps/bitcoin/get_ownership_proof.pycore/src/apps/bitcoin/multisig.pypyproject.tomltools/pyright_tool.pyInspect captured patch +1699 / −1394
diff --git a/core/embed/rust/src/protobuf/obj.rs b/core/embed/rust/src/protobuf/obj.rs
index 86b0ba74..07dc716f 100644
--- a/core/embed/rust/src/protobuf/obj.rs
+++ b/core/embed/rust/src/protobuf/obj.rs
@@ -348,7 +348,7 @@ pub static mp_module_trezorproto: Module = obj_module! {
Qstr::MP_QSTR_type_for_wire => obj_fn_2!(protobuf_type_for_wire).as_obj(),
/// def decode(
- /// buffer: bytes,
+ /// buffer: AnyBytes,
/// msg_type: type[T],
/// enable_experimental: bool,
/// ) -> T:
@@ -359,7 +359,7 @@ pub static mp_module_trezorproto: Module = obj_module! {
/// """Calculate length of encoding of the specified message."""
Qstr::MP_QSTR_encoded_length => obj_fn_1!(protobuf_len).as_obj(),
- /// def encode(buffer: bytearray | memoryview, msg: MessageType) -> int:
+ /// def encode(buffer: AnyBuffer, msg: MessageType) -> int:
/// """Encode the message into the specified buffer. Return length of
/// encoding."""
Qstr::MP_QSTR_encode => obj_fn_2!(protobuf_encode).as_obj()
diff --git a/core/embed/rust/src/translations/obj.rs b/core/embed/rust/src/translations/obj.rs
index c608c17a..be844fb4 100644
--- a/core/embed/rust/src/translations/obj.rs
+++ b/core/embed/rust/src/translations/obj.rs
@@ -195,11 +195,11 @@ pub static mp_module_trezortranslate: Module = obj_module! {
/// """Erase the translations blob from flash."""
Qstr::MP_QSTR_erase => obj_fn_0!(erase).as_obj(),
- /// def write(data: bytes, offset: int) -> None:
+ /// def write(data: AnyBytes, offset: int) -> None:
/// """Write data to the translations blob in flash."""
Qstr::MP_QSTR_write => obj_fn_2!(write).as_obj(),
- /// def verify(data: bytes) -> None:
+ /// def verify(data: AnyBytes) -> None:
/// """Verify the translations blob."""
Qstr::MP_QSTR_verify => obj_fn_1!(verify).as_obj(),
@@ -209,10 +209,10 @@ pub static mp_module_trezortranslate: Module = obj_module! {
/// language: str
/// version: tuple[int, int, int, int]
/// data_len: int
- /// data_hash: bytes
+ /// data_hash: AnyBytes
/// total_len: int
///
- /// def __init__(self, header_bytes: bytes) -> None:
+ /// def __init__(self, header_bytes: AnyBytes) -> None:
/// """Parse header from bytes.
/// The header has variable length.
/// """
diff --git a/core/embed/rust/src/trezorhal/ble/micropython.rs b/core/embed/rust/src/trezorhal/ble/micropython.rs
index e94feee2..693a7f98 100644
--- a/core/embed/rust/src/trezorhal/ble/micropython.rs
+++ b/core/embed/rust/src/trezorhal/ble/micropython.rs
@@ -272,12 +272,12 @@ pub static mp_module_trezorble: Module = obj_module! {
/// Returns the configured number of this interface.
/// """
///
- /// def write(self, msg: bytes) -> int:
+ /// def write(self, msg: AnyBytes) -> int:
/// """
/// Sends message over BLE
/// """
///
- /// def read(self, buf: bytearray, offset: int = 0) -> int:
+ /// def read(self, buf: AnyBuffer, offset: int = 0) -> int:
/// """
/// Reads message using BLE (device).
/// """
@@ -297,7 +297,7 @@ pub static mp_module_trezorble: Module = obj_module! {
/// """
Qstr::MP_QSTR_erase_bonds => obj_fn_0!(py_erase_bonds).as_obj(),
- /// def unpair(addr: bytes | None):
+ /// def unpair(addr: AnyBytes | None):
/// """
/// Erases the bond for the given address or for current connection if addr is None.
/// Raises exception if BLE driver reports an error.
diff --git a/core/embed/rust/src/ui/api/firmware_micropython.rs b/core/embed/rust/src/ui/api/firmware_micropython.rs
index 86679415..0e128c01 100644
--- a/core/embed/rust/src/ui/api/firmware_micropython.rs
+++ b/core/embed/rust/src/ui/api/firmware_micropython.rs
@@ -1315,9 +1315,9 @@ pub extern "C" fn upy_backlight_fade(_level: Obj) -> Obj {
#[no_mangle]
pub static mp_module_trezorui_api: Module = obj_module! {
/// from trezor import utils
- /// from trezor.enums import ButtonRequestType
+ /// from trezor.enums import ButtonRequestType, RecoveryType
///
- /// PropertyType = tuple[str | None, str | bytes | None, bool | None]
+ /// PropertyType = tuple[str | None, StrOrBytes | None, bool | None]
/// T = TypeVar("T")
///
/// class LayoutObj(Generic[T]):
@@ -1423,7 +1423,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// INFO: UiResult
Qstr::MP_QSTR_INFO => INFO.as_obj(),
- /// def check_homescreen_format(data: bytes) -> bool:
+ /// def check_homescreen_format(data: AnyBytes) -> bool:
/// """Check homescreen format and dimensions."""
Qstr::MP_QSTR_check_homescreen_format => obj_fn_1!(upy_check_homescreen_format).as_obj(),
@@ -1464,7 +1464,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// def confirm_address(
/// *,
/// title: str,
- /// address: str | bytes,
+ /// address: StrOrBytes,
/// address_label: str | None = None,
/// verb: str | None = None,
/// info_button: bool = False,
@@ -1488,7 +1488,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// def confirm_value(
/// *,
/// title: str,
- /// value: str | bytes,
+ /// value: StrOrBytes,
/// description: str | None,
/// is_data: bool = True,
/// extra: str | None = None,
@@ -1514,7 +1514,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// def confirm_value_intro(
/// *,
/// title: str,
- /// value: str | bytes,
+ /// value: StrOrBytes,
/// subtitle: str | None = None,
/// verb: str | None = None,
/// verb_cancel: str | None = None,
@@ -1550,7 +1550,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// title: str,
/// app_name: str,
/// icon_name: str | None,
- /// accounts: list[str | None],
+ /// accounts: Sequence[str | None],
/// ) -> LayoutObj[int | UiResult]:
/// """FIDO confirmation.
///
@@ -1569,7 +1569,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// def confirm_homescreen(
/// *,
/// title: str,
- /// image: bytes,
+ /// image: AnyBytes,
/// ) -> LayoutObj[UiResult]:
/// """Confirm homescreen."""
Qstr::MP_QSTR_confirm_homescreen => obj_fn_kw!(0, new_confirm_homescreen).as_obj(),
@@ -1600,7 +1600,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// button: str,
/// button_style_confirm: bool = False,
/// hold: bool = False,
- /// items: Iterable[tuple[str | bytes, bool]],
+ /// items: Iterable[tuple[StrOrBytes, bool]],
/// ) -> LayoutObj[UiResult]:
/// """Confirm long content with the possibility to go back from any page.
/// Meant to be used with confirm_with_info on UI Bolt and Caesar."""
@@ -1610,7 +1610,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// *,
/// title: str,
/// subtitle: str | None = None,
- /// items: list[PropertyType],
+ /// items: Sequence[PropertyType],
/// hold: bool = False,
/// verb: str | None = None,
/// external_menu: bool = False,
@@ -1630,9 +1630,9 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// fee: str,
/// fee_label: str,
/// title: str | None = None,
- /// account_items: list[PropertyType] | None = None,
+ /// account_items: Sequence[PropertyType] | None = None,
/// account_title: str | None = None,
- /// extra_items: list[PropertyType] | None = None,
+ /// extra_items: Sequence[PropertyType] | None = None,
/// extra_title: str | None = None,
/// verb_cancel: str | None = None,
/// back_button: bool = False,
@@ -1645,7 +1645,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// *,
/// title: str,
/// subtitle: str | None = None,
- /// items: Iterable[tuple[str | bytes, bool]],
+ /// items: Iterable[tuple[StrOrBytes, bool]],
/// verb: str,
/// verb_info: str,
/// verb_cancel: str | None = None,
@@ -1685,8 +1685,8 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// br_name: str,
/// address_item: PropertyType | None,
/// extra_item: PropertyType | None,
- /// summary_items: list[PropertyType] | None = None,
- /// fee_items: list[PropertyType] | None = None,
+ /// summary_items: Sequence[PropertyType] | None = None,
+ /// fee_items: Sequence[PropertyType] | None = None,
/// summary_title: str | None = None,
/// summary_br_code: ButtonRequestType | None = None,
/// summary_br_name: str | None = None,
@@ -1716,7 +1716,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// case_sensitive: bool,
/// account: str | None,
/// path: str | None,
- /// xpubs: list[tuple[str, str]],
+ /// xpubs: Sequence[tuple[str, str]],
/// br_code: ButtonRequestType,
/// br_name: str,
/// ) -> LayoutObj[UiResult]:
@@ -1745,7 +1745,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// *,
/// title: str,
/// verb: str,
- /// items: list[str],
+ /// items: Sequence[str],
/// ) -> LayoutObj[UiResult]:
/// """Show multiple texts, each on its own page. TR specific."""
Qstr::MP_QSTR_multiple_pages_texts => obj_fn_kw!(0, new_multiple_pages_texts).as_obj(),
@@ -1848,7 +1848,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// def select_word_count(
/// *,
/// recovery_type: RecoveryType,
- /// ) -> LayoutObj[int | str | UIResult]: # TR returns str
+ /// ) -> LayoutObj[int | str | UiResult]: # TR returns str
/// """Select a mnemonic word count from the options: 12, 18, 20, 24, or 33.
/// For unlocking a repeated backup, select between 20 and 33."""
Qstr::MP_QSTR_select_word_count => obj_fn_kw!(0, new_select_word_count).as_obj(),
@@ -1865,7 +1865,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// details_title: str,
/// account: str | None,
/// path: str | None,
- /// xpubs: list[tuple[str, str]],
+ /// xpubs: Sequence[tuple[str, str]],
/// ) -> LayoutObj[UiResult]:
/// """Show address details - QR code, account, path, cosigner xpubs."""
Qstr::MP_QSTR_show_address_details => obj_fn_kw!(0, new_show_address_details).as_obj(),
@@ -1936,7 +1936,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// brightness: str | None,
/// haptics_enabled: bool | None,
/// led_enabled: bool | None,
- /// about_items: list[tuple[str | None, str | bytes | None, bool | None]],
+ /// about_items: Sequence[tuple[str | None, StrOrBytes | None, bool | None]],
/// ) -> LayoutObj[UiResult | DeviceMenuResult | tuple[DeviceMenuResult, int]]:
/// """Show the device menu."""
Qstr::MP_QSTR_show_device_menu => obj_fn_kw!(0, new_show_device_menu).as_obj(),
@@ -1991,7 +1991,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// def show_info_with_cancel(
/// *,
/// title: str,
- /// items: list[PropertyType],
+ /// items: Sequence[PropertyType],
/// horizontal: bool = False,
/// chunkify: bool = False,
/// ) -> LayoutObj[UiResult]:
@@ -2038,7 +2038,7 @@ pub static mp_module_trezorui_api: Module = obj_module! {
/// def show_properties(
/// *,
/// title: str,
- /// value: list[PropertyType] | str,
+ /// value: Sequence[PropertyType] | str,
/// ) -> LayoutObj[None]:
/// """Show a list of key-value pairs, or a monospace string."""
Qstr::MP_QSTR_show_properties => obj_fn_kw!(0, new_show_properties).as_obj(),
diff --git a/core/embed/upymod/modtrezorconfig/modtrezorconfig.c b/core/embed/upymod/modtrezorconfig/modtrezorconfig.c
index 6f6b8ce6..cea36e87 100644
--- a/core/embed/upymod/modtrezorconfig/modtrezorconfig.c
+++ b/core/embed/upymod/modtrezorconfig/modtrezorconfig.c
@@ -67,7 +67,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: bytes | None) -> bool:
+/// def unlock(pin: str, ext_salt: AnyBytes | None) -> bool:
/// """
/// Attempts to unlock the storage with the given PIN and external salt.
/// Returns True on success, False on failure.
@@ -93,7 +93,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: bytes | None) -> bool:
+/// def check_pin(pin: str, ext_salt: AnyBytes | None) -> bool:
/// """
/// Check the given PIN with the given external salt.
/// Returns True on success, False on failure.
@@ -154,8 +154,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorconfig_get_pin_rem_obj,
/// def change_pin(
/// oldpin: str,
/// newpin: str,
-/// old_ext_salt: bytes | None,
-/// new_ext_salt: bytes | None,
+/// old_ext_salt: AnyBytes | None,
+/// new_ext_salt: AnyBytes | None,
/// ) -> bool:
/// """
/// Change PIN and external salt. Returns True on success, False on failure.
@@ -223,7 +223,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorconfig_has_wipe_code_obj,
/// def change_wipe_code(
/// pin: str,
-/// ext_salt: bytes | None,
+/// ext_salt: AnyBytes | None,
/// wipe_code: str,
/// ) -> bool:
/// """
@@ -292,7 +292,7 @@ STATIC mp_obj_t mod_trezorconfig_get(size_t n_args, const mp_obj_t *args) {
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorconfig_get_obj, 2, 3,
mod_trezorconfig_get);
-/// def set(app: int, key: int, value: bytes, public: bool = False) -> None:
+/// def set(app: int, key: int, value: AnyBytes, public: bool = False) -> None:
/// """
/// Sets a value of given key for given app.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-aes.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-aes.h
index 6fc47fdf..aac688e0 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-aes.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-aes.h
@@ -52,8 +52,8 @@ typedef struct _mp_obj_AES_t {
/// def __init__(
/// self,
/// mode: int,
-/// key: bytes,
-/// iv: bytes | None = None,
+/// key: AnyBytes,
+/// iv: AnyBytes | None = None,
/// ) -> None:
/// """
/// Initialize AES context.
@@ -161,7 +161,7 @@ static mp_obj_t aes_update(mp_obj_t self, mp_obj_t data, bool encrypt) {
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
-/// def encrypt(self, data: bytes) -> bytes:
+/// def encrypt(self, data: AnyBytes) -> bytes:
/// """
/// Encrypt data and update AES context.
/// """
@@ -171,7 +171,7 @@ STATIC mp_obj_t mod_trezorcrypto_AES_encrypt(mp_obj_t self, mp_obj_t data) {
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_AES_encrypt_obj,
mod_trezorcrypto_AES_encrypt);
-/// def decrypt(self, data: bytes) -> bytes:
+/// def decrypt(self, data: AnyBytes) -> bytes:
/// """
/// Decrypt data and update AES context.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-aesgcm.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-aesgcm.h
index b8a9296c..9f9eb7ae 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-aesgcm.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-aesgcm.h
@@ -40,7 +40,7 @@ typedef struct _mp_obj_AesGcm_t {
} state;
} mp_obj_AesGcm_t;
-/// def __init__(self, key: bytes, iv: bytes) -> None:
+/// def __init__(self, key: AnyBytes, iv: AnyBytes) -> None:
/// """
/// Initialize the AES-GCM context for encryption or decryption.
/// """
@@ -67,7 +67,7 @@ STATIC mp_obj_t mod_trezorcrypto_AesGcm_make_new(const mp_obj_type_t *type,
return MP_OBJ_FROM_PTR(o);
}
-/// def reset(self, iv: bytes) -> None:
+/// def reset(self, iv: AnyBytes) -> None:
/// """
/// Reset the IV for encryption or decryption.
/// """
@@ -85,7 +85,7 @@ STATIC mp_obj_t mod_trezorcrypto_AesGcm_reset(mp_obj_t self, mp_obj_t iv) {
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_AesGcm_reset_obj,
mod_trezorcrypto_AesGcm_reset);
-/// def encrypt(self, data: bytes) -> bytes:
+/// def encrypt(self, data: AnyBytes) -> bytes:
/// """
/// Encrypt data chunk.
/// """
@@ -110,7 +110,7 @@ STATIC mp_obj_t mod_trezorcrypto_AesGcm_encrypt(mp_obj_t self, mp_obj_t data) {
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_AesGcm_encrypt_obj,
mod_trezorcrypto_AesGcm_encrypt);
-/// def encrypt_in_place(self, data: bytearray | memoryview) -> int:
+/// def encrypt_in_place(self, data: AnyBuffer) -> int:
/// """
/// Encrypt data chunk in place. Returns the length of the encrypted data.
/// """
@@ -132,7 +132,7 @@ STATIC mp_obj_t mod_trezorcrypto_AesGcm_encrypt_in_place(mp_obj_t self,
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_AesGcm_encrypt_in_place_obj,
mod_trezorcrypto_AesGcm_encrypt_in_place);
-/// def decrypt(self, data: bytes) -> bytes:
+/// def decrypt(self, data: AnyBytes) -> bytes:
/// """
/// Decrypt data chunk.
/// """
@@ -157,7 +157,7 @@ STATIC mp_obj_t mod_trezorcrypto_AesGcm_decrypt(mp_obj_t self, mp_obj_t data) {
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_AesGcm_decrypt_obj,
mod_trezorcrypto_AesGcm_decrypt);
-/// def decrypt_in_place(self, data: bytearray | memoryview) -> int:
+/// def decrypt_in_place(self, data: AnyBuffer) -> int:
/// """
/// Decrypt data chunk in place. Returns the length of the decrypted data.
/// """
@@ -179,7 +179,7 @@ STATIC mp_obj_t mod_trezorcrypto_AesGcm_decrypt_in_place(mp_obj_t self,
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_AesGcm_decrypt_in_place_obj,
mod_trezorcrypto_AesGcm_decrypt_in_place);
-/// def auth(self, data: bytes) -> None:
+/// def auth(self, data: AnyBytes) -> None:
/// """
/// Include authenticated data chunk in the GCM authentication tag. This can
/// be called repeatedly to add authenticated data at any point before
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-bip32.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-bip32.h
index 7c891723..d8008192 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-bip32.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-bip32.h
@@ -42,9 +42,9 @@
/// depth: int,
/// fingerprint: int,
/// child_num: int,
-/// chain_code: bytes,
-/// private_key: bytes | None = None,
-/// public_key: bytes | None = None,
+/// chain_code: AnyBytes,
+/// private_key: AnyBytes | None = None,
+/// public_key: AnyBytes | None = None,
/// curve_name: str | None = None,
/// ) -> None:
/// """
@@ -386,7 +386,11 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_HDNode_nem_address_obj,
mod_trezorcrypto_HDNode_nem_address);
/// def nem_encrypt(
-/// self, transfer_public_key: bytes, iv: bytes, salt: bytes, payload: bytes
+/// self,
+/// transfer_public_key: AnyBytes,
+/// iv: AnyBytes,
+/// salt: AnyBytes,
+/// payload: AnyBytes,
/// ) -> bytes:
/// """
/// Encrypts payload using the transfer's public key
@@ -514,7 +518,7 @@ const mp_obj_type_t mod_trezorcrypto_HDNode_type = {
/// mock:global
-/// def from_seed(seed: bytes, curve_name: str) -> HDNode:
+/// def from_seed(seed: AnyBytes, curve_name: str) -> HDNode:
/// """
/// Construct a BIP0032 HD node from a BIP0039 seed value.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-bip340.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-bip340.h
index 9d5b9ca1..7c157b84 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-bip340.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-bip340.h
@@ -57,7 +57,7 @@ STATIC mp_obj_t mod_trezorcrypto_bip340_generate_secret() {
STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorcrypto_bip340_generate_secret_obj,
mod_trezorcrypto_bip340_generate_secret);
-/// def publickey(secret_key: bytes) -> bytes:
+/// def publickey(secret_key: AnyBytes) -> bytes:
/// """
/// Computes public key from secret key.
/// """
@@ -82,8 +82,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_bip340_publickey_obj,
mod_trezorcrypto_bip340_publickey);
/// def sign(
-/// secret_key: bytes,
-/// digest: bytes,
+/// secret_key: AnyBytes,
+/// digest: AnyBytes,
/// ) -> bytes:
/// """
/// Uses secret key to produce the signature of the digest.
@@ -115,7 +115,7 @@ STATIC mp_obj_t mod_trezorcrypto_bip340_sign(mp_obj_t secret_key,
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_bip340_sign_obj,
mod_trezorcrypto_bip340_sign);
-/// def verify_publickey(public_key: bytes) -> bool:
+/// def verify_publickey(public_key: AnyBytes) -> bool:
/// """
/// Verifies whether the public key is valid.
/// Returns True on success.
@@ -132,7 +132,9 @@ STATIC mp_obj_t mod_trezorcrypto_bip340_verify_publickey(mp_obj_t public_key) {
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_bip340_verify_publickey_obj,
mod_trezorcrypto_bip340_verify_publickey);
-/// def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool:
+/// def verify(
+/// public_key: AnyBytes, signature: AnyBytes, digest: AnyBytes
+/// ) -> bool:
/// """
/// Uses public key to verify the signature of the digest.
/// Returns True on success.
@@ -162,8 +164,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(mod_trezorcrypto_bip340_verify_obj,
mod_trezorcrypto_bip340_verify);
/// def tweak_public_key(
-/// public_key: bytes,
-/// root_hash: bytes | None = None,
+/// public_key: AnyBytes,
+/// root_hash: AnyBytes | None = None,
/// ) -> bytes:
/// """
/// Tweaks the public key with the specified root_hash.
@@ -202,8 +204,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_bip340_tweak_public_key);
/// def tweak_secret_key(
-/// secret_key: bytes,
-/// root_hash: bytes | None = None,
+/// secret_key: AnyBytes,
+/// root_hash: AnyBytes | None = None,
/// ) -> bytes:
/// """
/// Tweaks the secret key with the specified root_hash.
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-bip39.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-bip39.h
index 1ab64324..43754f7f 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-bip39.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-bip39.h
@@ -25,7 +25,7 @@
/// package: trezorcrypto.bip39
-/// def from_data(data: bytes) -> str:
+/// def from_data(data: AnyBytes) -> str:
/// """
/// Generate a mnemonic from given data (of 16, 20, 24, 28 and 32 bytes).
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-blake256.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-blake256.h
index 95d91619..bd46342d 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-blake256.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-blake256.h
@@ -37,7 +37,7 @@ typedef struct _mp_obj_Blake256_t {
STATIC mp_obj_t mod_trezorcrypto_Blake256_update(mp_obj_t self, mp_obj_t data);
-/// def __init__(self, __data: AnyStr | None = None) -> None:
+/// def __init__(self, __data: StrOrBytes | None = None) -> None:
/// """
/// Creates a hash context object.
/// """
@@ -55,7 +55,7 @@ STATIC mp_obj_t mod_trezorcrypto_Blake256_make_new(const mp_obj_type_t *type,
return MP_OBJ_FROM_PTR(o);
}
-/// def update(self, __data: AnyStr) -> None:
+/// def update(self, __data: StrOrBytes) -> None:
/// """
/// Update the hash context with hashed data.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-blake2b.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-blake2b.h
index cdfd0793..a5e89002 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-blake2b.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-blake2b.h
@@ -41,10 +41,10 @@ STATIC mp_obj_t mod_trezorcrypto_Blake2b_update(mp_obj_t self, mp_obj_t data);
/// def __init__(
/// self,
-/// data: bytes | None = None,
+/// data: AnyBytes | None = None,
/// outlen: int = blake2b.digest_size,
-/// key: bytes | None = None,
-/// personal: bytes | None = None,
+/// key: AnyBytes | None = None,
+/// personal: AnyBytes | None = None,
/// ) -> None:
/// """
/// Creates a hash context object.
@@ -109,7 +109,7 @@ STATIC mp_obj_t mod_trezorcrypto_Blake2b_make_new(const mp_obj_type_t *type,
return MP_OBJ_FROM_PTR(o);
}
-/// def update(self, __data: AnyStr) -> None:
+/// def update(self, __data: StrOrBytes) -> None:
/// """
/// Update the hash context with hashed data.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-blake2s.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-blake2s.h
index 3eeae904..5f0dedb9 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-blake2s.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-blake2s.h
@@ -41,10 +41,10 @@ STATIC mp_obj_t mod_trezorcrypto_Blake2s_update(mp_obj_t self, mp_obj_t data);
/// def __init__(
/// self,
-/// data: bytes | None = None,
+/// data: AnyBytes | None = None,
/// outlen: int = blake2s.digest_size,
-/// key: bytes | None = None,
-/// personal: bytes | None = None,
+/// key: AnyBytes | None = None,
+/// personal: AnyBytes | None = None,
/// ) -> None:
/// """
/// Creates a hash context object.
@@ -109,7 +109,7 @@ STATIC mp_obj_t mod_trezorcrypto_Blake2s_make_new(const mp_obj_type_t *type,
return MP_OBJ_FROM_PTR(o);
}
-/// def update(self, __data: AnyStr) -> None:
+/// def update(self, __data: StrOrBytes) -> None:
/// """
/// Update the hash context with hashed data.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-cardano.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-cardano.h
index 88097360..5a7cda2b 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-cardano.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-cardano.h
@@ -98,7 +98,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_cardano_derive_icarus_obj, 3, 4,
mod_trezorcrypto_cardano_derive_icarus);
-/// def from_secret(secret: bytes) -> HDNode:
+/// def from_secret(secret: AnyBytes) -> HDNode:
/// """
/// Creates a Cardano HD node from a master secret.
/// """
@@ -125,7 +125,7 @@ STATIC mp_obj_t mod_trezorcrypto_from_secret(mp_obj_t secret) {
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_from_secret_obj,
mod_trezorcrypto_from_secret);
-/// def from_seed_slip23(seed: bytes) -> HDNode:
+/// def from_seed_slip23(seed: AnyBytes) -> HDNode:
/// """
/// Creates a Cardano HD node from a seed via SLIP-23 derivation.
/// """
@@ -162,7 +162,7 @@ STATIC mp_obj_t mod_trezorcrypto_from_seed_slip23(mp_obj_t seed) {
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_from_seed_slip23_obj,
mod_trezorcrypto_from_seed_slip23);
-/// def from_seed_ledger(seed: bytes) -> HDNode:
+/// def from_seed_ledger(seed: AnyBytes) -> HDNode:
/// """
/// Creates a Cardano HD node from a seed via Ledger derivation.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-chacha20poly1305.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-chacha20poly1305.h
index 5a9b97c6..090accd8 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-chacha20poly1305.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-chacha20poly1305.h
@@ -34,7 +34,7 @@ typedef struct _mp_obj_ChaCha20Poly1305_t {
int64_t alen, plen;
} mp_obj_ChaCha20Poly1305_t;
-/// def __init__(self, key: bytes, nonce: bytes) -> None:
+/// def __init__(self, key: AnyBytes, nonce: AnyBytes) -> None:
/// """
/// Initialize the ChaCha20 + Poly1305 context for encryption or decryption
/// using a 32 byte key and 12 byte nonce as in the RFC 7539 style.
@@ -61,7 +61,7 @@ STATIC mp_obj_t mod_trezorcrypto_ChaCha20Poly1305_make_new(
return MP_OBJ_FROM_PTR(o);
}
-/// def encrypt(self, data: bytes) -> bytes:
+/// def encrypt(self, data: AnyBytes) -> bytes:
/// """
/// Encrypt data (length of data must be divisible by 64 except for the
/// final value).
@@ -80,7 +80,7 @@ STATIC mp_obj_t mod_trezorcrypto_ChaCha20Poly1305_encrypt(mp_obj_t self,
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_ChaCha20Poly1305_encrypt_obj,
mod_trezorcrypto_ChaCha20Poly1305_encrypt);
-/// def decrypt(self, data: bytes) -> bytes:
+/// def decrypt(self, data: AnyBytes) -> bytes:
/// """
/// Decrypt data (length of data must be divisible by 64 except for the
/// final value).
@@ -99,7 +99,7 @@ STATIC mp_obj_t mod_trezorcrypto_ChaCha20Poly1305_decrypt(mp_obj_t self,
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_ChaCha20Poly1305_decrypt_obj,
mod_trezorcrypto_ChaCha20Poly1305_decrypt);
-/// def auth(self, data: bytes) -> None:
+/// def auth(self, data: AnyBytes) -> None:
/// """
/// Include authenticated data in the Poly1305 MAC using the RFC 7539
/// style with 16 byte padding. This must only be called once and prior
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-crc.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-crc.h
index 467aef7a..5e4837e5 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-crc.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-crc.h
@@ -25,7 +25,7 @@
/// package: trezorcrypto.crc
-/// def crc32(data: bytes, crc: int = 0) -> int:
+/// def crc32(data: AnyBytes, crc: int = 0) -> int:
/// """
/// Computes a CRC32 checksum of `data`.
///
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-curve25519.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-curve25519.h
index d10d91c4..32199470 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-curve25519.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-curve25519.h
@@ -43,7 +43,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(
mod_trezorcrypto_curve25519_generate_secret_obj,
mod_trezorcrypto_curve25519_generate_secret);
-/// def publickey(secret_key: bytes) -> bytes:
+/// def publickey(secret_key: AnyBytes) -> bytes:
/// """
/// Computes public key from secret key.
/// """
@@ -61,7 +61,7 @@ STATIC mp_obj_t mod_trezorcrypto_curve25519_publickey(mp_obj_t secret_key) {
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_curve25519_publickey_obj,
mod_trezorcrypto_curve25519_publickey);
-/// def multiply(secret_key: bytes, public_key: bytes) -> bytes:
+/// def multiply(secret_key: AnyBytes, public_key: AnyBytes) -> bytes:
/// """
/// Multiplies point defined by public_key with scalar defined by
/// secret_key. Useful for ECDH.
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-ed25519.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-ed25519.h
index 81da8831..5e36360d 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-ed25519.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-ed25519.h
@@ -39,7 +39,7 @@ STATIC mp_obj_t mod_trezorcrypto_ed25519_generate_secret() {
STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorcrypto_ed25519_generate_secret_obj,
mod_trezorcrypto_ed25519_generate_secret);
-/// def publickey(secret_key: bytes) -> bytes:
+/// def publickey(secret_key: AnyBytes) -> bytes:
/// """
/// Computes public key from secret key.
/// """
@@ -58,7 +58,9 @@ STATIC mp_obj_t mod_trezorcrypto_ed25519_publickey(mp_obj_t secret_key) {
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_ed25519_publickey_obj,
mod_trezorcrypto_ed25519_publickey);
-/// def sign(secret_key: bytes, message: bytes, hasher: str = "") -> bytes:
+/// def sign(
+/// secret_key: AnyBytes, message: AnyBytes, hasher: str = ""
+/// ) -> bytes:
/// """
/// Uses secret key to produce the signature of message.
/// """
@@ -100,7 +102,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorcrypto_ed25519_sign_obj, 2,
#if !BITCOIN_ONLY
/// def sign_ext(
-/// secret_scalar: bytes, secret_extension: bytes, message: bytes
+/// secret_scalar: AnyBytes, secret_extension: AnyBytes, message: AnyBytes
/// ) -> bytes:
/// """
/// Uses extended secret key to produce the cardano signature of message.
@@ -134,7 +136,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(mod_trezorcrypto_ed25519_sign_ext_obj,
#endif
-/// def verify(public_key: bytes, signature: bytes, message: bytes) -> bool:
+/// def verify(
+/// public_key: AnyBytes, signature: AnyBytes, message: AnyBytes
+/// ) -> bool:
/// """
/// Uses public key to verify the signature of the message.
/// Returns True on success.
@@ -164,7 +168,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: Sequence[AnyBytes]) -> bytes:
/// """
/// Combines a list of public keys used in COSI cosigning scheme.
/// """
@@ -200,7 +204,9 @@ 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: AnyBytes, signatures: Sequence[AnyBytes]
+/// ) -> bytes:
/// """
/// Combines a list of signatures used in COSI cosigning scheme.
/// """
@@ -259,11 +265,11 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorcrypto_ed25519_cosi_commit_obj,
mod_trezorcrypto_ed25519_cosi_commit);
/// def cosi_sign(
-/// secret_key: bytes,
-/// message: bytes,
-/// nonce: bytes,
-/// sigR: bytes,
-/// combined_pubkey: bytes,
+/// secret_key: AnyBytes,
+/// message: AnyBytes,
+/// nonce: AnyBytes,
+/// sigR: AnyBytes,
+/// combined_pubkey: AnyBytes,
/// ) -> bytes:
/// """
/// Produce signature of message using COSI cosigning scheme.
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-elligator2.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-elligator2.h
index 9a355ab9..60abe666 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-elligator2.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-elligator2.h
@@ -25,7 +25,7 @@
/// package: trezorcrypto.elligator2
-/// def map_to_curve25519(input: bytes) -> bytes:
+/// def map_to_curve25519(input: AnyBytes) -> bytes:
/// """
/// Maps a 32-byte input to a curve25519 point.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-groestl.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-groestl.h
index 089bc46b..0e2e4f80 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-groestl.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-groestl.h
@@ -41,7 +41,7 @@ typedef struct _mp_obj_Groestl512_t {
STATIC mp_obj_t mod_trezorcrypto_Groestl512_update(mp_obj_t self,
mp_obj_t data);
-/// def __init__(self, __data: AnyStr | None = None) -> None:
+/// def __init__(self, __data: StrOrBytes | None = None) -> None:
/// """
/// Creates a hash context object.
/// """
@@ -58,7 +58,7 @@ STATIC mp_obj_t mod_trezorcrypto_Groestl512_make_new(const mp_obj_type_t *type,
return MP_OBJ_FROM_PTR(o);
}
-/// def update(self, __data: AnyStr) -> None:
+/// def update(self, __data: StrOrBytes) -> None:
/// """
/// Update the hash context with hashed data.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-hmac.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-hmac.h
index 2bc6ad50..3e819d8f 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-hmac.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-hmac.h
@@ -47,8 +47,8 @@ STATIC mp_obj_t mod_trezorcrypto_Hmac_update(mp_obj_t self, mp_obj_t data);
/// def __init__(
/// self,
/// hashtype: int,
-/// key: bytes,
-/// message: bytes | None = None,
+/// key: AnyBytes,
+/// message: AnyBytes | None = None,
/// ) -> None:
/// """
/// Create a HMAC context.
@@ -83,7 +83,7 @@ STATIC mp_obj_t mod_trezorcrypto_Hmac_make_new(const mp_obj_type_t *type,
return MP_OBJ_FROM_PTR(o);
}
-/// def update(self, message: bytes) -> None:
+/// def update(self, message: AnyBytes) -> None:
/// """
/// Update a HMAC context.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-monero.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-monero.h
index c89573a0..f9513c1f 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-monero.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-monero.h
@@ -223,12 +223,12 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(
/// XMR hasher
/// """
-/// def __init__(self, x: bytes | None = None):
+/// def __init__(self, x: AnyBytes | None = None):
/// """
/// Constructor
/// """
-/// def update(self, buffer: bytes) -> None:
+/// def update(self, buffer: AnyBytes) -> None:
/// """
/// Update hasher
/// """
@@ -466,7 +466,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_monero_sc_inv_into_obj,
mod_trezorcrypto_monero_sc_inv_into);
/// def encodeint_into(
-/// r: bytes | None, a: Scalar, offset: int | None = 0
+/// r: AnyBytes | None, a: Scalar, offset: int | None = 0
/// ) -> bytes:
/// """
/// Scalar compression
@@ -497,7 +497,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_encodeint_into);
/// def decodeint_into(
-/// r: Scalar | None, a: bytes, offset: int = 0
+/// r: Scalar | None, a: AnyBytes, offset: int = 0
/// ) -> Scalar:
/// """
/// Scalar decompression
@@ -515,7 +515,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_decodeint_into);
/// def decodeint_into_noreduce(
-/// r: Scalar | None, a: bytes, offset: int = 0
+/// r: Scalar | None, a: AnyBytes, offset: int = 0
/// ) -> Scalar:
/// """
/// Scalar decompression, raw, without modular reduction
@@ -725,7 +725,9 @@ STATIC mp_obj_t mod_trezorcrypto_monero_scalarmult_into(const mp_obj_t dest,
STATIC MP_DEFINE_CONST_FUN_OBJ_3(mod_trezorcrypto_monero_scalarmult_into_obj,
mod_trezorcrypto_monero_scalarmult_into);
-/// def encodepoint_into(r: bytes | None, p: Point, offset: int = 0) -> bytes:
+/// def encodepoint_into(
+/// r: AnyBytes | None, p: Point, offset: int = 0
+/// ) -> bytes:
/// """
/// Point compression
/// """
@@ -755,7 +757,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_encodepoint_into);
/// def decodepoint_into(
-/// r: Point | None, buff: bytes, offset: int = 0
+/// r: Point | None, buff: AnyBytes, offset: int = 0
/// ) -> Point:
/// """
/// Point decompression
@@ -776,7 +778,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
// XMR defs
//
-/// def xmr_base58_addr_encode_check(tag: int, buff: bytes) -> str:
+/// def xmr_base58_addr_encode_check(tag: int, buff: AnyBytes) -> str:
/// """
/// Monero block base 58 encoding
/// """
@@ -801,7 +803,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(
mod_trezorcrypto_monero_xmr_base58_addr_encode_check_obj,
mod_trezorcrypto_monero_xmr_base58_addr_encode_check);
-/// def xmr_base58_addr_decode_check(buff: bytes) -> tuple[bytes, int]:
+/// def xmr_base58_addr_decode_check(buff: AnyBytes) -> tuple[bytes, int]:
/// """
/// Monero block base 58 decoding, returning (decoded, tag) or raising on
/// error.
@@ -847,8 +849,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_monero_random_scalar);
/// def fast_hash_into(
-/// r: bytes | None,
-/// buff: bytes,
+/// r: AnyBytes | None,
+/// buff: AnyBytes,
/// length: int | None = None,
/// offset: int = 0,
/// ) -> bytes:
@@ -893,7 +895,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
/// def hash_to_point_into(
/// r: Point | None,
-/// buff: bytes,
+/// buff: AnyBytes,
/// length: int | None = None,
/// offset: int = 0,
/// ) -> Point:
@@ -923,7 +925,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
/// def hash_to_scalar_into(
/// r: Scalar | None,
-/// buff: bytes,
+/// buff: AnyBytes,
/// length: int | None = None,
/// offset: int = 0,
/// ) -> Scalar:
@@ -1108,7 +1110,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(
mod_trezorcrypto_monero_gen_commitment_into_obj,
mod_trezorcrypto_monero_gen_commitment_into);
-/// def ct_equals(a: bytes, b: bytes) -> bool:
+/// def ct_equals(a: AnyBytes, b: AnyBytes) -> bool:
/// """
/// Constant time buffer comparison
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-nem.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-nem.h
index b30efd78..5478b86f 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-nem.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-nem.h
@@ -40,7 +40,7 @@ STATIC mp_obj_t mod_trezorcrypto_nem_validate_address(mp_obj_t address,
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_nem_validate_address_obj,
mod_trezorcrypto_nem_validate_address);
-/// def compute_address(public_key: bytes, network: int) -> str:
+/// def compute_address(public_key: AnyBytes, network: int) -> str:
/// """
/// Compute a NEM address from a public key
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-nist256p1.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
index cf132525..133ff792 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
@@ -55,7 +55,7 @@ STATIC mp_obj_t mod_trezorcrypto_nist256p1_generate_secret() {
STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorcrypto_nist256p1_generate_secret_obj,
mod_trezorcrypto_nist256p1_generate_secret);
-/// def publickey(secret_key: bytes, compressed: bool = True) -> bytes:
+/// def publickey(secret_key: AnyBytes, compressed: bool = True) -> bytes:
/// """
/// Computes public key from secret key.
/// """
@@ -88,7 +88,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
mod_trezorcrypto_nist256p1_publickey);
/// def sign(
-/// secret_key: bytes, digest: bytes, compressed: bool = True
+/// secret_key: AnyBytes, digest: AnyBytes, compressed: bool = True
/// ) -> bytes:
/// """
/// Uses secret key to produce the signature of the digest.
@@ -122,7 +122,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorcrypto_nist256p1_sign_obj,
2, 3,
mod_trezorcrypto_nist256p1_sign);
-/// def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool:
+/// def verify(
+/// public_key: AnyBytes, signature: AnyBytes, digest: AnyBytes
+/// ) -> bool:
/// """
/// Uses public key to verify the signature of the digest.
/// Returns True on success.
@@ -152,7 +154,7 @@ STATIC mp_obj_t mod_trezorcrypto_nist256p1_verify(mp_obj_t public_key,
STATIC MP_DEFINE_CONST_FUN_OBJ_3(mod_trezorcrypto_nist256p1_verify_obj,
mod_trezorcrypto_nist256p1_verify);
-/// def verify_recover(signature: bytes, digest: bytes) -> bytes:
+/// def verify_recover(signature: AnyBytes, digest: AnyBytes) -> bytes:
/// """
/// Uses signature of the digest to verify the digest and recover the public
/// key. Returns public key on success, None if the signature is invalid.
@@ -191,7 +193,7 @@ STATIC mp_obj_t mod_trezorcrypto_nist256p1_verify_recover(mp_obj_t signature,
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_nist256p1_verify_recover_obj,
mod_trezorcrypto_nist256p1_verify_recover);
-/// def multiply(secret_key: bytes, public_key: bytes) -> bytes:
+/// def multiply(secret_key: AnyBytes, public_key: AnyBytes) -> bytes:
/// """
/// Multiplies point defined by public_key with scalar defined by
/// secret_key. Useful for ECDH.
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-optiga.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-optiga.h
index 6058b65b..f7462b11 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-optiga.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-optiga.h
@@ -68,7 +68,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_optiga_get_certificate_obj,
/// def sign(
/// key_index: int,
-/// digest: bytes,
+/// digest: AnyBytes,
/// ) -> bytes:
/// """
/// Uses the private key at key_index to produce a DER-encoded signature of
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-pbkdf2.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-pbkdf2.h
index 09150ffe..cf2880d4 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-pbkdf2.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-pbkdf2.h
@@ -47,8 +47,8 @@ STATIC mp_obj_t mod_trezorcrypto_Pbkdf2_update(mp_obj_t self, mp_obj_t data);
/// def __init__(
/// self,
/// prf: int,
-/// password: bytes,
-/// salt: bytes,
+/// password: AnyBytes,
+/// salt: AnyBytes,
/// iterations: int | None = None,
/// blocknr: int = 1,
/// ) -> None:
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-ripemd160.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-ripemd160.h
index 6a05382d..cc889719 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-ripemd160.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-ripemd160.h
@@ -37,7 +37,7 @@ typedef struct _mp_obj_Ripemd160_t {
STATIC mp_obj_t mod_trezorcrypto_Ripemd160_update(mp_obj_t self, mp_obj_t data);
-/// def __init__(self, __data: AnyStr | None = None) -> None:
+/// def __init__(self, __data: StrOrBytes | None = None) -> None:
/// """
/// Creates a hash context object.
/// """
@@ -55,7 +55,7 @@ STATIC mp_obj_t mod_trezorcrypto_Ripemd160_make_new(const mp_obj_type_t *type,
return MP_OBJ_FROM_PTR(o);
}
-/// def update(self, __data: AnyStr) -> None:
+/// def update(self, __data: StrOrBytes) -> None:
/// """
/// Update the hash context with hashed data.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-secp256k1.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
index c1ecc843..6eeda3dc 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
@@ -55,7 +55,7 @@ STATIC mp_obj_t mod_trezorcrypto_secp256k1_generate_secret() {
STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorcrypto_secp256k1_generate_secret_obj,
mod_trezorcrypto_secp256k1_generate_secret);
-/// def publickey(secret_key: bytes, compressed: bool = True) -> bytes:
+/// def publickey(secret_key: AnyBytes, compressed: bool = True) -> bytes:
/// """
/// Computes public key from secret key.
/// """
@@ -115,8 +115,8 @@ enum {
#endif
/// def sign(
-/// secret_key: bytes,
-/// digest: bytes,
+/// secret_key: AnyBytes,
+/// digest: AnyBytes,
/// compressed: bool = True,
/// canonical: int | None = None,
/// ) -> bytes:
@@ -164,7 +164,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorcrypto_secp256k1_sign_obj,
2, 4,
mod_trezorcrypto_secp256k1_sign);
-/// def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool:
+/// def verify(
+/// public_key: AnyBytes, signature: AnyBytes, digest: AnyBytes
+/// ) -> bool:
/// """
/// Uses public key to verify the signature of the digest.
/// Returns True on success.
@@ -194,7 +196,7 @@ STATIC mp_obj_t mod_trezorcrypto_secp256k1_verify(mp_obj_t public_key,
STATIC MP_DEFINE_CONST_FUN_OBJ_3(mod_trezorcrypto_secp256k1_verify_obj,
mod_trezorcrypto_secp256k1_verify);
-/// def verify_recover(signature: bytes, digest: bytes) -> bytes:
+/// def verify_recover(signature: AnyBytes, digest: AnyBytes) -> bytes:
/// """
/// Uses signature of the digest to verify the digest and recover the public
/// key. Returns public key on success, None if the signature is invalid.
@@ -233,7 +235,7 @@ STATIC mp_obj_t mod_trezorcrypto_secp256k1_verify_recover(mp_obj_t signature,
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorcrypto_secp256k1_verify_recover_obj,
mod_trezorcrypto_secp256k1_verify_recover);
-/// def multiply(secret_key: bytes, public_key: bytes) -> bytes:
+/// def multiply(secret_key: AnyBytes, public_key: AnyBytes) -> bytes:
/// """
/// Multiplies point defined by public_key with scalar defined by
/// secret_key. Useful for ECDH.
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha1.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha1.h
index f00b1bd7..82440ca0 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha1.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha1.h
@@ -37,7 +37,7 @@ typedef struct _mp_obj_Sha1_t {
STATIC mp_obj_t mod_trezorcrypto_Sha1_update(mp_obj_t self, mp_obj_t data);
-/// def __init__(self, __data: AnyStr | None = None) -> None:
+/// def __init__(self, __data: StrOrBytes | None = None) -> None:
/// """
/// Creates a hash context object.
/// """
@@ -55,7 +55,7 @@ STATIC mp_obj_t mod_trezorcrypto_Sha1_make_new(const mp_obj_type_t *type,
return MP_OBJ_FROM_PTR(o);
}
-/// def update(self, __data: AnyStr) -> None:
+/// def update(self, __data: StrOrBytes) -> None:
/// """
/// Update the hash context with hashed data.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha256.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha256.h
index cb4282c1..a88dbcf0 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha256.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha256.h
@@ -37,7 +37,7 @@ typedef struct _mp_obj_Sha256_t {
STATIC mp_obj_t mod_trezorcrypto_Sha256_update(mp_obj_t self, mp_obj_t data);
-/// def __init__(self, __data: AnyStr | None = None) -> None:
+/// def __init__(self, __data: StrOrBytes | None = None) -> None:
/// """
/// Creates a hash context object.
/// """
@@ -55,7 +55,7 @@ STATIC mp_obj_t mod_trezorcrypto_Sha256_make_new(const mp_obj_type_t *type,
return MP_OBJ_FROM_PTR(o);
}
-/// def update(self, __data: AnyStr) -> None:
+/// def update(self, __data: StrOrBytes) -> None:
/// """
/// Update the hash context with hashed data.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha3-256.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha3-256.h
index ce9728d0..6e672c6d 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha3-256.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha3-256.h
@@ -40,7 +40,7 @@ STATIC mp_obj_t mod_trezorcrypto_Sha3_256_update(mp_obj_t self, mp_obj_t data);
/// def __init__(
/// self,
-/// data: bytes | None = None,
+/// data: AnyBytes | None = None,
/// keccak: bool = False,
/// ) -> None:
/// """
@@ -72,7 +72,7 @@ STATIC mp_obj_t mod_trezorcrypto_Sha3_256_make_new(const mp_obj_type_t *type,
return MP_OBJ_FROM_PTR(o);
}
-/// def update(self, __data: AnyStr) -> None:
+/// def update(self, __data: StrOrBytes) -> None:
/// """
/// Update the hash context with hashed data.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha3-512.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha3-512.h
index efbcadb3..b66e3682 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha3-512.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha3-512.h
@@ -40,7 +40,7 @@ STATIC mp_obj_t mod_trezorcrypto_Sha3_512_update(mp_obj_t self, mp_obj_t data);
/// def __init__(
/// self,
-/// data: bytes | None = None,
+/// data: AnyBytes | None = None,
/// keccak: bool = False,
/// ) -> None:
/// """
@@ -72,7 +72,7 @@ STATIC mp_obj_t mod_trezorcrypto_Sha3_512_make_new(const mp_obj_type_t *type,
return MP_OBJ_FROM_PTR(o);
}
-/// def update(self, __data: AnyStr) -> None:
+/// def update(self, __data: StrOrBytes) -> None:
/// """
/// Update the hash context with hashed data.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha512.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha512.h
index 547ce6fd..9c6ac8e4 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha512.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-sha512.h
@@ -37,7 +37,7 @@ typedef struct _mp_obj_Sha512_t {
STATIC mp_obj_t mod_trezorcrypto_Sha512_update(mp_obj_t self, mp_obj_t data);
-/// def __init__(self, __data: AnyStr | None = None) -> None:
+/// def __init__(self, __data: StrOrBytes | None = None) -> None:
/// """
/// Creates a hash context object.
/// """
@@ -54,7 +54,7 @@ STATIC mp_obj_t mod_trezorcrypto_Sha512_make_new(const mp_obj_type_t *type,
return MP_OBJ_FROM_PTR(o);
}
-/// def update(self, __data: AnyStr) -> None:
+/// def update(self, __data: StrOrBytes) -> None:
/// """
/// Update the hash context with hashed data.
/// """
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-shamir.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-shamir.h
index 615fe80f..023cbb62 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-shamir.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-shamir.h
@@ -27,7 +27,7 @@
/// package: trezorcrypto.shamir
-/// def interpolate(shares: list[tuple[int, bytes]], x: int) -> bytes:
+/// def interpolate(shares: Sequence[tuple[int, AnyBytes]], x: int) -> bytes:
/// """
/// Returns f(x) given the Shamir shares (x_1, f(x_1)), ... , (x_k, f(x_k)).
/// :param shares: The Shamir shares.
diff --git a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-tropic.h b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-tropic.h
index 1d158368..30875397 100644
--- a/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-tropic.h
+++ b/core/embed/upymod/modtrezorcrypto/modtrezorcrypto-tropic.h
@@ -88,7 +88,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorcrypto_tropic_key_generate_obj,
/// def sign(
/// key_index: int,
-/// digest: bytes,
+/// digest: AnyBytes,
/// ) -> bytes:
/// """
/// Uses the private key at key_index to produce a signature of the digest.
diff --git a/core/embed/upymod/modtrezorio/modtrezorio-fatfs.h b/core/embed/upymod/modtrezorio/modtrezorio-fatfs.h
index cbc3fb87..4d9c1682 100644
--- a/core/embed/upymod/modtrezorio/modtrezorio-fatfs.h
+++ b/core/embed/upymod/modtrezorio/modtrezorio-fatfs.h
@@ -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: bytes | bytearray) -> int:
+/// def write(self, data: AnyBytes) -> int:
/// """
/// Write data to the file
/// """
diff --git a/core/embed/upymod/modtrezorio/modtrezorio-sdcard.h b/core/embed/upymod/modtrezorio/modtrezorio-sdcard.h
index 9ce48003..cf089000 100644
--- a/core/embed/upymod/modtrezorio/modtrezorio-sdcard.h
+++ b/core/embed/upymod/modtrezorio/modtrezorio-sdcard.h
@@ -93,7 +93,7 @@ STATIC mp_obj_t mod_trezorio_sdcard_read(mp_obj_t block_num, mp_obj_t buf) {
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorio_sdcard_read_obj,
mod_trezorio_sdcard_read);
-/// def write(block_num: int, buf: bytes) -> None:
+/// def write(block_num: int, buf: AnyBytes) -> None:
/// """
/// Writes blocks starting with block_num from buf to the SD card.
/// Number of bytes written is length of buf rounded down to multiply of
diff --git a/core/embed/upymod/modtrezorio/modtrezorio-usb-if.h b/core/embed/upymod/modtrezorio/modtrezorio-usb-if.h
index 9e34e1ca..da3ef0a1 100644
--- a/core/embed/upymod/modtrezorio/modtrezorio-usb-if.h
+++ b/core/embed/upymod/modtrezorio/modtrezorio-usb-if.h
@@ -68,7 +68,7 @@ STATIC mp_obj_t mod_trezorio_USBIF_iface_num(mp_obj_t self) {
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_trezorio_USBIF_iface_num_obj,
mod_trezorio_USBIF_iface_num);
-/// def write(self, msg: bytes) -> int:
+/// def write(self, msg: AnyBytes) -> int:
/// """
/// Sends message using USB interface.
/// """
@@ -93,7 +93,7 @@ STATIC mp_obj_t mod_trezorio_USBIF_write(mp_obj_t self, mp_obj_t msg) {
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorio_USBIF_write_obj,
mod_trezorio_USBIF_write);
-/// def write_blocking(self, msg: bytes, timeout_ms: int) -> int:
+/// def write_blocking(self, msg: AnyBytes, timeout_ms: int) -> int:
/// """
/// Sends message using USB interface.
/// """
diff --git a/core/embed/upymod/modtrezorui/modtrezorui-display.h b/core/embed/upymod/modtrezorui/modtrezorui-display.h
index 9bd6758b..3b5b437c 100644
--- a/core/embed/upymod/modtrezorui/modtrezorui-display.h
+++ b/core/embed/upymod/modtrezorui/modtrezorui-display.h
@@ -69,7 +69,9 @@ STATIC mp_obj_t mod_trezorui_Display_orientation(size_t n_args,
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorui_Display_orientation_obj,
1, 2,
mod_trezorui_Display_orientation);
-/// def record_start(self, target_directory: bytes, refresh_index: int) -> None:
+/// def record_start(
+/// self, target_directory: AnyBytes, refresh_index: int
+/// ) -> None:
/// """
/// Starts screen recording with specified target directory and refresh
/// index.
diff --git a/core/embed/upymod/modtrezorutils/modtrezorutils.c b/core/embed/upymod/modtrezorutils/modtrezorutils.c
index 7f73f0a6..d3ef902a 100644
--- a/core/embed/upymod/modtrezorutils/modtrezorutils.c
+++ b/core/embed/upymod/modtrezorutils/modtrezorutils.c
@@ -55,7 +55,7 @@
#include <sys/stack_utils.h>
#endif
-/// def consteq(sec: bytes, pub: bytes) -> bool:
+/// def consteq(sec: AnyBytes, pub: AnyBytes) -> bool:
/// """
/// Compares the private information in `sec` with public, user-provided
/// information in `pub`. Runs in constant time, corresponding to a length
@@ -85,9 +85,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_trezorutils_consteq_obj,
mod_trezorutils_consteq);
/// def memcpy(
-/// dst: bytearray | memoryview,
+/// dst: AnyBuffer,
/// dst_ofs: int,
-/// src: bytes,
+/// src: AnyBytes,
/// src_ofs: int,
/// n: int | None = None,
/// ) -> int:
@@ -127,7 +127,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorutils_memcpy_obj, 4, 5,
mod_trezorutils_memcpy);
/// def memzero(
-/// dst: bytearray | memoryview,
+/// dst: AnyBuffer,
/// ) -> None:
/// """
/// Zeroes all bytes at `dst`.
@@ -158,7 +158,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_trezorutils_halt_obj, 0, 1,
mod_trezorutils_halt);
/// def firmware_hash(
-/// challenge: bytes | None = None,
+/// challenge: AnyBytes | None = None,
/// callback: Callable[[int, int], None] | None = None,
/// ) -> bytes:
/// """
@@ -460,7 +460,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_trezorutils_check_heap_fragmentation_obj,
/// def reboot_to_bootloader(
/// boot_command : int = 0,
-/// boot_args : bytes | None = None,
+/// boot_args : AnyBytes | None = None,
/// ) -> None:
/// """
/// Reboots to bootloader.
@@ -512,12 +512,12 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(
/// class FirmwareHeaderInfo(NamedTuple):
/// version: VersionTuple
/// vendor: str
-/// fingerprint: bytes
-/// hash: bytes
+/// fingerprint: AnyBytes
+/// hash: AnyBytes
/// mock:global
-/// def check_firmware_header(header : bytes) -> FirmwareHeaderInfo:
+/// def check_firmware_header(header : AnyBytes) -> FirmwareHeaderInfo:
/// """Parses incoming firmware header and returns information about it."""
STATIC mp_obj_t mod_trezorutils_check_firmware_header(mp_obj_t header) {
mp_buffer_info_t header_buf = {0};
diff --git a/core/mocks/buffer_types.pyi b/core/mocks/buffer_types.pyi
new file mode 100644
index 00000000..3eb2c73d
--- /dev/null
+++ b/core/mocks/buffer_types.pyi
@@ -0,0 +1,3 @@
+AnyBuffer = bytearray | memoryview
+AnyBytes = bytes | bytearray | memoryview
+StrOrBytes = str | AnyBytes
diff --git a/core/mocks/generated/buffer_types.pyi b/core/mocks/generated/buffer_types.pyi
new file mode 120000
index 00000000..a6377880
--- /dev/null
+++ b/core/mocks/generated/buffer_types.pyi
@@ -0,0 +1 @@
+../buffer_types.pyi
\ No newline at end of file
diff --git a/core/mocks/generated/coveragedata.pyi b/core/mocks/generated/coveragedata.pyi
index 1ee2c8fb..48f5daaa 100644
--- a/core/mocks/generated/coveragedata.pyi
+++ b/core/mocks/generated/coveragedata.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# rust/src/coverage/mod.rs
diff --git a/core/mocks/generated/trezorble.pyi b/core/mocks/generated/trezorble.pyi
index 280e4df1..6cb86d4f 100644
--- a/core/mocks/generated/trezorble.pyi
+++ b/core/mocks/generated/trezorble.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# rust/src/trezorhal/ble/micropython.rs
@@ -16,12 +17,12 @@ class BLEIF:
Returns the configured number of this interface.
"""
- def write(self, msg: bytes) -> int:
+ def write(self, msg: AnyBytes) -> int:
"""
Sends message over BLE
"""
- def read(self, buf: bytearray, offset: int = 0) -> int:
+ def read(self, buf: AnyBuffer, offset: int = 0) -> int:
"""
Reads message using BLE (device).
"""
@@ -38,7 +39,7 @@ def erase_bonds():
# rust/src/trezorhal/ble/micropython.rs
-def unpair(addr: bytes | None):
+def unpair(addr: AnyBytes | None):
"""
Erases the bond for the given address or for current connection if addr is None.
Raises exception if BLE driver reports an error.
diff --git a/core/mocks/generated/trezorconfig.pyi b/core/mocks/generated/trezorconfig.pyi
index 44f72b77..f7ab806f 100644
--- a/core/mocks/generated/trezorconfig.pyi
+++ b/core/mocks/generated/trezorconfig.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorconfig/modtrezorconfig.c
@@ -14,7 +15,7 @@ def init(
# upymod/modtrezorconfig/modtrezorconfig.c
-def unlock(pin: str, ext_salt: bytes | None) -> bool:
+def unlock(pin: str, ext_salt: AnyBytes | None) -> bool:
"""
Attempts to unlock the storage with the given PIN and external salt.
Returns True on success, False on failure.
@@ -22,7 +23,7 @@ def unlock(pin: str, ext_salt: bytes | None) -> bool:
# upymod/modtrezorconfig/modtrezorconfig.c
-def check_pin(pin: str, ext_salt: bytes | None) -> bool:
+def check_pin(pin: str, ext_salt: AnyBytes | None) -> bool:
"""
Check the given PIN with the given external salt.
Returns True on success, False on failure.
@@ -61,8 +62,8 @@ def get_pin_rem() -> int:
def change_pin(
oldpin: str,
newpin: str,
- old_ext_salt: bytes | None,
- new_ext_salt: bytes | None,
+ old_ext_salt: AnyBytes | None,
+ new_ext_salt: AnyBytes | None,
) -> bool:
"""
Change PIN and external salt. Returns True on success, False on failure.
@@ -86,7 +87,7 @@ def has_wipe_code() -> bool:
# upymod/modtrezorconfig/modtrezorconfig.c
def change_wipe_code(
pin: str,
- ext_salt: bytes | None,
+ ext_salt: AnyBytes | None,
wipe_code: str,
) -> bool:
"""
@@ -104,7 +105,7 @@ def get(app: int, key: int, public: bool = False) -> bytes | None:
# upymod/modtrezorconfig/modtrezorconfig.c
-def set(app: int, key: int, value: bytes, public: bool = False) -> None:
+def set(app: int, key: int, value: AnyBytes, public: bool = False) -> None:
"""
Sets a value of given key for given app.
"""
diff --git a/core/mocks/generated/trezorcrypto/__init__.pyi b/core/mocks/generated/trezorcrypto/__init__.pyi
index 4d9ef558..03bf7fc4 100644
--- a/core/mocks/generated/trezorcrypto/__init__.pyi
+++ b/core/mocks/generated/trezorcrypto/__init__.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-aes.h
@@ -15,19 +16,19 @@ class aes:
def __init__(
self,
mode: int,
- key: bytes,
- iv: bytes | None = None,
+ key: AnyBytes,
+ iv: AnyBytes | None = None,
) -> None:
"""
Initialize AES context.
"""
- def encrypt(self, data: bytes) -> bytes:
+ def encrypt(self, data: AnyBytes) -> bytes:
"""
Encrypt data and update AES context.
"""
- def decrypt(self, data: bytes) -> bytes:
+ def decrypt(self, data: AnyBytes) -> bytes:
"""
Decrypt data and update AES context.
"""
@@ -39,37 +40,37 @@ class aesgcm:
AES-GCM context.
"""
- def __init__(self, key: bytes, iv: bytes) -> None:
+ def __init__(self, key: AnyBytes, iv: AnyBytes) -> None:
"""
Initialize the AES-GCM context for encryption or decryption.
"""
- def reset(self, iv: bytes) -> None:
+ def reset(self, iv: AnyBytes) -> None:
"""
Reset the IV for encryption or decryption.
"""
- def encrypt(self, data: bytes) -> bytes:
+ def encrypt(self, data: AnyBytes) -> bytes:
"""
Encrypt data chunk.
"""
- def encrypt_in_place(self, data: bytearray | memoryview) -> int:
+ def encrypt_in_place(self, data: AnyBuffer) -> int:
"""
Encrypt data chunk in place. Returns the length of the encrypted data.
"""
- def decrypt(self, data: bytes) -> bytes:
+ def decrypt(self, data: AnyBytes) -> bytes:
"""
Decrypt data chunk.
"""
- def decrypt_in_place(self, data: bytearray | memoryview) -> int:
+ def decrypt_in_place(self, data: AnyBuffer) -> int:
"""
Decrypt data chunk in place. Returns the length of the decrypted data.
"""
- def auth(self, data: bytes) -> None:
+ def auth(self, data: AnyBytes) -> None:
"""
Include authenticated data chunk in the GCM authentication tag. This can
be called repeatedly to add authenticated data at any point before
@@ -90,12 +91,12 @@ class blake256:
block_size: int
digest_size: int
- def __init__(self, __data: AnyStr | None = None) -> None:
+ def __init__(self, __data: StrOrBytes | None = None) -> None:
"""
Creates a hash context object.
"""
- def update(self, __data: AnyStr) -> None:
+ def update(self, __data: StrOrBytes) -> None:
"""
Update the hash context with hashed data.
"""
@@ -116,16 +117,16 @@ class blake2b:
def __init__(
self,
- data: bytes | None = None,
+ data: AnyBytes | None = None,
outlen: int = blake2b.digest_size,
- key: bytes | None = None,
- personal: bytes | None = None,
+ key: AnyBytes | None = None,
+ personal: AnyBytes | None = None,
) -> None:
"""
Creates a hash context object.
"""
- def update(self, __data: AnyStr) -> None:
+ def update(self, __data: StrOrBytes) -> None:
"""
Update the hash context with hashed data.
"""
@@ -146,16 +147,16 @@ class blake2s:
def __init__(
self,
- data: bytes | None = None,
+ data: AnyBytes | None = None,
outlen: int = blake2s.digest_size,
- key: bytes | None = None,
- personal: bytes | None = None,
+ key: AnyBytes | None = None,
+ personal: AnyBytes | None = None,
) -> None:
"""
Creates a hash context object.
"""
- def update(self, __data: AnyStr) -> None:
+ def update(self, __data: StrOrBytes) -> None:
"""
Update the hash context with hashed data.
"""
@@ -172,25 +173,25 @@ class chacha20poly1305:
ChaCha20Poly1305 context.
"""
- def __init__(self, key: bytes, nonce: bytes) -> None:
+ def __init__(self, key: AnyBytes, nonce: AnyBytes) -> None:
"""
Initialize the ChaCha20 + Poly1305 context for encryption or decryption
using a 32 byte key and 12 byte nonce as in the RFC 7539 style.
"""
- def encrypt(self, data: bytes) -> bytes:
+ def encrypt(self, data: AnyBytes) -> bytes:
"""
Encrypt data (length of data must be divisible by 64 except for the
final value).
"""
- def decrypt(self, data: bytes) -> bytes:
+ def decrypt(self, data: AnyBytes) -> bytes:
"""
Decrypt data (length of data must be divisible by 64 except for the
final value).
"""
- def auth(self, data: bytes) -> None:
+ def auth(self, data: AnyBytes) -> None:
"""
Include authenticated data in the Poly1305 MAC using the RFC 7539
style with 16 byte padding. This must only be called once and prior
@@ -211,12 +212,12 @@ class groestl512:
block_size: int
digest_size: int
- def __init__(self, __data: AnyStr | None = None) -> None:
+ def __init__(self, __data: StrOrBytes | None = None) -> None:
"""
Creates a hash context object.
"""
- def update(self, __data: AnyStr) -> None:
+ def update(self, __data: StrOrBytes) -> None:
"""
Update the hash context with hashed data.
"""
@@ -238,14 +239,14 @@ class hmac:
def __init__(
self,
hashtype: int,
- key: bytes,
- message: bytes | None = None,
+ key: AnyBytes,
+ message: AnyBytes | None = None,
) -> None:
"""
Create a HMAC context.
"""
- def update(self, message: bytes) -> None:
+ def update(self, message: AnyBytes) -> None:
"""
Update a HMAC context.
"""
@@ -267,8 +268,8 @@ class pbkdf2:
def __init__(
self,
prf: int,
- password: bytes,
- salt: bytes,
+ password: AnyBytes,
+ salt: AnyBytes,
iterations: int | None = None,
blocknr: int = 1,
) -> None:
@@ -295,12 +296,12 @@ class ripemd160:
block_size: int
digest_size: int
- def __init__(self, __data: AnyStr | None = None) -> None:
+ def __init__(self, __data: StrOrBytes | None = None) -> None:
"""
Creates a hash context object.
"""
- def update(self, __data: AnyStr) -> None:
+ def update(self, __data: StrOrBytes) -> None:
"""
Update the hash context with hashed data.
"""
@@ -319,12 +320,12 @@ class sha1:
block_size: int
digest_size: int
- def __init__(self, __data: AnyStr | None = None) -> None:
+ def __init__(self, __data: StrOrBytes | None = None) -> None:
"""
Creates a hash context object.
"""
- def update(self, __data: AnyStr) -> None:
+ def update(self, __data: StrOrBytes) -> None:
"""
Update the hash context with hashed data.
"""
@@ -343,12 +344,12 @@ class sha256:
block_size: int
digest_size: int
- def __init__(self, __data: AnyStr | None = None) -> None:
+ def __init__(self, __data: StrOrBytes | None = None) -> None:
"""
Creates a hash context object.
"""
- def update(self, __data: AnyStr) -> None:
+ def update(self, __data: StrOrBytes) -> None:
"""
Update the hash context with hashed data.
"""
@@ -369,14 +370,14 @@ class sha3_256:
def __init__(
self,
- data: bytes | None = None,
+ data: AnyBytes | None = None,
keccak: bool = False,
) -> None:
"""
Creates a hash context object.
"""
- def update(self, __data: AnyStr) -> None:
+ def update(self, __data: StrOrBytes) -> None:
"""
Update the hash context with hashed data.
"""
@@ -402,14 +403,14 @@ class sha3_512:
def __init__(
self,
- data: bytes | None = None,
+ data: AnyBytes | None = None,
keccak: bool = False,
) -> None:
"""
Creates a hash context object.
"""
- def update(self, __data: AnyStr) -> None:
+ def update(self, __data: StrOrBytes) -> None:
"""
Update the hash context with hashed data.
"""
@@ -433,12 +434,12 @@ class sha512:
block_size: int
digest_size: int
- def __init__(self, __data: AnyStr | None = None) -> None:
+ def __init__(self, __data: StrOrBytes | None = None) -> None:
"""
Creates a hash context object.
"""
- def update(self, __data: AnyStr) -> None:
+ def update(self, __data: StrOrBytes) -> None:
"""
Update the hash context with hashed data.
"""
diff --git a/core/mocks/generated/trezorcrypto/bech32.pyi b/core/mocks/generated/trezorcrypto/bech32.pyi
index c47a7b38..3c922dc2 100644
--- a/core/mocks/generated/trezorcrypto/bech32.pyi
+++ b/core/mocks/generated/trezorcrypto/bech32.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-bech32.h
diff --git a/core/mocks/generated/trezorcrypto/bip32.pyi b/core/mocks/generated/trezorcrypto/bip32.pyi
index be8b08e2..dcc6c5ea 100644
--- a/core/mocks/generated/trezorcrypto/bip32.pyi
+++ b/core/mocks/generated/trezorcrypto/bip32.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-bip32.h
@@ -12,9 +13,9 @@ class HDNode:
depth: int,
fingerprint: int,
child_num: int,
- chain_code: bytes,
- private_key: bytes | None = None,
- public_key: bytes | None = None,
+ chain_code: AnyBytes,
+ private_key: AnyBytes | None = None,
+ public_key: AnyBytes | None = None,
curve_name: str | None = None,
) -> None:
"""
@@ -87,7 +88,11 @@ class HDNode:
"""
def nem_encrypt(
- self, transfer_public_key: bytes, iv: bytes, salt: bytes, payload: bytes
+ self,
+ transfer_public_key: AnyBytes,
+ iv: AnyBytes,
+ salt: AnyBytes,
+ payload: AnyBytes,
) -> bytes:
"""
Encrypts payload using the transfer's public key
@@ -105,7 +110,7 @@ class HDNode:
# upymod/modtrezorcrypto/modtrezorcrypto-bip32.h
-def from_seed(seed: bytes, curve_name: str) -> HDNode:
+def from_seed(seed: AnyBytes, curve_name: str) -> HDNode:
"""
Construct a BIP0032 HD node from a BIP0039 seed value.
"""
diff --git a/core/mocks/generated/trezorcrypto/bip340.pyi b/core/mocks/generated/trezorcrypto/bip340.pyi
index 1039c9d7..009a9bda 100644
--- a/core/mocks/generated/trezorcrypto/bip340.pyi
+++ b/core/mocks/generated/trezorcrypto/bip340.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-bip340.h
@@ -9,7 +10,7 @@ def generate_secret() -> bytes:
# upymod/modtrezorcrypto/modtrezorcrypto-bip340.h
-def publickey(secret_key: bytes) -> bytes:
+def publickey(secret_key: AnyBytes) -> bytes:
"""
Computes public key from secret key.
"""
@@ -17,8 +18,8 @@ def publickey(secret_key: bytes) -> bytes:
# upymod/modtrezorcrypto/modtrezorcrypto-bip340.h
def sign(
- secret_key: bytes,
- digest: bytes,
+ secret_key: AnyBytes,
+ digest: AnyBytes,
) -> bytes:
"""
Uses secret key to produce the signature of the digest.
@@ -26,7 +27,7 @@ def sign(
# upymod/modtrezorcrypto/modtrezorcrypto-bip340.h
-def verify_publickey(public_key: bytes) -> bool:
+def verify_publickey(public_key: AnyBytes) -> bool:
"""
Verifies whether the public key is valid.
Returns True on success.
@@ -34,7 +35,9 @@ def verify_publickey(public_key: bytes) -> bool:
# upymod/modtrezorcrypto/modtrezorcrypto-bip340.h
-def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool:
+def verify(
+ public_key: AnyBytes, signature: AnyBytes, digest: AnyBytes
+) -> bool:
"""
Uses public key to verify the signature of the digest.
Returns True on success.
@@ -43,8 +46,8 @@ def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool:
# upymod/modtrezorcrypto/modtrezorcrypto-bip340.h
def tweak_public_key(
- public_key: bytes,
- root_hash: bytes | None = None,
+ public_key: AnyBytes,
+ root_hash: AnyBytes | None = None,
) -> bytes:
"""
Tweaks the public key with the specified root_hash.
@@ -53,8 +56,8 @@ def tweak_public_key(
# upymod/modtrezorcrypto/modtrezorcrypto-bip340.h
def tweak_secret_key(
- secret_key: bytes,
- root_hash: bytes | None = None,
+ secret_key: AnyBytes,
+ root_hash: AnyBytes | None = None,
) -> bytes:
"""
Tweaks the secret key with the specified root_hash.
diff --git a/core/mocks/generated/trezorcrypto/bip39.pyi b/core/mocks/generated/trezorcrypto/bip39.pyi
index c1426b62..a1c915c7 100644
--- a/core/mocks/generated/trezorcrypto/bip39.pyi
+++ b/core/mocks/generated/trezorcrypto/bip39.pyi
@@ -1,8 +1,9 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-bip39.h
-def from_data(data: bytes) -> str:
+def from_data(data: AnyBytes) -> str:
"""
Generate a mnemonic from given data (of 16, 20, 24, 28 and 32 bytes).
"""
diff --git a/core/mocks/generated/trezorcrypto/cardano.pyi b/core/mocks/generated/trezorcrypto/cardano.pyi
index 3633b258..29158df8 100644
--- a/core/mocks/generated/trezorcrypto/cardano.pyi
+++ b/core/mocks/generated/trezorcrypto/cardano.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
from trezorcrypto.bip32 import HDNode
@@ -18,21 +19,21 @@ def derive_icarus(
# upymod/modtrezorcrypto/modtrezorcrypto-cardano.h
-def from_secret(secret: bytes) -> HDNode:
+def from_secret(secret: AnyBytes) -> HDNode:
"""
Creates a Cardano HD node from a master secret.
"""
# upymod/modtrezorcrypto/modtrezorcrypto-cardano.h
-def from_seed_slip23(seed: bytes) -> HDNode:
+def from_seed_slip23(seed: AnyBytes) -> HDNode:
"""
Creates a Cardano HD node from a seed via SLIP-23 derivation.
"""
# upymod/modtrezorcrypto/modtrezorcrypto-cardano.h
-def from_seed_ledger(seed: bytes) -> HDNode:
+def from_seed_ledger(seed: AnyBytes) -> HDNode:
"""
Creates a Cardano HD node from a seed via Ledger derivation.
"""
diff --git a/core/mocks/generated/trezorcrypto/crc.pyi b/core/mocks/generated/trezorcrypto/crc.pyi
index 9a319f79..e30c84a1 100644
--- a/core/mocks/generated/trezorcrypto/crc.pyi
+++ b/core/mocks/generated/trezorcrypto/crc.pyi
@@ -1,8 +1,9 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-crc.h
-def crc32(data: bytes, crc: int = 0) -> int:
+def crc32(data: AnyBytes, crc: int = 0) -> int:
"""
Computes a CRC32 checksum of `data`.
diff --git a/core/mocks/generated/trezorcrypto/curve25519.pyi b/core/mocks/generated/trezorcrypto/curve25519.pyi
index e5ac78eb..066ec420 100644
--- a/core/mocks/generated/trezorcrypto/curve25519.pyi
+++ b/core/mocks/generated/trezorcrypto/curve25519.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-curve25519.h
@@ -9,14 +10,14 @@ def generate_secret() -> bytes:
# upymod/modtrezorcrypto/modtrezorcrypto-curve25519.h
-def publickey(secret_key: bytes) -> bytes:
+def publickey(secret_key: AnyBytes) -> bytes:
"""
Computes public key from secret key.
"""
# upymod/modtrezorcrypto/modtrezorcrypto-curve25519.h
-def multiply(secret_key: bytes, public_key: bytes) -> bytes:
+def multiply(secret_key: AnyBytes, public_key: AnyBytes) -> bytes:
"""
Multiplies point defined by public_key with scalar defined by
secret_key. Useful for ECDH.
diff --git a/core/mocks/generated/trezorcrypto/ed25519.pyi b/core/mocks/generated/trezorcrypto/ed25519.pyi
index 07da52b3..ecea0d3e 100644
--- a/core/mocks/generated/trezorcrypto/ed25519.pyi
+++ b/core/mocks/generated/trezorcrypto/ed25519.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-ed25519.h
@@ -9,14 +10,16 @@ def generate_secret() -> bytes:
# upymod/modtrezorcrypto/modtrezorcrypto-ed25519.h
-def publickey(secret_key: bytes) -> bytes:
+def publickey(secret_key: AnyBytes) -> bytes:
"""
Computes public key from secret key.
"""
# upymod/modtrezorcrypto/modtrezorcrypto-ed25519.h
-def sign(secret_key: bytes, message: bytes, hasher: str = "") -> bytes:
+def sign(
+ secret_key: AnyBytes, message: AnyBytes, hasher: str = ""
+) -> bytes:
"""
Uses secret key to produce the signature of message.
"""
@@ -24,7 +27,7 @@ def sign(secret_key: bytes, message: bytes, hasher: str = "") -> bytes:
# upymod/modtrezorcrypto/modtrezorcrypto-ed25519.h
def sign_ext(
- secret_scalar: bytes, secret_extension: bytes, message: bytes
+ secret_scalar: AnyBytes, secret_extension: AnyBytes, message: AnyBytes
) -> bytes:
"""
Uses extended secret key to produce the cardano signature of message.
@@ -32,7 +35,9 @@ def sign_ext(
# upymod/modtrezorcrypto/modtrezorcrypto-ed25519.h
-def verify(public_key: bytes, signature: bytes, message: bytes) -> bool:
+def verify(
+ public_key: AnyBytes, signature: AnyBytes, message: AnyBytes
+) -> bool:
"""
Uses public key to verify the signature of the message.
Returns True on success.
@@ -40,14 +45,16 @@ def verify(public_key: bytes, signature: bytes, message: bytes) -> bool:
# upymod/modtrezorcrypto/modtrezorcrypto-ed25519.h
-def cosi_combine_publickeys(public_keys: list[bytes]) -> bytes:
+def cosi_combine_publickeys(public_keys: Sequence[AnyBytes]) -> bytes:
"""
Combines a list of public keys used in COSI cosigning scheme.
"""
# upymod/modtrezorcrypto/modtrezorcrypto-ed25519.h
-def cosi_combine_signatures(R: bytes, signatures: list[bytes]) -> bytes:
+def cosi_combine_signatures(
+ R: AnyBytes, signatures: Sequence[AnyBytes]
+) -> bytes:
"""
Combines a list of signatures used in COSI cosigning scheme.
"""
@@ -62,11 +69,11 @@ def cosi_commit() -> tuple[bytes, bytes]:
# upymod/modtrezorcrypto/modtrezorcrypto-ed25519.h
def cosi_sign(
- secret_key: bytes,
- message: bytes,
- nonce: bytes,
- sigR: bytes,
- combined_pubkey: bytes,
+ secret_key: AnyBytes,
+ message: AnyBytes,
+ nonce: AnyBytes,
+ sigR: AnyBytes,
+ combined_pubkey: AnyBytes,
) -> bytes:
"""
Produce signature of message using COSI cosigning scheme.
diff --git a/core/mocks/generated/trezorcrypto/elligator2.pyi b/core/mocks/generated/trezorcrypto/elligator2.pyi
index c9240678..dc426e57 100644
--- a/core/mocks/generated/trezorcrypto/elligator2.pyi
+++ b/core/mocks/generated/trezorcrypto/elligator2.pyi
@@ -1,8 +1,9 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-elligator2.h
-def map_to_curve25519(input: bytes) -> bytes:
+def map_to_curve25519(input: AnyBytes) -> bytes:
"""
Maps a 32-byte input to a curve25519 point.
"""
diff --git a/core/mocks/generated/trezorcrypto/monero.pyi b/core/mocks/generated/trezorcrypto/monero.pyi
index e38926d1..98d8a702 100644
--- a/core/mocks/generated/trezorcrypto/monero.pyi
+++ b/core/mocks/generated/trezorcrypto/monero.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-monero.h
@@ -28,11 +29,11 @@ class Hasher:
"""
XMR hasher
"""
- def __init__(self, x: bytes | None = None):
+ def __init__(self, x: AnyBytes | None = None):
"""
Constructor
"""
- def update(self, buffer: bytes) -> None:
+ def update(self, buffer: AnyBytes) -> None:
"""
Update hasher
"""
@@ -124,7 +125,7 @@ def sc_inv_into(r: Scalar | None, a: Scalar) -> Scalar:
# upymod/modtrezorcrypto/modtrezorcrypto-monero.h
def encodeint_into(
- r: bytes | None, a: Scalar, offset: int | None = 0
+ r: AnyBytes | None, a: Scalar, offset: int | None = 0
) -> bytes:
"""
Scalar compression
@@ -133,7 +134,7 @@ def encodeint_into(
# upymod/modtrezorcrypto/modtrezorcrypto-monero.h
def decodeint_into(
- r: Scalar | None, a: bytes, offset: int = 0
+ r: Scalar | None, a: AnyBytes, offset: int = 0
) -> Scalar:
"""
Scalar decompression
@@ -142,7 +143,7 @@ def decodeint_into(
# upymod/modtrezorcrypto/modtrezorcrypto-monero.h
def decodeint_into_noreduce(
- r: Scalar | None, a: bytes, offset: int = 0
+ r: Scalar | None, a: AnyBytes, offset: int = 0
) -> Scalar:
"""
Scalar decompression, raw, without modular reduction
@@ -226,7 +227,9 @@ def scalarmult_into(
# upymod/modtrezorcrypto/modtrezorcrypto-monero.h
-def encodepoint_into(r: bytes | None, p: Point, offset: int = 0) -> bytes:
+def encodepoint_into(
+ r: AnyBytes | None, p: Point, offset: int = 0
+) -> bytes:
"""
Point compression
"""
@@ -234,7 +237,7 @@ def encodepoint_into(r: bytes | None, p: Point, offset: int = 0) -> bytes:
# upymod/modtrezorcrypto/modtrezorcrypto-monero.h
def decodepoint_into(
- r: Point | None, buff: bytes, offset: int = 0
+ r: Point | None, buff: AnyBytes, offset: int = 0
) -> Point:
"""
Point decompression
@@ -242,14 +245,14 @@ def decodepoint_into(
# upymod/modtrezorcrypto/modtrezorcrypto-monero.h
-def xmr_base58_addr_encode_check(tag: int, buff: bytes) -> str:
+def xmr_base58_addr_encode_check(tag: int, buff: AnyBytes) -> str:
"""
Monero block base 58 encoding
"""
# upymod/modtrezorcrypto/modtrezorcrypto-monero.h
-def xmr_base58_addr_decode_check(buff: bytes) -> tuple[bytes, int]:
+def xmr_base58_addr_decode_check(buff: AnyBytes) -> tuple[bytes, int]:
"""
Monero block base 58 decoding, returning (decoded, tag) or raising on
error.
@@ -265,8 +268,8 @@ def random_scalar(r: Scalar | None = None) -> Scalar:
# upymod/modtrezorcrypto/modtrezorcrypto-monero.h
def fast_hash_into(
- r: bytes | None,
- buff: bytes,
+ r: AnyBytes | None,
+ buff: AnyBytes,
length: int | None = None,
offset: int = 0,
) -> bytes:
@@ -278,7 +281,7 @@ def fast_hash_into(
# upymod/modtrezorcrypto/modtrezorcrypto-monero.h
def hash_to_point_into(
r: Point | None,
- buff: bytes,
+ buff: AnyBytes,
length: int | None = None,
offset: int = 0,
) -> Point:
@@ -290,7 +293,7 @@ def hash_to_point_into(
# upymod/modtrezorcrypto/modtrezorcrypto-monero.h
def hash_to_scalar_into(
r: Scalar | None,
- buff: bytes,
+ buff: AnyBytes,
length: int | None = None,
offset: int = 0,
) -> Scalar:
@@ -370,7 +373,7 @@ def gen_commitment_into(r: Point | None, a: Scalar, amount: int) -> Point:
# upymod/modtrezorcrypto/modtrezorcrypto-monero.h
-def ct_equals(a: bytes, b: bytes) -> bool:
+def ct_equals(a: AnyBytes, b: AnyBytes) -> bool:
"""
Constant time buffer comparison
"""
diff --git a/core/mocks/generated/trezorcrypto/nem.pyi b/core/mocks/generated/trezorcrypto/nem.pyi
index 896bae24..8217b401 100644
--- a/core/mocks/generated/trezorcrypto/nem.pyi
+++ b/core/mocks/generated/trezorcrypto/nem.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-nem.h
@@ -9,7 +10,7 @@ def validate_address(address: str, network: int) -> bool:
# upymod/modtrezorcrypto/modtrezorcrypto-nem.h
-def compute_address(public_key: bytes, network: int) -> str:
+def compute_address(public_key: AnyBytes, network: int) -> str:
"""
Compute a NEM address from a public key
"""
diff --git a/core/mocks/generated/trezorcrypto/nist256p1.pyi b/core/mocks/generated/trezorcrypto/nist256p1.pyi
index 204d03c9..249e47be 100644
--- a/core/mocks/generated/trezorcrypto/nist256p1.pyi
+++ b/core/mocks/generated/trezorcrypto/nist256p1.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
@@ -9,7 +10,7 @@ def generate_secret() -> bytes:
# upymod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
-def publickey(secret_key: bytes, compressed: bool = True) -> bytes:
+def publickey(secret_key: AnyBytes, compressed: bool = True) -> bytes:
"""
Computes public key from secret key.
"""
@@ -17,7 +18,7 @@ def publickey(secret_key: bytes, compressed: bool = True) -> bytes:
# upymod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
def sign(
- secret_key: bytes, digest: bytes, compressed: bool = True
+ secret_key: AnyBytes, digest: AnyBytes, compressed: bool = True
) -> bytes:
"""
Uses secret key to produce the signature of the digest.
@@ -25,7 +26,9 @@ def sign(
# upymod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
-def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool:
+def verify(
+ public_key: AnyBytes, signature: AnyBytes, digest: AnyBytes
+) -> bool:
"""
Uses public key to verify the signature of the digest.
Returns True on success.
@@ -33,7 +36,7 @@ def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool:
# upymod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
-def verify_recover(signature: bytes, digest: bytes) -> bytes:
+def verify_recover(signature: AnyBytes, digest: AnyBytes) -> bytes:
"""
Uses signature of the digest to verify the digest and recover the public
key. Returns public key on success, None if the signature is invalid.
@@ -41,7 +44,7 @@ def verify_recover(signature: bytes, digest: bytes) -> bytes:
# upymod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
-def multiply(secret_key: bytes, public_key: bytes) -> bytes:
+def multiply(secret_key: AnyBytes, public_key: AnyBytes) -> bytes:
"""
Multiplies point defined by public_key with scalar defined by
secret_key. Useful for ECDH.
diff --git a/core/mocks/generated/trezorcrypto/optiga.pyi b/core/mocks/generated/trezorcrypto/optiga.pyi
index dac03ebc..85379775 100644
--- a/core/mocks/generated/trezorcrypto/optiga.pyi
+++ b/core/mocks/generated/trezorcrypto/optiga.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-optiga.h
@@ -23,7 +24,7 @@ def get_certificate(cert_index: int) -> bytes:
# upymod/modtrezorcrypto/modtrezorcrypto-optiga.h
def sign(
key_index: int,
- digest: bytes,
+ digest: AnyBytes,
) -> bytes:
"""
Uses the private key at key_index to produce a DER-encoded signature of
diff --git a/core/mocks/generated/trezorcrypto/random.pyi b/core/mocks/generated/trezorcrypto/random.pyi
index b13e5a54..323647d9 100644
--- a/core/mocks/generated/trezorcrypto/random.pyi
+++ b/core/mocks/generated/trezorcrypto/random.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-random.h
diff --git a/core/mocks/generated/trezorcrypto/secp256k1.pyi b/core/mocks/generated/trezorcrypto/secp256k1.pyi
index 6c9b6167..fd8b0302 100644
--- a/core/mocks/generated/trezorcrypto/secp256k1.pyi
+++ b/core/mocks/generated/trezorcrypto/secp256k1.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
@@ -9,7 +10,7 @@ def generate_secret() -> bytes:
# upymod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
-def publickey(secret_key: bytes, compressed: bool = True) -> bytes:
+def publickey(secret_key: AnyBytes, compressed: bool = True) -> bytes:
"""
Computes public key from secret key.
"""
@@ -19,8 +20,8 @@ CANONICAL_SIG_EOS: int = 2
# upymod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
def sign(
- secret_key: bytes,
- digest: bytes,
+ secret_key: AnyBytes,
+ digest: AnyBytes,
compressed: bool = True,
canonical: int | None = None,
) -> bytes:
@@ -30,7 +31,9 @@ def sign(
# upymod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
-def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool:
+def verify(
+ public_key: AnyBytes, signature: AnyBytes, digest: AnyBytes
+) -> bool:
"""
Uses public key to verify the signature of the digest.
Returns True on success.
@@ -38,7 +41,7 @@ def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool:
# upymod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
-def verify_recover(signature: bytes, digest: bytes) -> bytes:
+def verify_recover(signature: AnyBytes, digest: AnyBytes) -> bytes:
"""
Uses signature of the digest to verify the digest and recover the public
key. Returns public key on success, None if the signature is invalid.
@@ -46,7 +49,7 @@ def verify_recover(signature: bytes, digest: bytes) -> bytes:
# upymod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
-def multiply(secret_key: bytes, public_key: bytes) -> bytes:
+def multiply(secret_key: AnyBytes, public_key: AnyBytes) -> bytes:
"""
Multiplies point defined by public_key with scalar defined by
secret_key. Useful for ECDH.
diff --git a/core/mocks/generated/trezorcrypto/shamir.pyi b/core/mocks/generated/trezorcrypto/shamir.pyi
index 7dedbdd2..4f2a61af 100644
--- a/core/mocks/generated/trezorcrypto/shamir.pyi
+++ b/core/mocks/generated/trezorcrypto/shamir.pyi
@@ -1,8 +1,9 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-shamir.h
-def interpolate(shares: list[tuple[int, bytes]], x: int) -> bytes:
+def interpolate(shares: Sequence[tuple[int, AnyBytes]], x: int) -> bytes:
"""
Returns f(x) given the Shamir shares (x_1, f(x_1)), ... , (x_k, f(x_k)).
:param shares: The Shamir shares.
diff --git a/core/mocks/generated/trezorcrypto/slip39.pyi b/core/mocks/generated/trezorcrypto/slip39.pyi
index 32d11ec4..06a6f13e 100644
--- a/core/mocks/generated/trezorcrypto/slip39.pyi
+++ b/core/mocks/generated/trezorcrypto/slip39.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-slip39.h
diff --git a/core/mocks/generated/trezorcrypto/tropic.pyi b/core/mocks/generated/trezorcrypto/tropic.pyi
index 000df41b..49bd2e58 100644
--- a/core/mocks/generated/trezorcrypto/tropic.pyi
+++ b/core/mocks/generated/trezorcrypto/tropic.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorcrypto/modtrezorcrypto-tropic.h
@@ -25,7 +26,7 @@ def key_generate(
# upymod/modtrezorcrypto/modtrezorcrypto-tropic.h
def sign(
key_index: int,
- digest: bytes,
+ digest: AnyBytes,
) -> bytes:
"""
Uses the private key at key_index to produce a signature of the digest.
diff --git a/core/mocks/generated/trezorio/__init__.pyi b/core/mocks/generated/trezorio/__init__.pyi
index d26e1478..06ca7804 100644
--- a/core/mocks/generated/trezorio/__init__.pyi
+++ b/core/mocks/generated/trezorio/__init__.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorio/modtrezorio-poll.h
@@ -37,12 +38,12 @@ class USBIF:
Returns the configured number of this interface.
"""
- def write(self, msg: bytes) -> int:
+ def write(self, msg: AnyBytes) -> int:
"""
Sends message using USB interface.
"""
- def write_blocking(self, msg: bytes, timeout_ms: int) -> int:
+ def write_blocking(self, msg: AnyBytes, timeout_ms: int) -> int:
"""
Sends message using USB interface.
"""
diff --git a/core/mocks/generated/trezorio/fatfs.pyi b/core/mocks/generated/trezorio/fatfs.pyi
index a5685ec3..79ad6358 100644
--- a/core/mocks/generated/trezorio/fatfs.pyi
+++ b/core/mocks/generated/trezorio/fatfs.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
FR_OK: int # (0) Succeeded
FR_DISK_ERR: int # (1) A hard error occurred in the low level disk I/O layer
FR_INT_ERR: int # (2) Assertion failed
@@ -69,7 +70,7 @@ class FatFSFile:
Read data from the file
"""
- def write(self, data: bytes | bytearray) -> int:
+ def write(self, data: AnyBytes) -> int:
"""
Write data to the file
"""
diff --git a/core/mocks/generated/trezorio/haptic.pyi b/core/mocks/generated/trezorio/haptic.pyi
index dd9c8b3b..e9de8433 100644
--- a/core/mocks/generated/trezorio/haptic.pyi
+++ b/core/mocks/generated/trezorio/haptic.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorio/modtrezorio-haptic.h
diff --git a/core/mocks/generated/trezorio/pm.pyi b/core/mocks/generated/trezorio/pm.pyi
index 3cc3309b..d41115f7 100644
--- a/core/mocks/generated/trezorio/pm.pyi
+++ b/core/mocks/generated/trezorio/pm.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# Wakeup flags:
WAKEUP_FLAG_BUTTON: int
WAKEUP_FLAG_POWER: int
diff --git a/core/mocks/generated/trezorio/rgb_led.pyi b/core/mocks/generated/trezorio/rgb_led.pyi
index 8844686a..b7ce581e 100644
--- a/core/mocks/generated/trezorio/rgb_led.pyi
+++ b/core/mocks/generated/trezorio/rgb_led.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorio/modtrezorio-rgb_led.h
diff --git a/core/mocks/generated/trezorio/sdcard.pyi b/core/mocks/generated/trezorio/sdcard.pyi
index fb42622c..46b82161 100644
--- a/core/mocks/generated/trezorio/sdcard.pyi
+++ b/core/mocks/generated/trezorio/sdcard.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
BLOCK_SIZE: int # size of SD card block
@@ -42,7 +43,7 @@ def read(block_num: int, buf: bytearray) -> None:
# upymod/modtrezorio/modtrezorio-sdcard.h
-def write(block_num: int, buf: bytes) -> None:
+def write(block_num: int, buf: AnyBytes) -> None:
"""
Writes blocks starting with block_num from buf to the SD card.
Number of bytes written is length of buf rounded down to multiply of
diff --git a/core/mocks/generated/trezorlog.pyi b/core/mocks/generated/trezorlog.pyi
index cbad7e51..8acf3629 100644
--- a/core/mocks/generated/trezorlog.pyi
+++ b/core/mocks/generated/trezorlog.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# rust/src/micropython/logging.rs
diff --git a/core/mocks/generated/trezorproto.pyi b/core/mocks/generated/trezorproto.pyi
index ac881d7c..e3513c31 100644
--- a/core/mocks/generated/trezorproto.pyi
+++ b/core/mocks/generated/trezorproto.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
from typing_extensions import Self
# XXX
# Note that MessageType "subclasses" are not true subclasses, but instead instances
@@ -30,7 +31,7 @@ def type_for_wire(enum_name: str, wire_id: int) -> type[MessageType]:
# rust/src/protobuf/obj.rs
def decode(
- buffer: bytes,
+ buffer: AnyBytes,
msg_type: type[T],
enable_experimental: bool,
) -> T:
@@ -43,6 +44,6 @@ def encoded_length(msg: MessageType) -> int:
# rust/src/protobuf/obj.rs
-def encode(buffer: bytearray | memoryview, msg: MessageType) -> int:
+def encode(buffer: AnyBuffer, msg: MessageType) -> int:
"""Encode the message into the specified buffer. Return length of
encoding."""
diff --git a/core/mocks/generated/trezortranslate.pyi b/core/mocks/generated/trezortranslate.pyi
index 6ff45e80..16d69dc7 100644
--- a/core/mocks/generated/trezortranslate.pyi
+++ b/core/mocks/generated/trezortranslate.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
from trezortranslate_keys import TR as TR # noqa: F401
"""Translation object with attributes."""
@@ -34,12 +35,12 @@ def erase() -> None:
# rust/src/translations/obj.rs
-def write(data: bytes, offset: int) -> None:
+def write(data: AnyBytes, offset: int) -> None:
"""Write data to the translations blob in flash."""
# rust/src/translations/obj.rs
-def verify(data: bytes) -> None:
+def verify(data: AnyBytes) -> None:
"""Verify the translations blob."""
@@ -49,9 +50,9 @@ class TranslationsHeader:
language: str
version: tuple[int, int, int, int]
data_len: int
- data_hash: bytes
+ data_hash: AnyBytes
total_len: int
- def __init__(self, header_bytes: bytes) -> None:
+ def __init__(self, header_bytes: AnyBytes) -> None:
"""Parse header from bytes.
The header has variable length.
"""
diff --git a/core/mocks/generated/trezorui.pyi b/core/mocks/generated/trezorui.pyi
index c20d76a1..22beca02 100644
--- a/core/mocks/generated/trezorui.pyi
+++ b/core/mocks/generated/trezorui.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorui/modtrezorui-display.h
@@ -22,7 +23,9 @@ class Display:
value.
"""
- def record_start(self, target_directory: bytes, refresh_index: int) -> None:
+ def record_start(
+ self, target_directory: AnyBytes, refresh_index: int
+ ) -> None:
"""
Starts screen recording with specified target directory and refresh
index.
diff --git a/core/mocks/generated/trezorui_api.pyi b/core/mocks/generated/trezorui_api.pyi
index 0e415243..0b01b17b 100644
--- a/core/mocks/generated/trezorui_api.pyi
+++ b/core/mocks/generated/trezorui_api.pyi
@@ -1,7 +1,8 @@
from typing import *
+from buffer_types import *
from trezor import utils
-from trezor.enums import ButtonRequestType
-PropertyType = tuple[str | None, str | bytes | None, bool | None]
+from trezor.enums import ButtonRequestType, RecoveryType
+PropertyType = tuple[str | None, StrOrBytes | None, bool | None]
T = TypeVar("T")
@@ -80,7 +81,7 @@ INFO: UiResult
# rust/src/ui/api/firmware_micropython.rs
-def check_homescreen_format(data: bytes) -> bool:
+def check_homescreen_format(data: AnyBytes) -> bool:
"""Check homescreen format and dimensions."""
@@ -127,7 +128,7 @@ def confirm_action(
def confirm_address(
*,
title: str,
- address: str | bytes,
+ address: StrOrBytes,
address_label: str | None = None,
verb: str | None = None,
info_button: bool = False,
@@ -153,7 +154,7 @@ def confirm_trade(
def confirm_value(
*,
title: str,
- value: str | bytes,
+ value: StrOrBytes,
description: str | None,
is_data: bool = True,
extra: str | None = None,
@@ -180,7 +181,7 @@ def confirm_value(
def confirm_value_intro(
*,
title: str,
- value: str | bytes,
+ value: StrOrBytes,
subtitle: str | None = None,
verb: str | None = None,
verb_cancel: str | None = None,
@@ -219,7 +220,7 @@ def confirm_fido(
title: str,
app_name: str,
icon_name: str | None,
- accounts: list[str | None],
+ accounts: Sequence[str | None],
) -> LayoutObj[int | UiResult]:
"""FIDO confirmation.
Returns page index in case of confirmation and CANCELLED otherwise.
@@ -239,7 +240,7 @@ def confirm_firmware_update(
def confirm_homescreen(
*,
title: str,
- image: bytes,
+ image: AnyBytes,
) -> LayoutObj[UiResult]:
"""Confirm homescreen."""
@@ -273,7 +274,7 @@ def confirm_more(
button: str,
button_style_confirm: bool = False,
hold: bool = False,
- items: Iterable[tuple[str | bytes, bool]],
+ items: Iterable[tuple[StrOrBytes, bool]],
) -> LayoutObj[UiResult]:
"""Confirm long content with the possibility to go back from any page.
Meant to be used with confirm_with_info on UI Bolt and Caesar."""
@@ -284,7 +285,7 @@ def confirm_properties(
*,
title: str,
subtitle: str | None = None,
- items: list[PropertyType],
+ items: Sequence[PropertyType],
hold: bool = False,
verb: str | None = None,
external_menu: bool = False,
@@ -306,9 +307,9 @@ def confirm_summary(
fee: str,
fee_label: str,
title: str | None = None,
- account_items: list[PropertyType] | None = None,
+ account_items: Sequence[PropertyType] | None = None,
account_title: str | None = None,
- extra_items: list[PropertyType] | None = None,
+ extra_items: Sequence[PropertyType] | None = None,
extra_title: str | None = None,
verb_cancel: str | None = None,
back_button: bool = False,
@@ -322,7 +323,7 @@ def confirm_with_info(
*,
title: str,
subtitle: str | None = None,
- items: Iterable[tuple[str | bytes, bool]],
+ items: Iterable[tuple[StrOrBytes, bool]],
verb: str,
verb_info: str,
verb_cancel: str | None = None,
@@ -364,8 +365,8 @@ def flow_confirm_output(
br_name: str,
address_item: PropertyType | None,
extra_item: PropertyType | None,
- summary_items: list[PropertyType] | None = None,
- fee_items: list[PropertyType] | None = None,
+ summary_items: Sequence[PropertyType] | None = None,
+ fee_items: Sequence[PropertyType] | None = None,
summary_title: str | None = None,
summary_br_code: ButtonRequestType | None = None,
summary_br_name: str | None = None,
@@ -397,7 +398,7 @@ def flow_get_address(
case_sensitive: bool,
account: str | None,
path: str | None,
- xpubs: list[tuple[str, str]],
+ xpubs: Sequence[tuple[str, str]],
br_code: ButtonRequestType,
br_name: str,
) -> LayoutObj[UiResult]:
@@ -428,7 +429,7 @@ def multiple_pages_texts(
*,
title: str,
verb: str,
- items: list[str],
+ items: Sequence[str],
) -> LayoutObj[UiResult]:
"""Show multiple texts, each on its own page. TR specific."""
@@ -542,7 +543,7 @@ def select_word(
def select_word_count(
*,
recovery_type: RecoveryType,
-) -> LayoutObj[int | str | UIResult]: # TR returns str
+) -> LayoutObj[int | str | UiResult]: # TR returns str
"""Select a mnemonic word count from the options: 12, 18, 20, 24, or 33.
For unlocking a repeated backup, select between 20 and 33."""
@@ -561,7 +562,7 @@ def show_address_details(
details_title: str,
account: str | None,
path: str | None,
- xpubs: list[tuple[str, str]],
+ xpubs: Sequence[tuple[str, str]],
) -> LayoutObj[UiResult]:
"""Show address details - QR code, account, path, cosigner xpubs."""
@@ -638,7 +639,7 @@ def show_device_menu(
brightness: str | None,
haptics_enabled: bool | None,
led_enabled: bool | None,
- about_items: list[tuple[str | None, str | bytes | None, bool | None]],
+ about_items: Sequence[tuple[str | None, StrOrBytes | None, bool | None]],
) -> LayoutObj[UiResult | DeviceMenuResult | tuple[DeviceMenuResult, int]]:
"""Show the device menu."""
@@ -699,7 +700,7 @@ def show_info(
def show_info_with_cancel(
*,
title: str,
- items: list[PropertyType],
+ items: Sequence[PropertyType],
horizontal: bool = False,
chunkify: bool = False,
) -> LayoutObj[UiResult]:
@@ -751,7 +752,7 @@ def show_progress_coinjoin(
def show_properties(
*,
title: str,
- value: list[PropertyType] | str,
+ value: Sequence[PropertyType] | str,
) -> LayoutObj[None]:
"""Show a list of key-value pairs, or a monospace string."""
diff --git a/core/mocks/generated/trezorutils.pyi b/core/mocks/generated/trezorutils.pyi
index c2809a8e..8562c25f 100644
--- a/core/mocks/generated/trezorutils.pyi
+++ b/core/mocks/generated/trezorutils.pyi
@@ -1,4 +1,5 @@
from typing import *
+from buffer_types import *
# upymod/modtrezorutils/modtrezorutils-meminfo.h
@@ -9,7 +10,7 @@ def meminfo(filename: str | None) -> None:
# upymod/modtrezorutils/modtrezorutils.c
-def consteq(sec: bytes, pub: bytes) -> bool:
+def consteq(sec: AnyBytes, pub: AnyBytes) -> bool:
"""
Compares the private information in `sec` with public, user-provided
information in `pub`. Runs in constant time, corresponding to a length
@@ -20,9 +21,9 @@ def consteq(sec: bytes, pub: bytes) -> bool:
# upymod/modtrezorutils/modtrezorutils.c
def memcpy(
- dst: bytearray | memoryview,
+ dst: AnyBuffer,
dst_ofs: int,
- src: bytes,
+ src: AnyBytes,
src_ofs: int,
n: int | None = None,
) -> int:
@@ -36,7 +37,7 @@ def memcpy(
# upymod/modtrezorutils/modtrezorutils.c
def memzero(
- dst: bytearray | memoryview,
+ dst: AnyBuffer,
) -> None:
"""
Zeroes all bytes at `dst`.
@@ -52,7 +53,7 @@ def halt(msg: str | None = None) -> None:
# upymod/modtrezorutils/modtrezorutils.c
def firmware_hash(
- challenge: bytes | None = None,
+ challenge: AnyBytes | None = None,
callback: Callable[[int, int], None] | None = None,
) -> bytes:
"""
@@ -152,7 +153,7 @@ if __debug__:
# upymod/modtrezorutils/modtrezorutils.c
def reboot_to_bootloader(
boot_command : int = 0,
- boot_args : bytes | None = None,
+ boot_args : AnyBytes | None = None,
) -> None:
"""
Reboots to bootloader.
@@ -164,12 +165,12 @@ VersionTuple = Tuple[int, int, int, int]
class FirmwareHeaderInfo(NamedTuple):
version: VersionTuple
vendor: str
- fingerprint: bytes
- hash: bytes
+ fingerprint: AnyBytes
+ hash: AnyBytes
# upymod/modtrezorutils/modtrezorutils.c
-def check_firmware_header(header : bytes) -> FirmwareHeaderInfo:
+def check_firmware_header(header : AnyBytes) -> FirmwareHeaderInfo:
"""Parses incoming firmware header and returns information about it."""
diff --git a/core/mocks/ubinascii.pyi b/core/mocks/ubinascii.pyi
index 0d1ddf03..969d21dd 100644
--- a/core/mocks/ubinascii.pyi
+++ b/core/mocks/ubinascii.pyi
@@ -1,7 +1,7 @@
-from typing import AnyStr
+from buffer_types import AnyBytes, StrOrBytes
-def hexlify(data: bytes, sep: bytes = ...) -> bytes: ...
-def unhexlify(data: AnyStr) -> bytes: ...
-def a2b_base64(data: bytes) -> bytes: ...
-def b2a_base64(data: bytes) -> bytes: ...
-def crc32(data: bytes, crc: int = ...) -> int: ...
+def hexlify(data: AnyBytes, sep: AnyBytes = ...) -> bytes: ...
+def unhexlify(data: StrOrBytes) -> bytes: ...
+def a2b_base64(data: AnyBytes) -> bytes: ...
+def b2a_base64(data: AnyBytes) -> bytes: ...
+def crc32(data: AnyBytes, crc: int = ...) -> int: ...
diff --git a/core/mocks/uctypes.pyi b/core/mocks/uctypes.pyi
index 91556a52..bb786005 100644
--- a/core/mocks/uctypes.pyi
+++ b/core/mocks/uctypes.pyi
@@ -1,3 +1,5 @@
+from buffer_types import *
+
ARRAY: int
NATIVE: int
LITTLE_ENDIAN: int
@@ -27,6 +29,6 @@ class struct:
StructDict = dict[str, int | tuple[int, int]]
def sizeof(struct: struct | bytearray | StructDict, endianity: int = LITTLE_ENDIAN, /) -> int: ...
-def addressof(obj: bytes) -> int: ...
+def addressof(obj: AnyBytes) -> int: ...
def bytes_at(addr: int, size: int) -> bytes: ...
def bytearray_at(addr: int, size: int) -> bytearray: ...
diff --git a/core/mocks/ustruct.pyi b/core/mocks/ustruct.pyi
index f61a28ad..99821c2c 100644
--- a/core/mocks/ustruct.pyi
+++ b/core/mocks/ustruct.pyi
@@ -1,7 +1,8 @@
from typing import *
+from buffer_types import *
def calcsize(fmt: str) -> int: ...
def pack(fmt: str, *args: Any) -> bytes: ...
-def pack_into(fmt: str, buffer: bytearray, offset: int, *args: Any) -> None: ...
-def unpack(fmt: str, data: bytes) -> Tuple: ...
-def unpack_from(fmt: str, data: bytes, offset: int = ...) -> Tuple: ...
+def pack_into(fmt: str, buffer: AnyBuffer, offset: int, *args: Any) -> None: ...
+def unpack(fmt: str, data: AnyBytes) -> Tuple: ...
+def unpack_from(fmt: str, data: AnyBytes, offset: int = ...) -> Tuple: ...
diff --git a/core/src/apps/base.py b/core/src/apps/base.py
index 0490f5b6..0872cbb2 100644
--- a/core/src/apps/base.py
+++ b/core/src/apps/base.py
@@ -503,6 +503,7 @@ async def handle_UnlockPath(msg: UnlockPath) -> protobuf.MessageType:
req = await call_any(UnlockedPathRequest(mac=expected_mac), *wire_types)
assert req.MESSAGE_WIRE_TYPE in wire_types
+ assert req.MESSAGE_WIRE_TYPE is not None
handler = workflow_handlers.find_registered_handler(req.MESSAGE_WIRE_TYPE)
assert handler is not None
return await handler(req, msg) # type: ignore [Expected 1 positional argument]
diff --git a/core/src/apps/bitcoin/addresses.py b/core/src/apps/bitcoin/addresses.py
index 9a47076e..fd34e00b 100644
--- a/core/src/apps/bitcoin/addresses.py
+++ b/core/src/apps/bitcoin/addresses.py
@@ -13,6 +13,9 @@ from .multisig import multisig_get_pubkeys, multisig_pubkey_index
from .scripts import output_script_native_segwit, write_output_script_multisig
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+ from typing import Sequence
+
from trezor.crypto import bip32
from trezor.messages import MultisigRedeemScriptType
@@ -87,7 +90,7 @@ def get_address(
raise ProcessError("Invalid script type")
-def _address_multisig_p2sh(pubkeys: list[bytes], m: int, coin: CoinInfo) -> str:
+def _address_multisig_p2sh(pubkeys: Sequence[AnyBytes], m: int, coin: CoinInfo) -> str:
if coin.address_type_p2sh is None:
raise ProcessError("Multisig not enabled on this coin")
redeem_script = HashWriter(coin.script_hash())
@@ -96,7 +99,7 @@ def _address_multisig_p2sh(pubkeys: list[bytes], m: int, coin: CoinInfo) -> str:
def _address_multisig_p2wsh_in_p2sh(
- pubkeys: list[bytes], m: int, coin: CoinInfo
+ pubkeys: Sequence[AnyBytes], m: int, coin: CoinInfo
) -> str:
if coin.address_type_p2sh is None:
raise ProcessError("Multisig not enabled on this coin")
@@ -105,7 +108,7 @@ def _address_multisig_p2wsh_in_p2sh(
return _address_p2wsh_in_p2sh(witness_script_h.get_digest(), coin)
-def _address_multisig_p2wsh(pubkeys: list[bytes], m: int, hrp: str) -> str:
+def _address_multisig_p2wsh(pubkeys: Sequence[AnyBytes], m: int, hrp: str) -> str:
if not hrp:
raise ProcessError("Multisig not enabled on this coin")
witness_script_h = HashWriter(sha256())
diff --git a/core/src/apps/bitcoin/authorization.py b/core/src/apps/bitcoin/authorization.py
index 17312fad..d7a5b163 100644
--- a/core/src/apps/bitcoin/authorization.py
+++ b/core/src/apps/bitcoin/authorization.py
@@ -34,7 +34,7 @@ class CoinJoinAuthorization:
and msg.address_n[:-BIP32_WALLET_DEPTH] == params.address_n
and msg.coin_name == params.coin_name
and msg.script_type == params.script_type
- and msg.commitment_data.startswith(bytes(coordinator))
+ and bytes(msg.commitment_data).startswith(bytes(coordinator))
)
def check_internal_input(self, txi: TxInput) -> bool:
diff --git a/core/src/apps/bitcoin/common.py b/core/src/apps/bitcoin/common.py
index f2c72aa3..95e65b60 100644
--- a/core/src/apps/bitcoin/common.py
+++ b/core/src/apps/bitcoin/common.py
@@ -9,6 +9,7 @@ from trezor.messages import MultisigRedeemScriptType
from trezor.utils import ensure
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from enum import IntEnum
from trezor.crypto import bip32
@@ -105,7 +106,7 @@ NONSEGWIT_INPUT_SCRIPT_TYPES = (
)
-def ecdsa_sign(node: bip32.HDNode, digest: bytes) -> bytes:
+def ecdsa_sign(node: bip32.HDNode, digest: bytes) -> AnyBytes:
from trezor.crypto import der
from trezor.crypto.curve import secp256k1
@@ -120,7 +121,7 @@ def bip340_sign(node: bip32.HDNode, digest: bytes) -> bytes:
return bip340.sign(output_private_key, digest)
-def ecdsa_hash_pubkey(pubkey: bytes, coin: CoinInfo) -> bytes:
+def ecdsa_hash_pubkey(pubkey: AnyBytes, coin: CoinInfo) -> bytes:
ensure(
coin.curve_name.startswith("secp256k1")
) # The following code makes sense only for Weiersrass curves
diff --git a/core/src/apps/bitcoin/get_ownership_proof.py b/core/src/apps/bitcoin/get_ownership_proof.py
index 1bb2fe27..90e716b1 100644
--- a/core/src/apps/bitcoin/get_ownership_proof.py
+++ b/core/src/apps/bitcoin/get_ownership_proof.py
@@ -3,6 +3,8 @@ from typing import TYPE_CHECKING
from .keychain import with_keychain
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import GetOwnershipProof, OwnershipProof
from apps.common.coininfo import CoinInfo
@@ -31,7 +33,7 @@ async def get_ownership_proof(
from .ownership import generate_proof, get_identifier
script_type = msg.script_type # local_cache_attribute
- ownership_ids = msg.ownership_ids # local_cache_attribute
+ ownership_ids: list[AnyBytes] = msg.ownership_ids # local_cache_attribute
if authorization:
if not authorization.check_get_ownership_proof(msg):
diff --git a/core/src/apps/bitcoin/multisig.py b/core/src/apps/bitcoin/multisig.py
index c294c2d8..074286c7 100644
--- a/core/src/apps/bitcoin/multisig.py
+++ b/core/src/apps/bitcoin/multisig.py
@@ -4,6 +4,9 @@ from trezor.enums import MultisigPubkeysOrder
from trezor.wire import DataError
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+ from typing import Sequence
+
from trezor.messages import HDNodeType, MultisigRedeemScriptType
from apps.common import paths
@@ -31,7 +34,7 @@ def multisig_fingerprint(multisig: MultisigRedeemScriptType) -> bytes:
if multisig.pubkeys_order == MultisigPubkeysOrder.LEXICOGRAPHIC:
# If the order of pubkeys is lexicographic, we don't want the fingerprint to depend on the order of the pubnodes, so we sort the pubnodes before hashing.
- pubnodes.sort(key=lambda n: n.public_key + n.chain_code)
+ pubnodes.sort(key=lambda n: n.public_key + n.chain_code) # type: ignore [Operator "+" not supported]
h = HashWriter(sha256())
write_uint32(h, m)
@@ -94,7 +97,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) -> Sequence[AnyBytes]:
validate_multisig(multisig)
if multisig.nodes:
pubkeys = [multisig_get_pubkey(hd, multisig.address_n) for hd in multisig.nodes]
diff --git a/core/src/apps/bitcoin/ownership.py b/core/src/apps/bitcoin/ownership.py
index 0305b803..9248906c 100644
--- a/core/src/apps/bitcoin/ownership.py
+++ b/core/src/apps/bitcoin/ownership.py
@@ -12,6 +12,8 @@ from apps.common.readers import read_compact_size
from .scripts import read_bip322_signature_proof
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.crypto import bip32
from trezor.enums import InputScriptType
from trezor.messages import MultisigRedeemScriptType
@@ -35,10 +37,10 @@ def generate_proof(
multisig: MultisigRedeemScriptType | None,
coin: CoinInfo,
user_confirmed: bool,
- ownership_ids: list[bytes],
- script_pubkey: bytes,
- commitment_data: bytes,
-) -> tuple[bytes, bytes]:
+ ownership_ids: list[AnyBytes],
+ script_pubkey: AnyBytes,
+ commitment_data: AnyBytes,
+) -> tuple[AnyBytes, AnyBytes]:
from trezor.enums import InputScriptType
from apps.bitcoin.writers import write_bytes_fixed, write_compact_size, write_uint8
@@ -81,9 +83,9 @@ def generate_proof(
def verify_nonownership(
- proof: bytes,
- script_pubkey: bytes,
- commitment_data: bytes | None,
+ proof: AnyBytes,
+ script_pubkey: AnyBytes,
+ commitment_data: AnyBytes | None,
keychain: Keychain,
coin: CoinInfo,
) -> bool:
@@ -128,7 +130,7 @@ def verify_nonownership(
return not_owned
-def read_scriptsig_witness(ownership_proof: bytes) -> tuple[memoryview, memoryview]:
+def read_scriptsig_witness(ownership_proof: AnyBytes) -> tuple[memoryview, memoryview]:
try:
r = utils.BufferReader(ownership_proof)
if r.read_memoryview(4) != _VERSION_MAGIC:
@@ -148,7 +150,7 @@ def read_scriptsig_witness(ownership_proof: bytes) -> tuple[memoryview, memoryvi
raise DataError("Invalid proof of ownership")
-def get_identifier(script_pubkey: bytes, keychain: Keychain) -> bytes:
+def get_identifier(script_pubkey: AnyBytes, keychain: Keychain) -> bytes:
from trezor.crypto import hmac
# k = Key(m/"SLIP-0019"/"Ownership identification key")
diff --git a/core/src/apps/bitcoin/scripts.py b/core/src/apps/bitcoin/scripts.py
index e0ded0d4..f2981690 100644
--- a/core/src/apps/bitcoin/scripts.py
+++ b/core/src/apps/bitcoin/scripts.py
@@ -22,6 +22,7 @@ from .writers import (
)
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Sequence
from trezor.messages import MultisigRedeemScriptType, TxInput
@@ -38,7 +39,7 @@ def write_input_script_prefixed(
coin: CoinInfo,
sighash_type: SigHashType,
pubkey: bytes,
- signature: bytes,
+ signature: AnyBytes,
) -> None:
from trezor import wire
from trezor.crypto.hashlib import sha256
@@ -79,7 +80,7 @@ def write_input_script_prefixed(
raise wire.ProcessError("Invalid script type")
-def output_derive_script(address: str, coin: CoinInfo) -> bytes:
+def output_derive_script(address: str, coin: CoinInfo) -> AnyBytes:
if coin.bech32_prefix and address.startswith(coin.bech32_prefix):
# p2wpkh or p2wsh or p2tr
witver, witprog = common.decode_bech32_address(coin.bech32_prefix, address)
@@ -124,7 +125,7 @@ def output_derive_script(address: str, coin: CoinInfo) -> bytes:
def write_bip143_script_code_prefixed(
w: Writer,
txi: TxInput,
- public_keys: Sequence[bytes | memoryview],
+ public_keys: Sequence[AnyBytes],
threshold: int,
coin: CoinInfo,
) -> None:
@@ -154,7 +155,7 @@ def write_bip143_script_code_prefixed(
def write_input_script_p2pkh_or_p2sh_prefixed(
- w: Writer, pubkey: bytes, signature: bytes, sighash_type: SigHashType
+ w: Writer, pubkey: AnyBytes, signature: AnyBytes, sighash_type: SigHashType
) -> None:
write_compact_size(w, 1 + len(signature) + 1 + 1 + len(pubkey))
append_signature(w, signature, sighash_type)
@@ -162,7 +163,7 @@ def write_input_script_p2pkh_or_p2sh_prefixed(
def parse_input_script_p2pkh(
- script_sig: bytes,
+ script_sig: AnyBytes,
) -> tuple[memoryview, memoryview, SigHashType]:
try:
r = BufferReader(script_sig)
@@ -181,7 +182,7 @@ def parse_input_script_p2pkh(
def write_output_script_p2pkh(
- w: Writer, pubkeyhash: bytes, prefixed: bool = False
+ w: Writer, pubkeyhash: AnyBytes, prefixed: bool = False
) -> None:
append = w.append # local_cache_attribute
@@ -195,13 +196,13 @@ def write_output_script_p2pkh(
append(0xAC) # OP_CHECKSIG
-def output_script_p2pkh(pubkeyhash: bytes) -> bytearray:
+def output_script_p2pkh(pubkeyhash: AnyBytes) -> bytearray:
s = empty_bytearray(25)
write_output_script_p2pkh(s, pubkeyhash)
return s
-def output_script_p2sh(scripthash: bytes) -> bytearray:
+def output_script_p2sh(scripthash: AnyBytes) -> bytearray:
# A9 14 <scripthash> 87
utils.ensure(len(scripthash) == 20)
s = bytearray(23)
@@ -233,7 +234,7 @@ def _input_script_native_segwit() -> bytearray:
return bytearray(0)
-def output_script_native_segwit(witver: int, witprog: bytes) -> bytearray:
+def output_script_native_segwit(witver: int, witprog: AnyBytes) -> bytearray:
# Either:
# 00 14 <20-byte-key-hash>
# 00 20 <32-byte-script-hash>
@@ -248,7 +249,7 @@ def output_script_native_segwit(witver: int, witprog: bytes) -> bytearray:
return w
-def parse_output_script_p2tr(script_pubkey: bytes) -> memoryview:
+def parse_output_script_p2tr(script_pubkey: AnyBytes) -> memoryview:
# 51 20 <32-byte-taproot-output-key>
try:
r = BufferReader(script_pubkey)
@@ -319,14 +320,16 @@ def write_input_script_p2wsh_in_p2sh(
def write_witness_p2wpkh(
- w: Writer, signature: bytes, pubkey: bytes, sighash_type: SigHashType
+ w: Writer, signature: AnyBytes, pubkey: AnyBytes, sighash_type: SigHashType
) -> None:
write_compact_size(w, 0x02) # num of segwit items, in P2WPKH it's always 2
write_signature_prefixed(w, signature, sighash_type)
write_bytes_prefixed(w, pubkey)
-def parse_witness_p2wpkh(witness: bytes) -> tuple[memoryview, memoryview, SigHashType]:
+def parse_witness_p2wpkh(
+ witness: AnyBytes,
+) -> tuple[memoryview, memoryview, SigHashType]:
try:
r = BufferReader(witness)
@@ -350,7 +353,7 @@ def parse_witness_p2wpkh(witness: bytes) -> tuple[memoryview, memoryview, SigHas
def write_witness_multisig(
w: Writer,
multisig: MultisigRedeemScriptType,
- signature: bytes,
+ signature: AnyBytes,
signature_index: int,
sighash_type: SigHashType,
) -> None:
@@ -385,7 +388,7 @@ def write_witness_multisig(
def parse_witness_multisig(
- witness: bytes,
+ witness: AnyBytes,
) -> tuple[memoryview, list[tuple[memoryview, SigHashType]]]:
try:
r = BufferReader(witness)
@@ -417,13 +420,15 @@ def parse_witness_multisig(
# ===
-def write_witness_p2tr(w: Writer, signature: bytes, sighash_type: SigHashType) -> None:
+def write_witness_p2tr(
+ w: Writer, signature: AnyBytes, sighash_type: SigHashType
+) -> None:
# Taproot key path spending without annex.
write_compact_size(w, 0x01) # num of segwit items
write_signature_prefixed(w, signature, sighash_type)
-def parse_witness_p2tr(witness: bytes) -> tuple[memoryview, SigHashType]:
+def parse_witness_p2tr(witness: AnyBytes) -> tuple[memoryview, SigHashType]:
try:
r = BufferReader(witness)
@@ -458,7 +463,7 @@ def parse_witness_p2tr(witness: bytes) -> tuple[memoryview, SigHashType]:
def _write_input_script_multisig_prefixed(
w: Writer,
multisig: MultisigRedeemScriptType,
- signature: bytes,
+ signature: AnyBytes,
signature_index: int,
sighash_type: SigHashType,
coin: CoinInfo,
@@ -497,7 +502,7 @@ def _write_input_script_multisig_prefixed(
def parse_input_script_multisig(
- script_sig: bytes,
+ script_sig: AnyBytes,
) -> tuple[memoryview, list[tuple[memoryview, SigHashType]]]:
try:
r = BufferReader(script_sig)
@@ -523,7 +528,7 @@ def parse_input_script_multisig(
return script, signatures
-def output_script_multisig(pubkeys: list[bytes], m: int) -> bytearray:
+def output_script_multisig(pubkeys: Sequence[AnyBytes], m: int) -> bytearray:
w = empty_bytearray(output_script_multisig_length(pubkeys, m))
write_output_script_multisig(w, pubkeys, m)
return w
@@ -531,7 +536,7 @@ def output_script_multisig(pubkeys: list[bytes], m: int) -> bytearray:
def write_output_script_multisig(
w: Writer,
- pubkeys: Sequence[bytes | memoryview],
+ pubkeys: Sequence[AnyBytes],
m: int,
prefixed: bool = False,
) -> None:
@@ -552,11 +557,11 @@ def write_output_script_multisig(
w.append(0xAE) # OP_CHECKMULTISIG
-def output_script_multisig_length(pubkeys: Sequence[bytes | memoryview], m: int) -> int:
+def output_script_multisig_length(pubkeys: Sequence[AnyBytes], m: int) -> int:
return 1 + len(pubkeys) * (1 + 33) + 1 + 1 # see output_script_multisig
-def parse_output_script_multisig(script: bytes) -> tuple[list[memoryview], int]:
+def parse_output_script_multisig(script: AnyBytes) -> tuple[list[memoryview], int]:
try:
r = BufferReader(script)
@@ -593,7 +598,7 @@ def parse_output_script_multisig(script: bytes) -> tuple[list[memoryview], int]:
# ===
-def output_script_paytoopreturn(data: bytes) -> bytearray:
+def output_script_paytoopreturn(data: AnyBytes) -> bytearray:
w = empty_bytearray(1 + 5 + len(data))
w.append(0x6A) # OP_RETURN
write_op_push(w, len(data))
@@ -612,7 +617,7 @@ def write_bip322_signature_proof(
multisig: MultisigRedeemScriptType | None,
coin: CoinInfo,
public_key: bytes,
- signature: bytes,
+ signature: AnyBytes,
) -> None:
write_input_script_prefixed(
w, script_type, multisig, coin, SigHashType.SIGHASH_ALL, public_key, signature
@@ -645,7 +650,7 @@ def read_bip322_signature_proof(r: BufferReader) -> tuple[memoryview, memoryview
def write_signature_prefixed(
- w: Writer, signature: bytes, sighash_type: SigHashType
+ w: Writer, signature: AnyBytes, sighash_type: SigHashType
) -> None:
length = len(signature)
if sighash_type != SigHashType.SIGHASH_ALL_TAPROOT:
@@ -657,12 +662,12 @@ def write_signature_prefixed(
w.append(sighash_type)
-def append_signature(w: Writer, signature: bytes, sighash_type: SigHashType) -> None:
+def append_signature(w: Writer, signature: AnyBytes, sighash_type: SigHashType) -> None:
write_op_push(w, len(signature) + 1)
write_bytes_unchecked(w, signature)
w.append(sighash_type)
-def append_pubkey(w: Writer, pubkey: bytes | memoryview) -> None:
+def append_pubkey(w: Writer, pubkey: AnyBytes) -> None:
write_op_push(w, len(pubkey))
write_bytes_unchecked(w, pubkey)
diff --git a/core/src/apps/bitcoin/scripts_decred.py b/core/src/apps/bitcoin/scripts_decred.py
index d8671d58..067a7687 100644
--- a/core/src/apps/bitcoin/scripts_decred.py
+++ b/core/src/apps/bitcoin/scripts_decred.py
@@ -24,6 +24,8 @@ _OP_SSTXCHANGE = const(0xBD)
_STAKE_TREE = const(1)
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.enums import InputScriptType
from trezor.messages import MultisigRedeemScriptType
@@ -40,7 +42,7 @@ def write_input_script_prefixed(
coin: CoinInfo,
sighash_type: SigHashType,
pubkey: bytes,
- signature: bytes,
+ signature: AnyBytes,
) -> None:
from trezor import wire
from trezor.enums import InputScriptType
@@ -66,7 +68,7 @@ def write_input_script_prefixed(
def _write_input_script_multisig_prefixed(
w: Writer,
multisig: MultisigRedeemScriptType,
- signature: bytes,
+ signature: AnyBytes,
signature_index: int,
sighash_type: SigHashType,
coin: CoinInfo,
@@ -143,7 +145,7 @@ def write_output_script_ssgen_prefixed(w: Writer, pkh: bytes) -> None:
# Stake commitment OPRETURN.
-def sstxcommitment_pkh(pkh: bytes, amount: int) -> bytes:
+def sstxcommitment_pkh(pkh: bytes, amount: int) -> AnyBytes:
from apps.common.writers import write_bytes_fixed, write_uint64_le
w = utils.empty_bytearray(30)
@@ -172,7 +174,7 @@ def output_script_p2sh(scripthash: bytes) -> bytearray:
def output_derive_script(
tree: int | None, stakeType: int | None, addr: str, coin: CoinInfo
-) -> bytes:
+) -> AnyBytes:
from trezor.crypto import base58
from apps.common import address_type
diff --git a/core/src/apps/bitcoin/sign_tx/approvers.py b/core/src/apps/bitcoin/sign_tx/approvers.py
index 83f2b615..0459de49 100644
--- a/core/src/apps/bitcoin/sign_tx/approvers.py
+++ b/core/src/apps/bitcoin/sign_tx/approvers.py
@@ -12,6 +12,7 @@ from . import helpers, tx_weight
from .tx_info import OriginalTxInfo
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Optional
from trezor.crypto import bip32
@@ -84,7 +85,7 @@ class Approver:
if txi.orig_hash:
self.orig_external_in += txi.amount
- async def _add_output(self, txo: TxOutput, script_pubkey: bytes) -> None:
+ async def _add_output(self, txo: TxOutput, script_pubkey: AnyBytes) -> None:
self.weight.add_output(script_pubkey)
self.total_out += txo.amount
@@ -107,7 +108,7 @@ class Approver:
self.payment_req_verifier.verify()
self.payment_req_verifier = None
- async def add_change_output(self, txo: TxOutput, script_pubkey: bytes) -> None:
+ async def add_change_output(self, txo: TxOutput, script_pubkey: AnyBytes) -> None:
await self._add_output(txo, script_pubkey)
self.change_out += txo.amount
if self.payment_req_verifier:
@@ -122,7 +123,7 @@ class Approver:
async def add_external_output(
self,
txo: TxOutput,
- script_pubkey: bytes,
+ script_pubkey: AnyBytes,
tx_info: TxInfo | None,
orig_txo: TxOutput | None = None,
) -> None:
@@ -177,7 +178,7 @@ class BasicApprover(Approver):
):
raise ProcessError("Transaction has changed during signing")
- async def _add_output(self, txo: TxOutput, script_pubkey: bytes) -> None:
+ async def _add_output(self, txo: TxOutput, script_pubkey: AnyBytes) -> None:
if txo.address_n and not validate_path_against_script_type(
self.coin,
address_n=txo.address_n,
@@ -188,14 +189,14 @@ class BasicApprover(Approver):
await super()._add_output(txo, script_pubkey)
- async def add_change_output(self, txo: TxOutput, script_pubkey: bytes) -> None:
+ async def add_change_output(self, txo: TxOutput, script_pubkey: AnyBytes) -> None:
await super().add_change_output(txo, script_pubkey)
self.change_count += 1
async def add_external_output(
self,
txo: TxOutput,
- script_pubkey: bytes,
+ script_pubkey: AnyBytes,
tx_info: TxInfo | None,
orig_txo: TxOutput | None = None,
) -> None:
diff --git a/core/src/apps/bitcoin/sign_tx/bitcoin.py b/core/src/apps/bitcoin/sign_tx/bitcoin.py
index 4f2bdbe2..8ee52c13 100644
--- a/core/src/apps/bitcoin/sign_tx/bitcoin.py
+++ b/core/src/apps/bitcoin/sign_tx/bitcoin.py
@@ -20,6 +20,7 @@ from .progress import progress
from .tx_info import OriginalTxInfo
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Sequence
from trezor.crypto import bip32
@@ -366,7 +367,9 @@ class Bitcoin:
):
raise DataError("Invalid external input")
- async def process_original_input(self, txi: TxInput, script_pubkey: bytes) -> None:
+ async def process_original_input(
+ self, txi: TxInput, script_pubkey: AnyBytes
+ ) -> None:
orig_hash = txi.orig_hash # local_cache_attribute
orig_index = txi.orig_index # local_cache_attribute
@@ -413,7 +416,7 @@ class Bitcoin:
orig.index += 1
async def fetch_removed_original_outputs(
- self, orig: OriginalTxInfo, orig_hash: bytes, last_index: int
+ self, orig: OriginalTxInfo, orig_hash: AnyBytes, last_index: int
) -> None:
while orig.index < last_index:
txo = await request_tx_output(self.tx_req, orig.index, self.coin, orig_hash)
@@ -431,7 +434,7 @@ class Bitcoin:
orig.index += 1
async def get_original_output(
- self, txo: TxOutput, script_pubkey: bytes
+ self, txo: TxOutput, script_pubkey: AnyBytes
) -> TxOutput:
orig_hash = txo.orig_hash # local_cache_attribute
orig_index = txo.orig_index # local_cache_attribute
@@ -508,7 +511,7 @@ class Bitcoin:
async def approve_output(
self,
txo: TxOutput,
- script_pubkey: bytes,
+ script_pubkey: AnyBytes,
orig_txo: TxOutput | None,
) -> None:
payment_req_index = txo.payment_req_index # local_cache_attribute
@@ -541,9 +544,9 @@ class Bitcoin:
i: int,
txi: TxInput,
tx_info: TxInfo | OriginalTxInfo,
- public_keys: Sequence[bytes | memoryview],
+ public_keys: Sequence[AnyBytes],
threshold: int,
- script_pubkey: bytes,
+ script_pubkey: AnyBytes,
) -> bytes:
if txi.witness:
if common.input_is_taproot(txi):
@@ -566,7 +569,7 @@ class Bitcoin:
return digest
async def verify_presigned_external_input(
- self, i: int, txi: TxInput, script_pubkey: bytes
+ self, i: int, txi: TxInput, script_pubkey: AnyBytes
) -> None:
verifier = SignatureVerifier(
script_pubkey, txi.script_sig, txi.witness, self.coin
@@ -610,7 +613,7 @@ class Bitcoin:
self.write_tx_input_derived(self.serialized_tx, txi, key_sign_pub, b"")
- def sign_bip143_input(self, i: int, txi: TxInput) -> tuple[bytes, bytes]:
+ def sign_bip143_input(self, i: int, txi: TxInput) -> tuple[bytes, AnyBytes]:
if self.taproot_only:
# Prevents an attacker from bypassing prev tx checking by providing a different
# script type than the one that was provided during the confirmation phase.
@@ -694,7 +697,7 @@ class Bitcoin:
self,
index: int,
tx_info: TxInfo | OriginalTxInfo,
- script_pubkey: bytes | None = None,
+ script_pubkey: AnyBytes | None = None,
) -> tuple[bytes, TxInput, bip32.HDNode | None]:
tx = tx_info.tx # local_cache_attribute
coin = self.coin # local_cache_attribute
@@ -793,8 +796,8 @@ class Bitcoin:
self.write_tx_output(self.serialized_tx, txo, script_pubkey)
async def get_prevtx_output(
- self, prev_hash: bytes, prev_index: int
- ) -> tuple[int, bytes]:
+ self, prev_hash: AnyBytes, prev_index: int
+ ) -> tuple[int, AnyBytes]:
coin = self.coin # local_cache_attribute
amount_out = 0 # output amount
@@ -820,7 +823,7 @@ class Bitcoin:
write_compact_size(txh, tx.outputs_count)
- script_pubkey: bytes | None = None
+ script_pubkey: AnyBytes | None = None
for i in range(tx.outputs_count):
# STAGE_REQUEST_3_PREV_OUTPUT in legacy
progress.advance_prev_tx()
@@ -868,7 +871,7 @@ class Bitcoin:
w: Writer,
txi: TxInput,
pubkey: bytes,
- signature: bytes,
+ signature: AnyBytes,
) -> None:
writers.write_bytes_reversed(w, txi.prev_hash, writers.TX_HASH_SIZE)
writers.write_uint32(w, txi.prev_index)
@@ -887,7 +890,7 @@ class Bitcoin:
def write_tx_input(
w: Writer,
txi: TxInput | PrevInput,
- script: bytes,
+ script: AnyBytes,
) -> None:
writers.write_tx_input(w, txi, script)
@@ -895,7 +898,7 @@ class Bitcoin:
def write_tx_output(
w: Writer,
txo: TxOutput | PrevOutput,
- script_pubkey: bytes,
+ script_pubkey: AnyBytes,
) -> None:
writers.write_tx_output(w, txo, script_pubkey)
@@ -914,11 +917,11 @@ class Bitcoin:
writers.write_uint32(w, tx.lock_time)
async def write_prev_tx_footer(
- self, w: Writer, tx: PrevTx, prev_hash: bytes
+ self, w: Writer, tx: PrevTx, prev_hash: AnyBytes
) -> None:
self.write_tx_footer(w, tx)
- def set_serialized_signature(self, index: int, signature: bytes) -> None:
+ def set_serialized_signature(self, index: int, signature: AnyBytes) -> None:
serialized = self.tx_req.serialized # local_cache_attribute
# Only one signature per TxRequest can be serialized.
@@ -933,7 +936,7 @@ class Bitcoin:
def input_derive_script(
self, txi: TxInput, node: bip32.HDNode | None = None
- ) -> bytes:
+ ) -> AnyBytes:
if input_is_external(txi):
assert txi.script_pubkey is not None # checked in _sanitize_tx_input
return txi.script_pubkey
@@ -944,7 +947,7 @@ class Bitcoin:
address = addresses.get_address(txi.script_type, self.coin, node, txi.multisig)
return scripts.output_derive_script(address, self.coin)
- def output_derive_script(self, txo: TxOutput) -> bytes:
+ def output_derive_script(self, txo: TxOutput) -> AnyBytes:
if txo.script_type == OutputScriptType.PAYTOOPRETURN:
assert txo.op_return_data is not None # checked in _sanitize_tx_output
return scripts.output_script_paytoopreturn(txo.op_return_data)
diff --git a/core/src/apps/bitcoin/sign_tx/decred.py b/core/src/apps/bitcoin/sign_tx/decred.py
index f0613f47..d6351c21 100644
--- a/core/src/apps/bitcoin/sign_tx/decred.py
+++ b/core/src/apps/bitcoin/sign_tx/decred.py
@@ -26,6 +26,7 @@ OUTPUT_SCRIPT_NULL_SSTXCHANGE = (
)
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Sequence
from trezor.crypto import bip32
@@ -88,7 +89,7 @@ class DecredApprover(BasicApprover):
self.weight = DecredTxWeightCalculator()
async def add_decred_sstx_submission(
- self, txo: TxOutput, script_pubkey: bytes
+ self, txo: TxOutput, script_pubkey: AnyBytes
) -> None:
# NOTE: The following calls Approver.add_external_output(), not BasicApprover.add_external_output().
# This is needed to skip calling helpers.confirm_output(), which is what BasicApprover would do.
@@ -102,16 +103,16 @@ class DecredSigHasher:
def __init__(self, h_prefix: HashWriter) -> None:
self.h_prefix = h_prefix
- def add_input(self, txi: TxInput, script_pubkey: bytes) -> None:
+ def add_input(self, txi: TxInput, script_pubkey: AnyBytes) -> None:
Decred.write_tx_input(self.h_prefix, txi, bytes())
- def add_output(self, txo: TxOutput, script_pubkey: bytes) -> None:
+ def add_output(self, txo: TxOutput, script_pubkey: AnyBytes) -> None:
Decred.write_tx_output(self.h_prefix, txo, script_pubkey)
def hash143(
self,
txi: TxInput,
- public_keys: Sequence[bytes | memoryview],
+ public_keys: Sequence[AnyBytes],
threshold: int,
tx: SignTx | PrevTx,
coin: CoinInfo,
@@ -130,7 +131,7 @@ class DecredSigHasher:
def hash_zip244(
self,
txi: TxInput | None,
- script_pubkey: bytes | None,
+ script_pubkey: AnyBytes | None,
) -> bytes:
raise NotImplementedError
@@ -316,7 +317,7 @@ class Decred(Bitcoin):
def write_tx_output(
w: Writer,
txo: TxOutput | PrevOutput,
- script_pubkey: bytes,
+ script_pubkey: AnyBytes,
) -> None:
from trezor.messages import PrevOutput
@@ -409,7 +410,7 @@ class Decred(Bitcoin):
write_uint32(w, tx.expiry)
def write_tx_input_witness(
- self, w: Writer, txi: TxInput, pubkey: bytes, signature: bytes
+ self, w: Writer, txi: TxInput, pubkey: bytes, signature: AnyBytes
) -> None:
writers.write_uint64(w, txi.amount)
write_uint32(w, 0) # block height fraud proof
@@ -429,7 +430,7 @@ class Decred(Bitcoin):
def input_derive_script(
self, txi: TxInput, node: bip32.HDNode | None = None
- ) -> bytes:
+ ) -> AnyBytes:
if input_is_external(txi):
assert txi.script_pubkey is not None # checked in _sanitize_tx_input
return txi.script_pubkey
diff --git a/core/src/apps/bitcoin/sign_tx/helpers.py b/core/src/apps/bitcoin/sign_tx/helpers.py
index c32efead..fcda2476 100644
--- a/core/src/apps/bitcoin/sign_tx/helpers.py
+++ b/core/src/apps/bitcoin/sign_tx/helpers.py
@@ -18,6 +18,7 @@ from ..writers import TX_HASH_SIZE
from . import layout
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Any, Awaitable
from trezor.enums import AmountUnit
@@ -115,7 +116,7 @@ class UiConfirmPaymentRequest(UiConfirm):
class UiConfirmReplacement(UiConfirm):
- def __init__(self, title: str, txid: bytes) -> None:
+ def __init__(self, title: str, txid: AnyBytes) -> None:
self.title = title
self.txid = txid
@@ -278,7 +279,7 @@ def show_payment_request_details(provider_address: str, payment_req: PaymentRequ
return (yield UiConfirmPaymentRequest(provider_address, payment_req, coin, amount_unit, address_n)) # type: ignore [awaitable-return-type]
-def confirm_replacement(description: str, txid: bytes) -> Awaitable[Any]: # type: ignore [awaitable-return-type]
+def confirm_replacement(description: str, txid: AnyBytes) -> Awaitable[Any]: # type: ignore [awaitable-return-type]
return (yield UiConfirmReplacement(description, txid)) # type: ignore [awaitable-return-type]
@@ -326,7 +327,7 @@ def confirm_multiple_accounts() -> Awaitable[Any]: # type: ignore [awaitable-re
return (yield UiConfirmMultipleAccounts()) # type: ignore [awaitable-return-type]
-def request_tx_meta(tx_req: TxRequest, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[PrevTx]: # type: ignore [awaitable-return-type]
+def request_tx_meta(tx_req: TxRequest, coin: CoinInfo, tx_hash: AnyBytes | None = None) -> Awaitable[PrevTx]: # type: ignore [awaitable-return-type]
assert tx_req.details is not None
tx_req.request_type = RequestType.TXMETA
tx_req.details.tx_hash = tx_hash
@@ -336,7 +337,7 @@ def request_tx_meta(tx_req: TxRequest, coin: CoinInfo, tx_hash: bytes | None = N
def request_tx_extra_data(
- tx_req: TxRequest, offset: int, size: int, tx_hash: bytes | None = None
+ tx_req: TxRequest, offset: int, size: int, tx_hash: AnyBytes | None = None
) -> Awaitable[bytearray]: # type: ignore [awaitable-return-type]
details = tx_req.details # local_cache_attribute
@@ -350,7 +351,7 @@ def request_tx_extra_data(
return ack.tx.extra_data_chunk
-def request_tx_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[TxInput]: # type: ignore [awaitable-return-type]
+def request_tx_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: AnyBytes | None = None) -> Awaitable[TxInput]: # type: ignore [awaitable-return-type]
assert tx_req.details is not None
if tx_hash:
tx_req.request_type = RequestType.TXORIGINPUT
@@ -363,7 +364,7 @@ def request_tx_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes |
return _sanitize_tx_input(ack.tx.input, coin)
-def request_tx_prev_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[PrevInput]: # type: ignore [awaitable-return-type]
+def request_tx_prev_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: AnyBytes | None = None) -> Awaitable[PrevInput]: # type: ignore [awaitable-return-type]
assert tx_req.details is not None
tx_req.request_type = RequestType.TXINPUT
tx_req.details.request_index = i
@@ -373,7 +374,7 @@ def request_tx_prev_input(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: by
return _sanitize_tx_prev_input(ack.tx.input, coin)
-def request_tx_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[TxOutput]: # type: ignore [awaitable-return-type]
+def request_tx_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: AnyBytes | None = None) -> Awaitable[TxOutput]: # type: ignore [awaitable-return-type]
assert tx_req.details is not None
if tx_hash:
tx_req.request_type = RequestType.TXORIGOUTPUT
@@ -386,7 +387,7 @@ def request_tx_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes
return _sanitize_tx_output(ack.tx.output, coin)
-def request_tx_prev_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[PrevOutput]: # type: ignore [awaitable-return-type]
+def request_tx_prev_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: AnyBytes | None = None) -> Awaitable[PrevOutput]: # type: ignore [awaitable-return-type]
assert tx_req.details is not None
tx_req.request_type = RequestType.TXOUTPUT
tx_req.details.request_index = i
diff --git a/core/src/apps/bitcoin/sign_tx/layout.py b/core/src/apps/bitcoin/sign_tx/layout.py
index 40090c05..60adb1ba 100644
--- a/core/src/apps/bitcoin/sign_tx/layout.py
+++ b/core/src/apps/bitcoin/sign_tx/layout.py
@@ -18,6 +18,8 @@ from ..common import (
from ..keychain import address_n_to_name
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.enums import AmountUnit
from trezor.messages import PaymentRequest, TxOutput
from trezor.ui.layouts import PropertyType
@@ -222,7 +224,7 @@ async def show_payment_request_details(
)
-async def confirm_replacement(title: str, txid: bytes) -> None:
+async def confirm_replacement(title: str, txid: AnyBytes) -> None:
from ubinascii import hexlify
await layouts.confirm_replacement(
diff --git a/core/src/apps/bitcoin/sign_tx/omni.py b/core/src/apps/bitcoin/sign_tx/omni.py
index 433a78e0..9e840b92 100644
--- a/core/src/apps/bitcoin/sign_tx/omni.py
+++ b/core/src/apps/bitcoin/sign_tx/omni.py
@@ -1,4 +1,9 @@
from micropython import const
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
_OMNI_DECIMALS = const(8)
@@ -10,11 +15,11 @@ currencies = {
}
-def is_valid(data: bytes) -> bool:
+def is_valid(data: AnyBytes) -> bool:
return len(data) >= 8 and data[:4] == b"omni"
-def parse(data: bytes) -> str:
+def parse(data: AnyBytes) -> str:
from ustruct import unpack
from trezor import TR
diff --git a/core/src/apps/bitcoin/sign_tx/sig_hasher.py b/core/src/apps/bitcoin/sign_tx/sig_hasher.py
index 6b5d6555..0136262b 100644
--- a/core/src/apps/bitcoin/sign_tx/sig_hasher.py
+++ b/core/src/apps/bitcoin/sign_tx/sig_hasher.py
@@ -11,6 +11,7 @@ from ..writers import (
)
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Protocol, Sequence
from trezor.messages import PrevTx, SignTx, TxInput, TxOutput
@@ -20,14 +21,14 @@ if TYPE_CHECKING:
from ..common import SigHashType
class SigHasher(Protocol):
- def add_input(self, txi: TxInput, script_pubkey: bytes) -> None: ...
+ def add_input(self, txi: TxInput, script_pubkey: AnyBytes) -> None: ...
- def add_output(self, txo: TxOutput, script_pubkey: bytes) -> None: ...
+ def add_output(self, txo: TxOutput, script_pubkey: AnyBytes) -> None: ...
def hash143(
self,
txi: TxInput,
- public_keys: Sequence[bytes | memoryview],
+ public_keys: Sequence[AnyBytes],
threshold: int,
tx: SignTx | PrevTx,
coin: coininfo.CoinInfo,
@@ -44,7 +45,7 @@ if TYPE_CHECKING:
def hash_zip244(
self,
txi: TxInput | None,
- script_pubkey: bytes | None,
+ script_pubkey: AnyBytes | None,
) -> bytes: ...
@@ -60,20 +61,20 @@ class BitcoinSigHasher:
self.h_sequences = HashWriter(sha256())
self.h_outputs = HashWriter(sha256())
- def add_input(self, txi: TxInput, script_pubkey: bytes) -> None:
+ def add_input(self, txi: TxInput, script_pubkey: AnyBytes) -> None:
write_bytes_reversed(self.h_prevouts, txi.prev_hash, TX_HASH_SIZE)
write_uint32(self.h_prevouts, txi.prev_index)
write_uint64(self.h_amounts, txi.amount)
write_bytes_prefixed(self.h_scriptpubkeys, script_pubkey)
write_uint32(self.h_sequences, txi.sequence)
- def add_output(self, txo: TxOutput, script_pubkey: bytes) -> None:
+ def add_output(self, txo: TxOutput, script_pubkey: AnyBytes) -> None:
write_tx_output(self.h_outputs, txo, script_pubkey)
def hash143(
self,
txi: TxInput,
- public_keys: Sequence[bytes | memoryview],
+ public_keys: Sequence[AnyBytes],
threshold: int,
tx: SignTx | PrevTx,
coin: coininfo.CoinInfo,
@@ -174,6 +175,6 @@ class BitcoinSigHasher:
def hash_zip244(
self,
txi: TxInput | None,
- script_pubkey: bytes | None,
+ script_pubkey: AnyBytes | None,
) -> bytes:
raise NotImplementedError
diff --git a/core/src/apps/bitcoin/sign_tx/tx_info.py b/core/src/apps/bitcoin/sign_tx/tx_info.py
index 8ffe9bdd..7f6b0add 100644
--- a/core/src/apps/bitcoin/sign_tx/tx_info.py
+++ b/core/src/apps/bitcoin/sign_tx/tx_info.py
@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING
from .. import writers
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Protocol
from trezor.messages import PrevTx, SignTx, TxInput, TxOutput
@@ -28,7 +29,7 @@ if TYPE_CHECKING:
) -> None: ...
async def write_prev_tx_footer(
- self, w: writers.Writer, tx: PrevTx, prev_hash: bytes
+ self, w: writers.Writer, tx: PrevTx, prev_hash: AnyBytes
) -> None: ...
@@ -65,14 +66,14 @@ class TxInfoBase:
# The minimum nSequence of all inputs.
self.min_sequence = _SEQUENCE_FINAL
- def add_input(self, txi: TxInput, script_pubkey: bytes) -> None:
+ def add_input(self, txi: TxInput, script_pubkey: AnyBytes) -> None:
# all inputs are included (non-segwit as well)
self.sig_hasher.add_input(txi, script_pubkey)
writers.write_tx_input_check(self.h_tx_check, txi)
self.min_sequence = min(self.min_sequence, txi.sequence)
self.change_detector.add_input(txi)
- def add_output(self, txo: TxOutput, script_pubkey: bytes) -> None:
+ def add_output(self, txo: TxOutput, script_pubkey: AnyBytes) -> None:
self.sig_hasher.add_output(txo, script_pubkey)
writers.write_tx_output(self.h_tx_check, txo, script_pubkey)
@@ -101,7 +102,7 @@ class TxInfo(TxInfoBase):
# Used to keep track of any original transactions which are being replaced by the current transaction.
class OriginalTxInfo(TxInfoBase):
- def __init__(self, signer: Signer, tx: PrevTx, orig_hash: bytes) -> None:
+ def __init__(self, signer: Signer, tx: PrevTx, orig_hash: AnyBytes) -> None:
super().__init__(signer, tx)
self.tx = tx
self.signer = signer
@@ -118,11 +119,11 @@ class OriginalTxInfo(TxInfoBase):
signer.write_tx_header(self.h_tx, tx, witness_marker=False)
writers.write_compact_size(self.h_tx, tx.inputs_count)
- def add_input(self, txi: TxInput, script_pubkey: bytes) -> None:
+ def add_input(self, txi: TxInput, script_pubkey: AnyBytes) -> None:
super().add_input(txi, script_pubkey)
writers.write_tx_input(self.h_tx, txi, txi.script_sig or bytes())
- def add_output(self, txo: TxOutput, script_pubkey: bytes) -> None:
+ def add_output(self, txo: TxOutput, script_pubkey: AnyBytes) -> None:
super().add_output(txo, script_pubkey)
if self.index == 0:
diff --git a/core/src/apps/bitcoin/sign_tx/tx_weight.py b/core/src/apps/bitcoin/sign_tx/tx_weight.py
index a1b44dbd..a8cb40a0 100644
--- a/core/src/apps/bitcoin/sign_tx/tx_weight.py
+++ b/core/src/apps/bitcoin/sign_tx/tx_weight.py
@@ -14,6 +14,8 @@ from trezor.enums import InputScriptType
from .. import common
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import TxInput
# transaction header size: 4 byte version
@@ -136,7 +138,7 @@ class TxWeightCalculator:
else:
raise wire.DataError("Invalid script type")
- def add_output(self, script: bytes) -> None:
+ def add_output(self, script: AnyBytes) -> None:
self.outputs_count += 1
script_size = self.compact_size_len(len(script)) + len(script)
self.counter += 4 * (_TXSIZE_OUTPUT + script_size)
diff --git a/core/src/apps/bitcoin/sign_tx/zcash_v4.py b/core/src/apps/bitcoin/sign_tx/zcash_v4.py
index 38a6ecc1..3b69bfe2 100644
--- a/core/src/apps/bitcoin/sign_tx/zcash_v4.py
+++ b/core/src/apps/bitcoin/sign_tx/zcash_v4.py
@@ -9,6 +9,7 @@ from ..writers import TX_HASH_SIZE, write_bytes_reversed, write_uint32, write_ui
from .bitcoinlike import Bitcoinlike
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Sequence
from trezor.messages import PrevTx, SignTx, TxInput, TxOutput
@@ -31,12 +32,12 @@ class Zip243SigHasher:
self.h_sequence = HashWriter(blake2b(outlen=32, personal=b"ZcashSequencHash"))
self.h_outputs = HashWriter(blake2b(outlen=32, personal=b"ZcashOutputsHash"))
- def add_input(self, txi: TxInput, script_pubkey: bytes) -> None:
+ def add_input(self, txi: TxInput, script_pubkey: AnyBytes) -> None:
write_bytes_reversed(self.h_prevouts, txi.prev_hash, TX_HASH_SIZE)
write_uint32(self.h_prevouts, txi.prev_index)
write_uint32(self.h_sequence, txi.sequence)
- def add_output(self, txo: TxOutput, script_pubkey: bytes) -> None:
+ def add_output(self, txo: TxOutput, script_pubkey: AnyBytes) -> None:
from ..writers import write_tx_output
write_tx_output(self.h_outputs, txo, script_pubkey)
@@ -44,7 +45,7 @@ class Zip243SigHasher:
def hash143(
self,
txi: TxInput,
- public_keys: Sequence[bytes | memoryview],
+ public_keys: Sequence[AnyBytes],
threshold: int,
tx: SignTx | PrevTx,
coin: CoinInfo,
@@ -113,7 +114,7 @@ class Zip243SigHasher:
def hash_zip244(
self,
txi: TxInput | None,
- script_pubkey: bytes | None,
+ script_pubkey: AnyBytes | None,
) -> bytes:
raise NotImplementedError
diff --git a/core/src/apps/bitcoin/verification.py b/core/src/apps/bitcoin/verification.py
index d8300bd8..f7c70ce9 100644
--- a/core/src/apps/bitcoin/verification.py
+++ b/core/src/apps/bitcoin/verification.py
@@ -3,6 +3,7 @@ from typing import TYPE_CHECKING
from trezor.wire import DataError
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Sequence
from apps.common.coininfo import CoinInfo
@@ -13,9 +14,9 @@ if TYPE_CHECKING:
class SignatureVerifier:
def __init__(
self,
- script_pubkey: bytes,
- script_sig: bytes | None,
- witness: bytes | None,
+ script_pubkey: AnyBytes,
+ script_sig: AnyBytes | None,
+ witness: AnyBytes | None,
coin: CoinInfo,
) -> None:
from trezor import utils
diff --git a/core/src/apps/bitcoin/writers.py b/core/src/apps/bitcoin/writers.py
index ca764438..00b3fa0c 100644
--- a/core/src/apps/bitcoin/writers.py
+++ b/core/src/apps/bitcoin/writers.py
@@ -18,6 +18,8 @@ from apps.common.writers import ( # noqa: F401
from .multisig import multisig_fingerprint
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import PrevInput, PrevOutput, TxInput, TxOutput
from trezor.utils import HashWriter
@@ -30,7 +32,7 @@ write_uint64 = write_uint64_le
TX_HASH_SIZE = const(32)
-def write_tx_input(w: Writer, i: TxInput | PrevInput, script: bytes) -> None:
+def write_tx_input(w: Writer, i: TxInput | PrevInput, script: AnyBytes) -> None:
write_bytes_reversed(w, i.prev_hash, TX_HASH_SIZE)
write_uint32(w, i.prev_index)
write_bytes_prefixed(w, script)
@@ -56,7 +58,9 @@ def write_tx_input_check(w: Writer, i: TxInput) -> None:
write_bytes_prefixed(w, i.script_pubkey or b"")
-def write_tx_output(w: Writer, o: TxOutput | PrevOutput, script_pubkey: bytes) -> None:
+def write_tx_output(
+ w: Writer, o: TxOutput | PrevOutput, script_pubkey: AnyBytes
+) -> None:
write_uint64(w, o.amount)
write_bytes_prefixed(w, script_pubkey)
diff --git a/core/src/apps/cardano/addresses.py b/core/src/apps/cardano/addresses.py
index af40b1ad..a4b7fb19 100644
--- a/core/src/apps/cardano/addresses.py
+++ b/core/src/apps/cardano/addresses.py
@@ -11,6 +11,7 @@ from .helpers.paths import SCHEMA_STAKING_ANY_ACCOUNT
from .helpers.utils import get_public_key_hash
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Any
from trezor import messages
@@ -212,7 +213,7 @@ def _validate_address_parameters_structure(
def _validate_base_address_staking_info(
staking_path: list[int],
- staking_key_hash: bytes | None,
+ staking_key_hash: AnyBytes | None,
) -> None:
from .helpers import ADDRESS_KEY_HASH_SIZE
@@ -226,7 +227,7 @@ def _validate_base_address_staking_info(
raise ProcessError("Invalid address parameters")
-def _validate_script_hash(script_hash: bytes | None) -> None:
+def _validate_script_hash(script_hash: AnyBytes | None) -> None:
from .helpers import SCRIPT_HASH_SIZE
assert_params_cond(script_hash is not None and len(script_hash) == SCRIPT_HASH_SIZE)
@@ -412,7 +413,7 @@ def _derive_shelley_address(
def _get_payment_part(
keychain: Keychain, parameters: messages.CardanoAddressParametersType
-) -> bytes:
+) -> AnyBytes:
if parameters.address_n:
return get_public_key_hash(keychain, parameters.address_n)
elif parameters.script_payment_hash:
@@ -423,7 +424,7 @@ def _get_payment_part(
def _get_staking_part(
keychain: Keychain, parameters: messages.CardanoAddressParametersType
-) -> bytes:
+) -> AnyBytes:
from .helpers.utils import variable_length_encode
if parameters.staking_key_hash:
diff --git a/core/src/apps/cardano/auxiliary_data.py b/core/src/apps/cardano/auxiliary_data.py
index 3dab3a4c..76989c19 100644
--- a/core/src/apps/cardano/auxiliary_data.py
+++ b/core/src/apps/cardano/auxiliary_data.py
@@ -11,9 +11,11 @@ from .helpers.paths import SCHEMA_STAKING_ANY_ACCOUNT
from .helpers.utils import derive_public_key
if TYPE_CHECKING:
- Delegations = list[tuple[bytes, int]]
- CVoteRegistrationPayload = dict[int, Delegations | bytes | int]
- SignedCVoteRegistrationPayload = tuple[CVoteRegistrationPayload, bytes]
+ from buffer_types import AnyBytes
+
+ Delegations = list[tuple[AnyBytes, int]]
+ CVoteRegistrationPayload = dict[int, Delegations | AnyBytes | int]
+ SignedCVoteRegistrationPayload = tuple[CVoteRegistrationPayload, AnyBytes]
from trezor import messages
@@ -91,7 +93,7 @@ def _validate_cvote_registration_parameters(
assert_cond(parameters.format == CardanoCVoteRegistrationFormat.CIP36)
-def _validate_vote_public_key(key: bytes) -> None:
+def _validate_vote_public_key(key: AnyBytes) -> None:
assert_cond(len(key) == _CVOTE_PUBLIC_KEY_LENGTH)
@@ -115,7 +117,7 @@ def _get_voting_purpose_to_serialize(
async def show(
keychain: seed.Keychain,
- auxiliary_data_hash: bytes,
+ auxiliary_data_hash: AnyBytes,
parameters: messages.CardanoCVoteRegistrationParametersType | None,
protocol_magic: int,
network_id: int,
@@ -204,7 +206,7 @@ def get_hash_and_supplement(
auxiliary_data: messages.CardanoTxAuxiliaryData,
protocol_magic: int,
network_id: int,
-) -> tuple[bytes, messages.CardanoTxAuxiliaryDataSupplement]:
+) -> tuple[AnyBytes, messages.CardanoTxAuxiliaryDataSupplement]:
from trezor import messages
from trezor.enums import CardanoTxAuxiliaryDataSupplementType
@@ -233,7 +235,7 @@ def get_hash_and_supplement(
def _get_cvote_registration_hash(
cvote_registration_payload: CVoteRegistrationPayload,
- cvote_registration_payload_signature: bytes,
+ cvote_registration_payload_signature: AnyBytes,
) -> bytes:
# _cborize_catalyst_registration
cvote_registration_signature = {1: cvote_registration_payload_signature}
@@ -262,7 +264,7 @@ def _get_signed_cvote_registration_payload(
protocol_magic: int,
network_id: int,
) -> SignedCVoteRegistrationPayload:
- delegations_or_key: Delegations | bytes
+ delegations_or_key: Delegations | AnyBytes
if len(parameters.delegations) > 0:
delegations_or_key = [
(delegation.vote_public_key, delegation.weight)
diff --git a/core/src/apps/cardano/certificates.py b/core/src/apps/cardano/certificates.py
index 762dea43..d757a195 100644
--- a/core/src/apps/cardano/certificates.py
+++ b/core/src/apps/cardano/certificates.py
@@ -8,6 +8,7 @@ from . import addresses
from .helpers.utils import get_public_key_hash
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Any
from trezor import messages
@@ -184,9 +185,9 @@ def cborize(
def cborize_stake_credential(
keychain: seed.Keychain,
path: list[int],
- script_hash: bytes | None,
- key_hash: bytes | None,
-) -> tuple[int, bytes]:
+ script_hash: AnyBytes | None,
+ key_hash: AnyBytes | None,
+) -> tuple[int, AnyBytes]:
if key_hash or path:
return 0, key_hash or get_public_key_hash(keychain, path)
@@ -323,7 +324,7 @@ def validate_pool_relay(pool_relay: messages.CardanoPoolRelayParameters) -> None
raise RuntimeError # should be unreachable
-def cborize_drep(drep: messages.CardanoDRep) -> tuple[int, bytes] | tuple[int]:
+def cborize_drep(drep: messages.CardanoDRep) -> tuple[int, AnyBytes] | tuple[int]:
if drep.type == CardanoDRepType.KEY_HASH:
assert drep.key_hash is not None
return 0, drep.key_hash
@@ -340,7 +341,7 @@ def cborize_drep(drep: messages.CardanoDRep) -> tuple[int, bytes] | tuple[int]:
def cborize_pool_owner(
keychain: seed.Keychain, pool_owner: messages.CardanoPoolOwner
-) -> bytes:
+) -> AnyBytes:
if pool_owner.staking_key_path:
return get_public_key_hash(keychain, pool_owner.staking_key_path)
elif pool_owner.staking_key_hash:
@@ -349,7 +350,7 @@ def cborize_pool_owner(
raise ValueError
-def _cborize_ipv6_address(ipv6_address: bytes | None) -> bytes | None:
+def _cborize_ipv6_address(ipv6_address: AnyBytes | None) -> bytes | None:
if ipv6_address is None:
return None
diff --git a/core/src/apps/cardano/helpers/bech32.py b/core/src/apps/cardano/helpers/bech32.py
index 68477641..c914be29 100644
--- a/core/src/apps/cardano/helpers/bech32.py
+++ b/core/src/apps/cardano/helpers/bech32.py
@@ -1,5 +1,10 @@
+from typing import TYPE_CHECKING
+
from trezor.crypto import bech32
+if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
HRP_SEPARATOR = "1"
# CIP-0005 prefixes - https://github.com/cardano-foundation/CIPs/blob/master/CIP-0005/CIP-0005.md
@@ -19,7 +24,7 @@ HRP_DREP_KEY_HASH = "drep"
HRP_DREP_SCRIPT_HASH = "drep_script"
-def encode(hrp: str, data: bytes) -> str:
+def encode(hrp: str, data: AnyBytes) -> str:
converted_bits = bech32.convertbits(data, 8, 5)
return bech32.bech32_encode(hrp, converted_bits, bech32.Encoding.BECH32)
diff --git a/core/src/apps/cardano/helpers/credential.py b/core/src/apps/cardano/helpers/credential.py
index a1257b80..8418b7eb 100644
--- a/core/src/apps/cardano/helpers/credential.py
+++ b/core/src/apps/cardano/helpers/credential.py
@@ -6,6 +6,8 @@ from trezor.enums import CardanoAddressType
from .paths import SCHEMA_PAYMENT
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor import messages
from trezor.ui.layouts import PropertyType
@@ -24,8 +26,8 @@ class Credential:
type_name: str
address_type: CardanoAddressType
path: list[int]
- key_hash: bytes | None
- script_hash: bytes | None
+ key_hash: AnyBytes | None
+ script_hash: AnyBytes | None
pointer: messages.CardanoBlockchainPointerType | None
is_reward: bool = False
@@ -39,8 +41,8 @@ class Credential:
type_name: str,
address_type: CardanoAddressType,
path: list[int],
- key_hash: bytes | None,
- script_hash: bytes | None,
+ key_hash: AnyBytes | None,
+ script_hash: AnyBytes | None,
pointer: messages.CardanoBlockchainPointerType | None,
) -> None:
self.type_name = type_name
diff --git a/core/src/apps/cardano/helpers/utils.py b/core/src/apps/cardano/helpers/utils.py
index 8b7357c4..cbdbe332 100644
--- a/core/src/apps/cardano/helpers/utils.py
+++ b/core/src/apps/cardano/helpers/utils.py
@@ -6,6 +6,8 @@ from . import ADDRESS_KEY_HASH_SIZE, bech32
from .paths import ACCOUNT_PATH_INDEX
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.wire import ProcessError
from .. import seed
@@ -48,11 +50,11 @@ def format_optional_int(number: int | None) -> str:
return str(number)
-def format_stake_pool_id(pool_id_bytes: bytes) -> str:
+def format_stake_pool_id(pool_id_bytes: AnyBytes) -> str:
return bech32.encode("pool", pool_id_bytes)
-def format_asset_fingerprint(policy_id: bytes, asset_name_bytes: bytes) -> str:
+def format_asset_fingerprint(policy_id: AnyBytes, asset_name_bytes: AnyBytes) -> str:
fingerprint = hashlib.blake2b(
# bytearrays are being promoted to bytes: https://github.com/python/mypy/issues/654
# but bytearrays are not concatenable, this casting works around this limitation
@@ -80,8 +82,8 @@ def derive_public_key(
def validate_stake_credential(
path: list[int],
- script_hash: bytes | None,
- key_hash: bytes | None,
+ script_hash: AnyBytes | None,
+ key_hash: AnyBytes | None,
error: ProcessError,
) -> None:
from . import SCRIPT_HASH_SIZE
@@ -115,12 +117,12 @@ def validate_network_info(network_id: int, protocol_magic: int) -> None:
raise wire.ProcessError("Invalid network id/protocol magic combination!")
-def is_printable_ascii(bytestring: bytes) -> bool:
+def is_printable_ascii(bytestring: AnyBytes) -> bool:
"""Includes space character."""
return all(32 <= b <= 126 for b in bytestring)
-def is_unambiguous_ascii(bytestring: bytes) -> bool:
+def is_unambiguous_ascii(bytestring: AnyBytes) -> bool:
"""
Checks whether the bytestring can be printed as ASCII without confusion.
Based on https://github.com/vacuumlabs/ledger-app-cardano-shelley/blob/6ddc60e8fdff13e35bff5cdf108b84b81a79f10c/src/textUtils.c#L274
diff --git a/core/src/apps/cardano/layout.py b/core/src/apps/cardano/layout.py
index 692c71a2..f9520478 100644
--- a/core/src/apps/cardano/layout.py
+++ b/core/src/apps/cardano/layout.py
@@ -25,6 +25,7 @@ from .helpers.utils import (
)
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Callable, Literal
from trezor import messages
@@ -261,7 +262,9 @@ async def confirm_sending(
)
-async def confirm_sending_token(policy_id: bytes, token: messages.CardanoToken) -> None:
+async def confirm_sending_token(
+ policy_id: AnyBytes, token: messages.CardanoToken
+) -> None:
assert token.amount is not None # _validate_token
await confirm_properties(
@@ -286,7 +289,7 @@ async def confirm_sending_token(policy_id: bytes, token: messages.CardanoToken)
)
-async def confirm_datum_hash(datum_hash: bytes) -> None:
+async def confirm_datum_hash(datum_hash: AnyBytes) -> None:
await confirm_properties(
"confirm_datum_hash",
TR.cardano__confirm_transaction,
@@ -301,7 +304,7 @@ async def confirm_datum_hash(datum_hash: bytes) -> None:
)
-async def confirm_inline_datum(first_chunk: bytes, inline_datum_size: int) -> None:
+async def confirm_inline_datum(first_chunk: AnyBytes, inline_datum_size: int) -> None:
await _confirm_tx_data_chunk(
"confirm_inline_datum",
TR.cardano__inline_datum,
@@ -311,7 +314,7 @@ async def confirm_inline_datum(first_chunk: bytes, inline_datum_size: int) -> No
async def confirm_reference_script(
- first_chunk: bytes, reference_script_size: int
+ first_chunk: AnyBytes, reference_script_size: int
) -> None:
await _confirm_tx_data_chunk(
"confirm_reference_script",
@@ -322,7 +325,7 @@ async def confirm_reference_script(
async def confirm_message_payload(
- payload: bytes,
+ payload: AnyBytes,
payload_size: int,
prefer_hex_display: bool,
) -> None:
@@ -341,7 +344,7 @@ async def confirm_message_payload(
first_chunk=payload,
data_size=payload_size,
max_displayed_size=None,
- decoder=lambda chunk: chunk.decode("ascii"),
+ decoder=lambda chunk: bytes(chunk).decode("ascii"),
)
else:
props = _get_data_chunk_props(
@@ -361,10 +364,10 @@ async def confirm_message_payload(
def _get_data_chunk_props(
title: str,
- first_chunk: bytes,
+ first_chunk: AnyBytes,
data_size: int,
max_displayed_size: int | None = _DEFAULT_MAX_DISPLAYED_CHUNK_SIZE,
- decoder: Callable[[bytes], bytes | str] | None = None,
+ decoder: Callable[[AnyBytes], AnyBytes | str] | None = None,
) -> list[PropertyType]:
displayed_bytes = (
first_chunk[:max_displayed_size]
@@ -386,7 +389,7 @@ def _get_data_chunk_props(
async def _confirm_tx_data_chunk(
- br_name: str, title: str, first_chunk: bytes, data_size: int
+ br_name: str, title: str, first_chunk: AnyBytes, data_size: int
) -> None:
await confirm_properties(
br_name,
@@ -914,7 +917,7 @@ async def confirm_withdrawal(
def _format_stake_credential(
- path: list[int], script_hash: bytes | None, key_hash: bytes | None
+ path: list[int], script_hash: AnyBytes | None, key_hash: AnyBytes | None
) -> PropertyType:
from .helpers.paths import ADDRESS_INDEX_PATH_INDEX, RECOMMENDED_ADDRESS_INDEX
@@ -1052,7 +1055,7 @@ async def confirm_cvote_registration(
)
-async def show_auxiliary_data_hash(auxiliary_data_hash: bytes) -> None:
+async def show_auxiliary_data_hash(auxiliary_data_hash: AnyBytes) -> None:
await confirm_properties(
"confirm_auxiliary_data",
TR.cardano__confirm_transaction,
@@ -1061,7 +1064,9 @@ async def show_auxiliary_data_hash(auxiliary_data_hash: bytes) -> None:
)
-async def confirm_token_minting(policy_id: bytes, token: messages.CardanoToken) -> None:
+async def confirm_token_minting(
+ policy_id: AnyBytes, token: messages.CardanoToken
+) -> None:
assert token.mint_amount is not None # _validate_token
await confirm_properties(
"confirm_mint",
@@ -1098,7 +1103,7 @@ async def warn_tx_network_unverifiable() -> None:
)
-async def confirm_script_data_hash(script_data_hash: bytes) -> None:
+async def confirm_script_data_hash(script_data_hash: AnyBytes) -> None:
await confirm_properties(
"confirm_script_data_hash",
TR.cardano__confirm_transaction,
diff --git a/core/src/apps/cardano/sign_message.py b/core/src/apps/cardano/sign_message.py
index d85dad8a..99e8d4be 100644
--- a/core/src/apps/cardano/sign_message.py
+++ b/core/src/apps/cardano/sign_message.py
@@ -12,6 +12,7 @@ from apps.common import cbor
from . import addresses, seed
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Any
from trezor.messages import CardanoMessageSignature, CardanoSignMessageInit
@@ -78,7 +79,7 @@ async def _get_payload_data(
payload_size: int,
chunk_length: int,
chunk_offset: int,
-) -> bytes:
+) -> AnyBytes:
"""Returns payload data using length+offset pattern."""
from trezor.messages import CardanoMessageDataRequest, CardanoMessageDataResponse
@@ -94,7 +95,7 @@ async def _get_payload_data(
return response.data
-async def _get_confirmed_payload(size: int, prefer_hex_display: bool) -> bytes:
+async def _get_confirmed_payload(size: int, prefer_hex_display: bool) -> AnyBytes:
from . import layout
# Request the entire payload at once for now, regardless of RAM constraints.
@@ -120,7 +121,7 @@ async def _get_confirmed_payload(size: int, prefer_hex_display: bool) -> bytes:
def _cborize_sig_structure(
- payload: bytes,
+ payload: AnyBytes,
protected_headers: Headers,
external_aad: bytes | None = None,
) -> CborSequence:
diff --git a/core/src/apps/cardano/sign_tx/signer.py b/core/src/apps/cardano/sign_tx/signer.py
index 6b20fb0a..985cc2f4 100644
--- a/core/src/apps/cardano/sign_tx/signer.py
+++ b/core/src/apps/cardano/sign_tx/signer.py
@@ -26,6 +26,7 @@ from ..helpers.paths import SCHEMA_STAKING, SLIP44_ID
from ..helpers.utils import derive_public_key
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from enum import IntEnum
from typing import Any, Awaitable, ClassVar
@@ -194,7 +195,7 @@ class Signer:
await self._process_certificates(certificates_set)
if msg.withdrawals_count > 0:
- withdrawals_dict: HashBuilderDict[bytes, int] = HashBuilderDict(
+ withdrawals_dict: HashBuilderDict[AnyBytes, int] = HashBuilderDict(
msg.withdrawals_count, ProcessError("Invalid withdrawal")
)
with add(_TX_BODY_KEY_WITHDRAWALS, withdrawals_dict):
@@ -207,7 +208,7 @@ class Signer:
add(_TX_BODY_KEY_VALIDITY_INTERVAL_START, msg.validity_interval_start)
if msg.minting_asset_groups_count > 0:
- minting_dict: HashBuilderDict[bytes, HashBuilderDict] = HashBuilderDict(
+ minting_dict: HashBuilderDict[AnyBytes, HashBuilderDict] = HashBuilderDict(
msg.minting_asset_groups_count,
ProcessError("Invalid mint token bundle"),
)
@@ -218,14 +219,14 @@ class Signer:
await self._process_script_data_hash()
if msg.collateral_inputs_count > 0:
- collateral_inputs_set: HashBuilderSet[tuple[bytes, int]] = HBS(
+ collateral_inputs_set: HashBuilderSet[tuple[AnyBytes, int]] = HBS(
msg.collateral_inputs_count, tagged=self.msg.tag_cbor_sets
)
with add(_TX_BODY_KEY_COLLATERAL_INPUTS, collateral_inputs_set):
await self._process_collateral_inputs(collateral_inputs_set)
if msg.required_signers_count > 0:
- required_signers_set: HashBuilderSet[bytes] = HBS(
+ required_signers_set: HashBuilderSet[AnyBytes] = HBS(
msg.required_signers_count, tagged=self.msg.tag_cbor_sets
)
with add(_TX_BODY_KEY_REQUIRED_SIGNERS, required_signers_set):
@@ -241,7 +242,7 @@ class Signer:
add(_TX_BODY_KEY_TOTAL_COLLATERAL, msg.total_collateral)
if msg.reference_inputs_count > 0:
- reference_inputs_set: HashBuilderSet[tuple[bytes, int]] = HBS(
+ reference_inputs_set: HashBuilderSet[tuple[AnyBytes, int]] = HBS(
msg.reference_inputs_count, tagged=self.msg.tag_cbor_sets
)
with add(_TX_BODY_KEY_REFERENCE_INPUTS, reference_inputs_set):
@@ -277,7 +278,7 @@ class Signer:
# inputs
async def _process_inputs(
- self, inputs_list: HashBuilderList[tuple[bytes, int]]
+ self, inputs_list: HashBuilderList[tuple[AnyBytes, int]]
) -> None:
for _ in range(self.msg.inputs_count):
input: messages.CardanoTxInput = await ctx_call(
@@ -577,7 +578,7 @@ class Signer:
output_value_list.append(output.amount)
- asset_groups_dict: HashBuilderDict[bytes, HashBuilderDict[bytes, int]] = (
+ asset_groups_dict: HashBuilderDict[AnyBytes, HashBuilderDict[AnyBytes, int]] = (
HashBuilderDict(
output.asset_groups_count,
ProcessError("Invalid token bundle in output"),
@@ -594,7 +595,7 @@ class Signer:
async def _process_asset_groups(
self,
- asset_groups_dict: HashBuilderDict[bytes, HashBuilderDict[bytes, int]],
+ asset_groups_dict: HashBuilderDict[AnyBytes, HashBuilderDict[AnyBytes, int]],
asset_groups_count: int,
should_show_tokens: bool,
) -> None:
@@ -604,7 +605,7 @@ class Signer:
)
self._validate_asset_group(asset_group)
- tokens: HashBuilderDict[bytes, int] = HashBuilderDict(
+ tokens: HashBuilderDict[AnyBytes, int] = HashBuilderDict(
asset_group.tokens_count,
ProcessError("Invalid token bundle in output"),
)
@@ -634,8 +635,8 @@ class Signer:
async def _process_tokens(
self,
- tokens_dict: HashBuilderDict[bytes, int],
- policy_id: bytes,
+ tokens_dict: HashBuilderDict[AnyBytes, int],
+ policy_id: AnyBytes,
tokens_count: int,
should_show_tokens: bool,
) -> None:
@@ -834,7 +835,7 @@ class Signer:
# withdrawals
async def _process_withdrawals(
- self, withdrawals_dict: HashBuilderDict[bytes, int]
+ self, withdrawals_dict: HashBuilderDict[AnyBytes, int]
) -> None:
for _ in range(self.msg.withdrawals_count):
withdrawal: messages.CardanoTxWithdrawal = await ctx_call(
@@ -899,7 +900,7 @@ class Signer:
# minting
async def _process_minting(
- self, minting_dict: HashBuilderDict[bytes, HashBuilderDict]
+ self, minting_dict: HashBuilderDict[AnyBytes, HashBuilderDict]
) -> None:
token_minting: messages.CardanoTxMint = await ctx_call(
CardanoTxItemAck(), messages.CardanoTxMint
@@ -913,7 +914,7 @@ class Signer:
)
self._validate_asset_group(asset_group, is_mint=True)
- tokens: HashBuilderDict[bytes, int] = HashBuilderDict(
+ tokens: HashBuilderDict[AnyBytes, int] = HashBuilderDict(
asset_group.tokens_count, ProcessError("Invalid mint token bundle")
)
with minting_dict.add(asset_group.policy_id, tokens):
@@ -927,8 +928,8 @@ class Signer:
async def _process_minting_tokens(
self,
- tokens: HashBuilderDict[bytes, int],
- policy_id: bytes,
+ tokens: HashBuilderDict[AnyBytes, int],
+ policy_id: AnyBytes,
tokens_count: int,
) -> None:
for _ in range(tokens_count):
@@ -961,7 +962,7 @@ class Signer:
# collateral inputs
async def _process_collateral_inputs(
- self, collateral_inputs_list: HashBuilderList[tuple[bytes, int]]
+ self, collateral_inputs_list: HashBuilderList[tuple[AnyBytes, int]]
) -> None:
for _ in range(self.msg.collateral_inputs_count):
collateral_input: messages.CardanoTxCollateralInput = await ctx_call(
@@ -990,7 +991,7 @@ class Signer:
# required signers
async def _process_required_signers(
- self, required_signers_set: HashBuilderSet[bytes]
+ self, required_signers_set: HashBuilderSet[AnyBytes]
) -> None:
from ..helpers.utils import get_public_key_hash
@@ -1123,7 +1124,7 @@ class Signer:
# reference inputs
async def _process_reference_inputs(
- self, reference_inputs_list: HashBuilderList[tuple[bytes, int]]
+ self, reference_inputs_list: HashBuilderList[tuple[AnyBytes, int]]
) -> None:
for _ in range(self.msg.reference_inputs_count):
reference_input: messages.CardanoTxReferenceInput = await ctx_call(
@@ -1145,7 +1146,9 @@ class Signer:
# witness requests
- async def _process_witness_requests(self, tx_hash: bytes) -> CardanoTxResponseType:
+ async def _process_witness_requests(
+ self, tx_hash: AnyBytes
+ ) -> CardanoTxResponseType:
response: CardanoTxResponseType = CardanoTxItemAck()
for _ in range(self.msg.witness_requests_count):
@@ -1234,7 +1237,7 @@ class Signer:
)
def _get_byron_witness(
- self, path: list[int], tx_hash: bytes
+ self, path: list[int], tx_hash: AnyBytes
) -> messages.CardanoTxWitnessResponse:
node = self.keychain.derive(path)
return messages.CardanoTxWitnessResponse(
@@ -1245,7 +1248,7 @@ class Signer:
)
def _get_shelley_witness(
- self, path: list[int], tx_hash: bytes
+ self, path: list[int], tx_hash: AnyBytes
) -> messages.CardanoTxWitnessResponse:
return messages.CardanoTxWitnessResponse(
type=CardanoTxWitnessType.SHELLEY_WITNESS,
@@ -1253,7 +1256,7 @@ class Signer:
signature=self._sign_tx_hash(tx_hash, path),
)
- def _sign_tx_hash(self, tx_body_hash: bytes, path: list[int]) -> bytes:
+ def _sign_tx_hash(self, tx_body_hash: AnyBytes, path: list[int]) -> bytes:
from trezor.crypto.curve import ed25519
node = self.keychain.derive(path)
diff --git a/core/src/apps/common/address_mac.py b/core/src/apps/common/address_mac.py
index 9b9645b7..5e906fe2 100644
--- a/core/src/apps/common/address_mac.py
+++ b/core/src/apps/common/address_mac.py
@@ -3,6 +3,8 @@ from typing import TYPE_CHECKING
from trezor import utils
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from apps.common.keychain import Keychain
from apps.common.paths import Bip32Path
@@ -10,7 +12,7 @@ _ADDRESS_MAC_KEY_PATH = [b"SLIP-0024", b"Address MAC key"]
def check_address_mac(
- address: str, mac: bytes, slip44: int, address_n: Bip32Path, keychain: Keychain
+ address: str, mac: AnyBytes, slip44: int, address_n: Bip32Path, keychain: Keychain
) -> None:
from trezor import wire
from trezor.crypto import hashlib
diff --git a/core/src/apps/common/chunked.py b/core/src/apps/common/chunked.py
index ee6f7eb1..6119bbf6 100644
--- a/core/src/apps/common/chunked.py
+++ b/core/src/apps/common/chunked.py
@@ -6,14 +6,13 @@ from trezor.wire import DataError
from trezor.wire.context import call
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Callable
- pass
-
_CHUNK_SIZE = const(1024)
-async def get_data_chunk(data_left: int, offset: int) -> bytes:
+async def get_data_chunk(data_left: int, offset: int) -> AnyBytes:
data_length = min(data_left, _CHUNK_SIZE)
req = DataChunkRequest(data_length=data_length, data_offset=offset)
res = await call(req, DataChunkAck)
diff --git a/core/src/apps/common/definitions.py b/core/src/apps/common/definitions.py
index 3b510680..2c8b777a 100644
--- a/core/src/apps/common/definitions.py
+++ b/core/src/apps/common/definitions.py
@@ -4,6 +4,7 @@ from trezor.messages import EthereumNetworkInfo, EthereumTokenInfo, SolanaTokenI
from trezor.wire import DataError
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import TypeVar
# NOTE: it's important all DefType variants can't be cross-parsed
@@ -12,7 +13,7 @@ if TYPE_CHECKING:
)
-def decode_definition(definition: bytes, expected_type: type[DefType]) -> DefType:
+def decode_definition(definition: AnyBytes, expected_type: type[DefType]) -> DefType:
from trezor.crypto.cosi import verify as cosi_verify
from trezor.crypto.hashlib import sha256
from trezor.enums import DefinitionType
@@ -58,8 +59,8 @@ def decode_definition(definition: bytes, expected_type: type[DefType]) -> DefTyp
proof_length = r.get()
for _ in range(proof_length):
proof_entry = r.read_memoryview(32)
- hash_a = min(hash, proof_entry)
- hash_b = max(hash, proof_entry)
+ hash_a = min(hash, proof_entry) # type: ignore [not assignable to "bytes"]
+ hash_b = max(hash, proof_entry) # type: ignore [not assignable to "bytes"]
hasher = sha256(b"\x01")
hasher.update(hash_a)
hasher.update(hash_b)
diff --git a/core/src/apps/common/paths.py b/core/src/apps/common/paths.py
index 909a914c..9e5cde2f 100644
--- a/core/src/apps/common/paths.py
+++ b/core/src/apps/common/paths.py
@@ -290,7 +290,7 @@ class PathSchema:
# Which in practice it is, the only non-Collection is Interval.
# But we're not going to introduce an additional type requirement
# for the sake of __repr__ that doesn't exist in production anyway
- collection: Collection[int] = component # type: ignore [Expression of type "Container[int]" is incompatible with declared type "Collection[int]"]
+ collection: Collection[int] = component # type: ignore [Type "Container[int]" is not assignable to declared type "Collection[int]"]
component_str = ",".join(str(unharden(i)) for i in collection)
if len(collection) > 1:
component_str = "[" + component_str + "]"
diff --git a/core/src/apps/common/signverify.py b/core/src/apps/common/signverify.py
index 9fbc982d..ad32dc1b 100644
--- a/core/src/apps/common/signverify.py
+++ b/core/src/apps/common/signverify.py
@@ -1,10 +1,12 @@
from typing import TYPE_CHECKING
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from apps.common.coininfo import CoinInfo
-def message_digest(coin: CoinInfo, message: bytes) -> bytes:
+def message_digest(coin: CoinInfo, message: AnyBytes) -> bytes:
from trezor import utils, wire
from trezor.crypto.hashlib import blake256, sha256
@@ -26,7 +28,7 @@ def message_digest(coin: CoinInfo, message: bytes) -> bytes:
return ret
-def decode_message(message: bytes) -> str:
+def decode_message(message: AnyBytes) -> str:
from ubinascii import hexlify
try:
diff --git a/core/src/apps/common/writers.py b/core/src/apps/common/writers.py
index 12c3505a..d206811e 100644
--- a/core/src/apps/common/writers.py
+++ b/core/src/apps/common/writers.py
@@ -3,6 +3,8 @@ from typing import TYPE_CHECKING
from trezor.utils import ensure
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.utils import Writer
@@ -40,23 +42,23 @@ def write_uint64_be(w: Writer, n: int) -> int:
return _write_uint(w, n, 64, True)
-def write_bytes_unchecked(w: Writer, b: bytes | memoryview) -> int:
+def write_bytes_unchecked(w: Writer, b: AnyBytes) -> int:
w.extend(b)
return len(b)
-def write_bytes_fixed(w: Writer, b: bytes, length: int) -> int:
+def write_bytes_fixed(w: Writer, b: AnyBytes, length: int) -> int:
ensure(len(b) == length)
w.extend(b)
return length
-def write_bytes_prefixed(w: Writer, b: bytes) -> None:
+def write_bytes_prefixed(w: Writer, b: AnyBytes) -> None:
write_compact_size(w, len(b))
write_bytes_unchecked(w, b)
-def write_bytes_reversed(w: Writer, b: bytes, length: int) -> int:
+def write_bytes_reversed(w: Writer, b: AnyBytes, length: int) -> int:
ensure(len(b) == length)
w.extend(bytes(reversed(b)))
return length
diff --git a/core/src/apps/eos/writers.py b/core/src/apps/eos/writers.py
index d96d5b13..822df5ba 100644
--- a/core/src/apps/eos/writers.py
+++ b/core/src/apps/eos/writers.py
@@ -11,6 +11,8 @@ from apps.common.writers import (
)
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import (
EosActionBuyRam,
EosActionBuyRamBytes,
@@ -163,6 +165,6 @@ def write_asset(w: Writer, asset: EosAsset) -> None:
write_uint64_le(w, asset.symbol)
-def write_bytes_prefixed(w: Writer, data: bytes) -> None:
+def write_bytes_prefixed(w: Writer, data: AnyBytes) -> None:
write_uvarint(w, len(data))
write_bytes_unchecked(w, data)
diff --git a/core/src/apps/ethereum/definitions.py b/core/src/apps/ethereum/definitions.py
index 355dc9ff..d106470c 100644
--- a/core/src/apps/ethereum/definitions.py
+++ b/core/src/apps/ethereum/definitions.py
@@ -4,6 +4,8 @@ from trezor.messages import EthereumNetworkInfo, EthereumTokenInfo
from trezor.wire import DataError
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from typing_extensions import Self
@@ -21,8 +23,8 @@ class Definitions:
@classmethod
def from_encoded(
cls,
- encoded_network: bytes | None,
- encoded_token: bytes | None,
+ encoded_network: AnyBytes | None,
+ encoded_token: AnyBytes | None,
chain_id: int | None = None,
slip44: int | None = None,
) -> Self:
@@ -61,7 +63,7 @@ class Definitions:
# This might help us in the future if we allow multiple networks/tokens
# in the same message.
if token.chain_id == network.chain_id:
- tokens[token.address] = token
+ tokens[bytes(token.address)] = token
return cls(network, tokens)
diff --git a/core/src/apps/ethereum/helpers.py b/core/src/apps/ethereum/helpers.py
index 6e7397be..87e172eb 100644
--- a/core/src/apps/ethereum/helpers.py
+++ b/core/src/apps/ethereum/helpers.py
@@ -6,6 +6,7 @@ from trezor import TR
from . import networks
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Iterable
from trezor.messages import EthereumFieldType, EthereumTokenInfo
@@ -17,7 +18,7 @@ RSKIP60_NETWORKS = (30, 31)
def address_from_bytes(
- address_bytes: bytes, network: EthereumNetworkInfo = networks.UNKNOWN_NETWORK
+ address_bytes: AnyBytes, network: EthereumNetworkInfo = networks.UNKNOWN_NETWORK
) -> str:
"""
Converts address in bytes to a checksummed string as defined
@@ -111,12 +112,12 @@ def get_type_name(field: EthereumFieldType) -> str:
return TYPE_TRANSLATION_DICT[data_type]
-def decode_typed_data(data: bytes, type_name: str) -> str:
+def decode_typed_data(data: AnyBytes, type_name: str) -> str:
"""Used by sign_typed_data module to show data to user."""
if type_name.startswith("bytes"):
return hexlify(data).decode()
elif type_name == "string":
- return data.decode()
+ return bytes(data).decode()
elif type_name == "address":
return address_from_bytes(data)
elif type_name == "bool":
@@ -212,7 +213,7 @@ def get_account_and_path(address_n: list[int]) -> tuple[str | None, str | None]:
return (account, account_path)
-def _from_bytes_bigendian_signed(b: bytes) -> int:
+def _from_bytes_bigendian_signed(b: AnyBytes) -> int:
negative = b[0] & 0x80
if negative:
neg_b = bytearray(b)
diff --git a/core/src/apps/ethereum/layout.py b/core/src/apps/ethereum/layout.py
index 4eb0b180..8182c589 100644
--- a/core/src/apps/ethereum/layout.py
+++ b/core/src/apps/ethereum/layout.py
@@ -17,6 +17,7 @@ from .helpers import (
)
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Awaitable, Iterable
from trezor.messages import (
@@ -30,7 +31,7 @@ if TYPE_CHECKING:
async def require_confirm_approve(
- to_bytes: bytes,
+ to_bytes: AnyBytes,
value: int | None,
address_n: list[int],
maximum_fee: str,
@@ -38,7 +39,7 @@ async def require_confirm_approve(
chain_id: int,
network: EthereumNetworkInfo,
token: EthereumTokenInfo,
- token_address: bytes,
+ token_address: AnyBytes,
chunkify: bool,
) -> None:
from trezor.ui.layouts import confirm_ethereum_approve
@@ -298,7 +299,7 @@ def require_confirm_address(
)
-def require_confirm_other_data(data: bytes, data_total: int) -> Awaitable[None]:
+def require_confirm_other_data(data: AnyBytes, data_total: int) -> Awaitable[None]:
return confirm_blob(
"confirm_data",
TR.ethereum__title_input_data,
@@ -351,7 +352,7 @@ def confirm_empty_typed_message() -> Awaitable[None]:
)
-async def should_show_domain(name: bytes, version: bytes) -> bool:
+async def should_show_domain(name: AnyBytes, version: AnyBytes) -> bool:
domain_name = decode_typed_data(name, "string")
domain_version = decode_typed_data(version, "string")
@@ -418,7 +419,7 @@ async def should_show_array(
async def confirm_typed_value(
name: str,
- value: bytes,
+ value: AnyBytes,
parent_objects: list[str],
field: EthereumFieldType,
array_index: int | None = None,
diff --git a/core/src/apps/ethereum/sign_message.py b/core/src/apps/ethereum/sign_message.py
index 576503c6..ce7a7949 100644
--- a/core/src/apps/ethereum/sign_message.py
+++ b/core/src/apps/ethereum/sign_message.py
@@ -3,6 +3,8 @@ from typing import TYPE_CHECKING
from .keychain import PATTERNS_ADDRESS, with_keychain_from_path
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import EthereumMessageSignature, EthereumSignMessage
from apps.common.keychain import Keychain
@@ -10,7 +12,7 @@ if TYPE_CHECKING:
from .definitions import Definitions
-def message_digest(message: bytes) -> bytes:
+def message_digest(message: AnyBytes) -> bytes:
from trezor.crypto.hashlib import sha3_256
from trezor.utils import HashWriter
diff --git a/core/src/apps/ethereum/sign_tx.py b/core/src/apps/ethereum/sign_tx.py
index da19da6f..95828bf7 100644
--- a/core/src/apps/ethereum/sign_tx.py
+++ b/core/src/apps/ethereum/sign_tx.py
@@ -11,6 +11,7 @@ from .helpers import address_from_bytes, bytes_from_address
from .keychain import with_keychain_from_chain_id
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Iterable
from trezor.messages import (
@@ -305,7 +306,9 @@ async def _handle_erc20(
msg: MsgInSignTx,
definitions: Definitions,
address_bytes: bytes,
-) -> tuple[EthereumTokenInfo | None, bytes | None, bytes | None, bytes, int | None]:
+) -> tuple[
+ EthereumTokenInfo | None, AnyBytes | None, AnyBytes | None, AnyBytes, int | None
+]:
# local_cache_attribute
data_initial_chunk = msg.data_initial_chunk
SC_FUNC_SIG_BYTES = constants.SC_FUNC_SIG_BYTES
diff --git a/core/src/apps/ethereum/sign_typed_data.py b/core/src/apps/ethereum/sign_typed_data.py
index b8c1fe4e..c1db9372 100644
--- a/core/src/apps/ethereum/sign_typed_data.py
+++ b/core/src/apps/ethereum/sign_typed_data.py
@@ -9,6 +9,8 @@ from .keychain import PATTERNS_ADDRESS, with_keychain_from_path
from .layout import should_show_struct
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import (
EthereumFieldType,
EthereumSignTypedData,
@@ -61,7 +63,7 @@ async def sign_typed_data(
async def _generate_typed_data_hash(
primary_type: str,
metamask_v4_compat: bool = True,
- show_message_hash: bytes | None = None,
+ show_message_hash: AnyBytes | None = None,
) -> bytes:
"""
Generate typed data hash according to EIP-712 specification
@@ -130,7 +132,7 @@ def get_hash_writer() -> HashWriter:
return HashWriter(sha3_256(keccak=True))
-def keccak256(message: bytes) -> bytes:
+def keccak256(message: AnyBytes) -> bytes:
h = get_hash_writer()
h.extend(message)
return h.get_digest()
@@ -368,7 +370,7 @@ class TypedDataEnvelope:
def encode_field(
w: HashWriter,
field: EthereumFieldType,
- value: bytes,
+ value: AnyBytes,
) -> None:
"""
SPEC:
@@ -413,7 +415,7 @@ def encode_field(
raise ValueError # Unsupported data type for field encoding
-def write_leftpad32(w: HashWriter, value: bytes, signed: bool = False) -> None:
+def write_leftpad32(w: HashWriter, value: AnyBytes, signed: bool = False) -> None:
assert len(value) <= 32
# Values need to be sign-extended, so accounting for negative ints
@@ -427,7 +429,7 @@ def write_leftpad32(w: HashWriter, value: bytes, signed: bool = False) -> None:
w.extend(value)
-def _validate_value(field: EthereumFieldType, value: bytes) -> None:
+def _validate_value(field: EthereumFieldType, value: AnyBytes) -> None:
"""
Make sure the byte data we receive are not corrupted or incorrect.
@@ -449,7 +451,7 @@ def _validate_value(field: EthereumFieldType, value: bytes) -> None:
raise DataError("Invalid address")
elif field.data_type == EthereumDataType.STRING:
try:
- value.decode()
+ bytes(value).decode()
except UnicodeError:
raise DataError("Invalid UTF-8")
@@ -518,7 +520,7 @@ async def _get_array_size(member_path: list[int]) -> int:
async def get_value(
field: EthereumFieldType,
member_value_path: list[int],
-) -> bytes:
+) -> AnyBytes:
"""Get a single value from the client and perform its validation."""
from trezor.messages import EthereumTypedDataValueAck, EthereumTypedDataValueRequest
@@ -535,7 +537,7 @@ async def get_value(
async def _get_name_and_version_for_domain(
typed_data_envelope: TypedDataEnvelope,
-) -> tuple[bytes, bytes]:
+) -> tuple[AnyBytes, AnyBytes]:
domain_name = b"unknown"
domain_version = b"unknown"
diff --git a/core/src/apps/homescreen/device_menu.py b/core/src/apps/homescreen/device_menu.py
index af7c50da..9fffaecb 100644
--- a/core/src/apps/homescreen/device_menu.py
+++ b/core/src/apps/homescreen/device_menu.py
@@ -10,6 +10,8 @@ from trezor.wire import ActionCancelled, PinCancelled
from trezorui_api import CANCELLED, DeviceMenuResult
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import ThpPairedCacheEntry
BLE_MAX_BONDS = 8
@@ -29,7 +31,7 @@ class SubmenuId:
def _get_hostinfo(
- ble_addr: bytes, hostname_map: dict[bytes, ThpPairedCacheEntry]
+ ble_addr: AnyBytes, hostname_map: dict[AnyBytes, ThpPairedCacheEntry]
) -> tuple[str, tuple[str, str] | None]:
# Internal MAC address representation is using reversed byte order.
mac = ":".join(f"{byte:02X}" for byte in reversed(ble_addr))
@@ -39,7 +41,7 @@ def _get_hostinfo(
def _get_hostname(
- ble_addr: bytes, hostname_map: dict[bytes, ThpPairedCacheEntry]
+ ble_addr: AnyBytes, hostname_map: dict[AnyBytes, ThpPairedCacheEntry]
) -> str:
mac, hostinfo = _get_hostinfo(ble_addr, hostname_map)
return mac if hostinfo is None else hostinfo[0]
diff --git a/core/src/apps/management/apply_settings.py b/core/src/apps/management/apply_settings.py
index 61b3ff34..17712f19 100644
--- a/core/src/apps/management/apply_settings.py
+++ b/core/src/apps/management/apply_settings.py
@@ -8,10 +8,11 @@ from trezor.ui.layouts import confirm_action
from trezor.wire import DataError
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.enums import SafetyCheckLevel
from trezor.messages import ApplySettings, Success
-
BRT_PROTECT_CALL = ButtonRequestType.ProtectCall # CACHE
@@ -35,7 +36,7 @@ async def _load_homescreen(length: int) -> bytearray:
return buf
-def _validate_homescreen(homescreen: bytes) -> None:
+def _validate_homescreen(homescreen: AnyBytes) -> None:
if homescreen == b"":
return
@@ -164,7 +165,7 @@ async def apply_settings(msg: ApplySettings) -> Success:
return Success(message="Settings applied")
-async def _require_confirm_change_homescreen(homescreen: bytes) -> None:
+async def _require_confirm_change_homescreen(homescreen: AnyBytes) -> None:
from trezor.ui.layouts import confirm_homescreen
await confirm_homescreen(homescreen)
diff --git a/core/src/apps/management/authenticate_device.py b/core/src/apps/management/authenticate_device.py
index ad6d4033..81b506c2 100644
--- a/core/src/apps/management/authenticate_device.py
+++ b/core/src/apps/management/authenticate_device.py
@@ -1,11 +1,13 @@
from typing import TYPE_CHECKING
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import AuthenticateDevice, AuthenticityProof
from trezor.utils import BufferReader
-def parse_cert_chain(r: BufferReader) -> list[bytes]:
+def parse_cert_chain(r: BufferReader) -> list[AnyBytes]:
from trezor import wire
from trezor.crypto.der import read_length
diff --git a/core/src/apps/management/reboot_to_bootloader.py b/core/src/apps/management/reboot_to_bootloader.py
index d7605173..8d12b31f 100644
--- a/core/src/apps/management/reboot_to_bootloader.py
+++ b/core/src/apps/management/reboot_to_bootloader.py
@@ -3,6 +3,7 @@ from micropython import const
from typing import TYPE_CHECKING
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import NoReturn
from trezor.enums import BootCommand
@@ -13,8 +14,8 @@ _REBOOT_SUCCESS_TIMEOUT_MS = const(500)
async def install_upgrade(
- firmware_header: bytes, language_data_length: int
-) -> tuple[BootCommand, bytes]:
+ firmware_header: AnyBytes, language_data_length: int
+) -> tuple[BootCommand, AnyBytes]:
from ubinascii import hexlify
from trezor import TR, utils, wire
diff --git a/core/src/apps/management/reset_device/__init__.py b/core/src/apps/management/reset_device/__init__.py
index 5bb4e7fe..b10b4bf2 100644
--- a/core/src/apps/management/reset_device/__init__.py
+++ b/core/src/apps/management/reset_device/__init__.py
@@ -16,6 +16,8 @@ if __debug__:
import storage.debug
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import ResetDevice, Success
@@ -321,7 +323,7 @@ def _validate_reset_device(msg: ResetDevice) -> None:
def _compute_secret_from_entropy(
- int_entropy: bytes, ext_entropy: bytes, strength_bits: int
+ int_entropy: AnyBytes, ext_entropy: AnyBytes, strength_bits: int
) -> bytes:
from trezor.crypto import hashlib
diff --git a/core/src/apps/management/wipe_device.py b/core/src/apps/management/wipe_device.py
index 1ac19c6f..4f964c49 100644
--- a/core/src/apps/management/wipe_device.py
+++ b/core/src/apps/management/wipe_device.py
@@ -4,15 +4,13 @@ from trezor import utils
from trezor.wire.context import get_context, try_get_ctx_ids
if TYPE_CHECKING:
- from typing import NoReturn
-
from trezor.messages import WipeDevice
if __debug__:
from trezor import log
-async def wipe_device(msg: WipeDevice) -> NoReturn:
+async def wipe_device(msg: WipeDevice) -> None:
import storage
from trezor import TR, config, translations
from trezor.enums import ButtonRequestType
diff --git a/core/src/apps/misc/sign_identity.py b/core/src/apps/misc/sign_identity.py
index fd6298a4..54c90c94 100644
--- a/core/src/apps/misc/sign_identity.py
+++ b/core/src/apps/misc/sign_identity.py
@@ -5,6 +5,8 @@ from trezor.crypto.hashlib import sha256
from apps.common import coininfo
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import IdentityType, SignedIdentity, SignIdentity
from apps.common.paths import Bip32Path
@@ -100,7 +102,7 @@ def get_identity_path(identity: str, index: int, num: int) -> Bip32Path:
def sign_challenge(
seckey: bytes,
- challenge_hidden: bytes,
+ challenge_hidden: AnyBytes,
challenge_visual: str,
sigtype: str | coininfo.CoinInfo,
curve: str,
diff --git a/core/src/apps/nem/mosaic/__init__.py b/core/src/apps/nem/mosaic/__init__.py
index c8044d5c..cd1c1eee 100644
--- a/core/src/apps/nem/mosaic/__init__.py
+++ b/core/src/apps/nem/mosaic/__init__.py
@@ -3,6 +3,8 @@ from typing import TYPE_CHECKING
from . import layout, serialize
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import (
NEMMosaicCreation,
NEMMosaicSupplyChange,
@@ -11,18 +13,18 @@ if TYPE_CHECKING:
async def mosaic_creation(
- public_key: bytes,
+ public_key: AnyBytes,
common: NEMTransactionCommon,
creation: NEMMosaicCreation,
-) -> bytes:
+) -> bytearray:
await layout.ask_mosaic_creation(common, creation)
return serialize.serialize_mosaic_creation(common, creation, public_key)
async def supply_change(
- public_key: bytes,
+ public_key: AnyBytes,
common: NEMTransactionCommon,
change: NEMMosaicSupplyChange,
-) -> bytes:
+) -> bytearray:
await layout.ask_supply_change(common, change)
return serialize.serialize_mosaic_supply_change(common, change, public_key)
diff --git a/core/src/apps/nem/mosaic/serialize.py b/core/src/apps/nem/mosaic/serialize.py
index 31b02530..30ffced5 100644
--- a/core/src/apps/nem/mosaic/serialize.py
+++ b/core/src/apps/nem/mosaic/serialize.py
@@ -8,6 +8,8 @@ from ..writers import (
)
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import (
NEMMosaicCreation,
NEMMosaicSupplyChange,
@@ -17,8 +19,8 @@ if TYPE_CHECKING:
def serialize_mosaic_creation(
- common: NEMTransactionCommon, creation: NEMMosaicCreation, public_key: bytes
-) -> bytes:
+ common: NEMTransactionCommon, creation: NEMMosaicCreation, public_key: AnyBytes
+) -> bytearray:
from ..helpers import NEM_TRANSACTION_TYPE_MOSAIC_CREATION
w = serialize_tx_common(common, public_key, NEM_TRANSACTION_TYPE_MOSAIC_CREATION)
@@ -70,8 +72,8 @@ def serialize_mosaic_creation(
def serialize_mosaic_supply_change(
- common: NEMTransactionCommon, change: NEMMosaicSupplyChange, public_key: bytes
-) -> bytes:
+ common: NEMTransactionCommon, change: NEMMosaicSupplyChange, public_key: AnyBytes
+) -> bytearray:
from ..helpers import NEM_TRANSACTION_TYPE_MOSAIC_SUPPLY_CHANGE
w = serialize_tx_common(
diff --git a/core/src/apps/nem/multisig/__init__.py b/core/src/apps/nem/multisig/__init__.py
index 7b553299..a1ba64f1 100644
--- a/core/src/apps/nem/multisig/__init__.py
+++ b/core/src/apps/nem/multisig/__init__.py
@@ -3,6 +3,8 @@ from typing import TYPE_CHECKING
from . import layout, serialize
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import (
NEMAggregateModification,
NEMSignTx,
@@ -14,22 +16,27 @@ async def ask(msg: NEMSignTx) -> None:
await layout.ask_multisig(msg)
-def initiate(public_key: bytes, common: NEMTransactionCommon, inner_tx: bytes) -> bytes:
+def initiate(
+ public_key: AnyBytes, common: NEMTransactionCommon, inner_tx: AnyBytes
+) -> bytearray:
return serialize.serialize_multisig(common, public_key, inner_tx)
def cosign(
- public_key: bytes, common: NEMTransactionCommon, inner_tx: bytes, signer: bytes
-) -> bytes:
+ public_key: AnyBytes,
+ common: NEMTransactionCommon,
+ inner_tx: AnyBytes,
+ signer: AnyBytes,
+) -> bytearray:
return serialize.serialize_multisig_signature(common, public_key, inner_tx, signer)
async def aggregate_modification(
- public_key: bytes,
+ public_key: AnyBytes,
common: NEMTransactionCommon,
aggr: NEMAggregateModification,
multisig: bool,
-) -> bytes:
+) -> bytearray:
await layout.ask_aggregate_modification(common, aggr, multisig)
w = serialize.serialize_aggregate_modification(common, aggr, public_key)
diff --git a/core/src/apps/nem/multisig/serialize.py b/core/src/apps/nem/multisig/serialize.py
index 3c4e71d2..efd7c54a 100644
--- a/core/src/apps/nem/multisig/serialize.py
+++ b/core/src/apps/nem/multisig/serialize.py
@@ -3,13 +3,15 @@ from typing import TYPE_CHECKING
from ..writers import serialize_tx_common, write_bytes_with_len, write_uint32_le
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import NEMAggregateModification, NEMTransactionCommon
from trezor.utils import Writer
def serialize_multisig(
- common: NEMTransactionCommon, public_key: bytes, inner: bytes
-) -> bytes:
+ common: NEMTransactionCommon, public_key: AnyBytes, inner: AnyBytes
+) -> bytearray:
from ..helpers import NEM_TRANSACTION_TYPE_MULTISIG
w = serialize_tx_common(common, public_key, NEM_TRANSACTION_TYPE_MULTISIG)
@@ -19,10 +21,10 @@ def serialize_multisig(
def serialize_multisig_signature(
common: NEMTransactionCommon,
- public_key: bytes,
- inner: bytes,
- address_public_key: bytes,
-) -> bytes:
+ public_key: AnyBytes,
+ inner: AnyBytes,
+ address_public_key: AnyBytes,
+) -> bytearray:
from trezor.crypto import hashlib, nem
from ..helpers import NEM_TRANSACTION_TYPE_MULTISIG_SIGNATURE
@@ -38,7 +40,7 @@ def serialize_multisig_signature(
def serialize_aggregate_modification(
- common: NEMTransactionCommon, mod: NEMAggregateModification, public_key: bytes
+ common: NEMTransactionCommon, mod: NEMAggregateModification, public_key: AnyBytes
) -> bytearray:
from ..helpers import NEM_TRANSACTION_TYPE_AGGREGATE_MODIFICATION
@@ -54,7 +56,7 @@ def serialize_aggregate_modification(
def write_cosignatory_modification(
- w: Writer, cosignatory_type: int, cosignatory_pubkey: bytes
+ w: Writer, cosignatory_type: int, cosignatory_pubkey: AnyBytes
) -> None:
write_uint32_le(w, 4 + 4 + len(cosignatory_pubkey))
write_uint32_le(w, cosignatory_type)
diff --git a/core/src/apps/nem/namespace/__init__.py b/core/src/apps/nem/namespace/__init__.py
index d5760479..4662ee40 100644
--- a/core/src/apps/nem/namespace/__init__.py
+++ b/core/src/apps/nem/namespace/__init__.py
@@ -1,14 +1,16 @@
from typing import TYPE_CHECKING
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import NEMProvisionNamespace, NEMTransactionCommon
async def namespace(
- public_key: bytes,
+ public_key: AnyBytes,
common: NEMTransactionCommon,
namespace: NEMProvisionNamespace,
-) -> bytes:
+) -> bytearray:
from . import layout, serialize
await layout.ask_provision_namespace(common, namespace)
diff --git a/core/src/apps/nem/namespace/serialize.py b/core/src/apps/nem/namespace/serialize.py
index 2c3c9b68..99069629 100644
--- a/core/src/apps/nem/namespace/serialize.py
+++ b/core/src/apps/nem/namespace/serialize.py
@@ -1,12 +1,14 @@
from typing import TYPE_CHECKING
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import NEMProvisionNamespace, NEMTransactionCommon
def serialize_provision_namespace(
- common: NEMTransactionCommon, namespace: NEMProvisionNamespace, public_key: bytes
-) -> bytes:
+ common: NEMTransactionCommon, namespace: NEMProvisionNamespace, public_key: AnyBytes
+) -> bytearray:
from ..helpers import NEM_TRANSACTION_TYPE_PROVISION_NAMESPACE
from ..writers import (
serialize_tx_common,
diff --git a/core/src/apps/nem/transfer/__init__.py b/core/src/apps/nem/transfer/__init__.py
index c6a95d39..551e4c8f 100644
--- a/core/src/apps/nem/transfer/__init__.py
+++ b/core/src/apps/nem/transfer/__init__.py
@@ -3,17 +3,19 @@ from typing import TYPE_CHECKING
from . import layout, serialize
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.crypto import bip32
from trezor.messages import NEMImportanceTransfer, NEMTransactionCommon, NEMTransfer
async def transfer(
- public_key: bytes,
+ public_key: AnyBytes,
common: NEMTransactionCommon,
transfer: NEMTransfer,
node: bip32.HDNode,
chunkify: bool,
-) -> bytes:
+) -> bytearray:
transfer.mosaics = serialize.canonicalize_mosaics(transfer.mosaics)
payload, encrypted = serialize.get_transfer_payload(transfer, node)
@@ -26,9 +28,9 @@ async def transfer(
async def importance_transfer(
- public_key: bytes,
+ public_key: AnyBytes,
common: NEMTransactionCommon,
imp: NEMImportanceTransfer,
-) -> bytes:
+) -> bytearray:
await layout.ask_importance_transfer(common, imp)
return serialize.serialize_importance_transfer(common, imp, public_key)
diff --git a/core/src/apps/nem/transfer/serialize.py b/core/src/apps/nem/transfer/serialize.py
index b02d238f..17db2858 100644
--- a/core/src/apps/nem/transfer/serialize.py
+++ b/core/src/apps/nem/transfer/serialize.py
@@ -8,6 +8,8 @@ from ..writers import (
)
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.crypto import bip32
from trezor.messages import (
NEMImportanceTransfer,
@@ -21,8 +23,8 @@ if TYPE_CHECKING:
def serialize_transfer(
common: NEMTransactionCommon,
transfer: NEMTransfer,
- public_key: bytes,
- payload: bytes,
+ public_key: AnyBytes,
+ payload: AnyBytes,
encrypted: bool,
) -> bytearray:
from ..helpers import NEM_TRANSACTION_TYPE_TRANSFER
@@ -69,8 +71,8 @@ def serialize_mosaic(w: Writer, namespace: str, mosaic: str, quantity: int) -> N
def serialize_importance_transfer(
- common: NEMTransactionCommon, imp: NEMImportanceTransfer, public_key: bytes
-) -> bytes:
+ common: NEMTransactionCommon, imp: NEMImportanceTransfer, public_key: AnyBytes
+) -> bytearray:
from ..helpers import NEM_TRANSACTION_TYPE_IMPORTANCE_TRANSFER
w = serialize_tx_common(
@@ -84,7 +86,7 @@ def serialize_importance_transfer(
def get_transfer_payload(
transfer: NEMTransfer, node: bip32.HDNode
-) -> tuple[bytes, bool]:
+) -> tuple[AnyBytes, bool]:
from trezor.crypto import random
from ..helpers import AES_BLOCK_SIZE, NEM_SALT_SIZE
diff --git a/core/src/apps/nem/validators.py b/core/src/apps/nem/validators.py
index 361af1f3..743b2357 100644
--- a/core/src/apps/nem/validators.py
+++ b/core/src/apps/nem/validators.py
@@ -3,6 +3,8 @@ from typing import TYPE_CHECKING
from trezor.wire import ProcessError
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import NEMSignTx, NEMTransactionCommon
@@ -187,7 +189,7 @@ def _validate_common(common: NEMTransactionCommon, inner: bool = False) -> None:
_validate_public_key(signer, "Invalid signer public key in inner transaction")
-def _validate_public_key(public_key: bytes | None, err_msg: str) -> None:
+def _validate_public_key(public_key: AnyBytes | None, err_msg: str) -> None:
from .helpers import NEM_PUBLIC_KEY_SIZE
if not public_key:
diff --git a/core/src/apps/nem/writers.py b/core/src/apps/nem/writers.py
index 3498c460..4c606b69 100644
--- a/core/src/apps/nem/writers.py
+++ b/core/src/apps/nem/writers.py
@@ -3,13 +3,15 @@ from typing import TYPE_CHECKING
from apps.common.writers import write_bytes_unchecked, write_uint32_le, write_uint64_le
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import NEMTransactionCommon
from trezor.utils import Writer
def serialize_tx_common(
common: NEMTransactionCommon,
- public_key: bytes,
+ public_key: AnyBytes,
transaction_type: int,
version: int | None = None,
) -> bytearray:
@@ -28,6 +30,6 @@ def serialize_tx_common(
return w
-def write_bytes_with_len(w: Writer, buf: bytes) -> None:
+def write_bytes_with_len(w: Writer, buf: AnyBytes) -> None:
write_uint32_le(w, len(buf))
write_bytes_unchecked(w, buf)
diff --git a/core/src/apps/ripple/serialize.py b/core/src/apps/ripple/serialize.py
index d4085627..f18f4a3d 100644
--- a/core/src/apps/ripple/serialize.py
+++ b/core/src/apps/ripple/serialize.py
@@ -12,6 +12,8 @@ from micropython import const
from typing import TYPE_CHECKING
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import RippleSignTx
from trezor.utils import Writer
@@ -26,8 +28,8 @@ _FIELD_TYPE_ACCOUNT = const(8)
def serialize(
msg: RippleSignTx,
source_address: str,
- pubkey: bytes,
- signature: bytes | None = None,
+ pubkey: AnyBytes,
+ signature: AnyBytes | None = None,
) -> bytearray:
# must be sorted numerically first by type and then by name
fields_to_write = ( # field_type, field_key, value
@@ -51,7 +53,7 @@ def serialize(
def _write(
- w: Writer, field_type: int, field_key: int, value: int | bytes | str | None
+ w: Writer, field_type: int, field_key: int, value: int | AnyBytes | str | None
) -> None:
from . import helpers
@@ -89,13 +91,14 @@ def _write(
assert isinstance(value, str)
write_bytes_varint(w, helpers.decode_address(value))
elif field_type == _FIELD_TYPE_VL:
- assert isinstance(value, (bytes, bytearray))
+ # XXX this should be AnyBytes, but that doesn't exist at runtime
+ assert isinstance(value, (bytes, bytearray, memoryview))
write_bytes_varint(w, value)
else:
raise ValueError("Unknown field type")
-def write_bytes_varint(w: Writer, value: bytes) -> None:
+def write_bytes_varint(w: Writer, value: AnyBytes) -> None:
"""Serialize a variable length bytes."""
append = w.append # local_cache_attribute
diff --git a/core/src/apps/solana/definitions.py b/core/src/apps/solana/definitions.py
index 5c91df23..3917c51d 100644
--- a/core/src/apps/solana/definitions.py
+++ b/core/src/apps/solana/definitions.py
@@ -3,6 +3,8 @@ from typing import TYPE_CHECKING
from trezor.messages import SolanaTokenInfo
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from typing_extensions import Self
@@ -13,7 +15,7 @@ class Definitions:
self._tokens = tokens or {}
@classmethod
- def from_encoded(cls, encoded_token: bytes | None) -> Self:
+ def from_encoded(cls, encoded_token: AnyBytes | None) -> Self:
from apps.common.definitions import decode_definition
tokens: dict[bytes, SolanaTokenInfo] = {}
@@ -21,7 +23,7 @@ class Definitions:
# get token definition
if encoded_token is not None:
token = decode_definition(encoded_token, SolanaTokenInfo)
- tokens[token.mint] = token
+ tokens[bytes(token.mint)] = token
return cls(tokens)
diff --git a/core/src/apps/solana/transaction/__init__.py b/core/src/apps/solana/transaction/__init__.py
index 989ccfa2..42e454e5 100644
--- a/core/src/apps/solana/transaction/__init__.py
+++ b/core/src/apps/solana/transaction/__init__.py
@@ -21,6 +21,8 @@ from .instructions import (
from .parse import parse_block_hash, parse_pubkey, parse_var_int
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from ..types import Account, Address, AddressReference, RawInstruction
@@ -53,12 +55,12 @@ class Transaction:
address_lookup_tables_rw_addresses: list[AddressReference]
address_lookup_tables_ro_addresses: list[AddressReference]
- def __init__(self, serialized_tx: bytes) -> None:
+ def __init__(self, serialized_tx: AnyBytes) -> None:
self._parse_transaction(serialized_tx)
self._create_instructions()
self._determine_if_blind_signing()
- def _parse_transaction(self, serialized_tx: bytes) -> None:
+ def _parse_transaction(self, serialized_tx: AnyBytes) -> None:
serialized_tx_reader = BufferReader(serialized_tx)
self._parse_header(serialized_tx_reader)
@@ -74,8 +76,6 @@ class Transaction:
raise DataError("Invalid transaction")
def _parse_header(self, serialized_tx_reader: BufferReader) -> None:
- self.version: int | None = None
-
if serialized_tx_reader.peek() & 0b10000000:
self.version = serialized_tx_reader.get() & 0b01111111
# only version 0 is supported
diff --git a/core/src/apps/stellar/helpers.py b/core/src/apps/stellar/helpers.py
index e6bf3c60..349f6699 100644
--- a/core/src/apps/stellar/helpers.py
+++ b/core/src/apps/stellar/helpers.py
@@ -1,5 +1,10 @@
+from typing import TYPE_CHECKING
+
from trezor.crypto import base32
+if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
def public_key_from_address(address: str) -> bytes:
"""Extracts public key from an address
@@ -15,7 +20,7 @@ def public_key_from_address(address: str) -> bytes:
return b[1:-2]
-def address_from_public_key(pubkey: bytes) -> str:
+def address_from_public_key(pubkey: AnyBytes) -> str:
"""Returns the base32-encoded version of public key bytes (G...)"""
address = bytearray()
address.append(6 << 3) # version -> 'G'
@@ -25,7 +30,7 @@ def address_from_public_key(pubkey: bytes) -> str:
return base32.encode(address)
-def _crc16_checksum(data: bytes) -> bytes:
+def _crc16_checksum(data: AnyBytes) -> bytes:
"""Returns the CRC-16 checksum of bytearray bytes
Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html
diff --git a/core/src/apps/stellar/operations/layout.py b/core/src/apps/stellar/operations/layout.py
index f3fde0ea..8c7d627e 100644
--- a/core/src/apps/stellar/operations/layout.py
+++ b/core/src/apps/stellar/operations/layout.py
@@ -15,6 +15,8 @@ from trezor.wire import DataError, ProcessError
from ..layout import format_amount
if TYPE_CHECKING:
+ from buffer_types import StrOrBytes
+
from trezor.messages import (
StellarAccountMergeOp,
StellarAllowTrustOp,
@@ -140,18 +142,22 @@ async def _confirm_offer(
buying_asset = op.buying_asset # local_cache_attribute
selling_asset = op.selling_asset # local_cache_attribute
+ buying: PropertyType
+ selling: PropertyType
+ price: PropertyType
+
if StellarManageBuyOfferOp.is_type_of(op):
- buying: PropertyType = (
+ buying = (
TR.stellar__buying,
format_amount(op.amount, buying_asset),
False,
)
- selling: PropertyType = (
+ selling = (
TR.stellar__selling,
format_asset(selling_asset),
False,
)
- price: PropertyType = (
+ price = (
TR.stellar__price_per_template.format(format_asset(selling_asset)),
str(op.price_n / op.price_d),
False,
@@ -162,13 +168,13 @@ async def _confirm_offer(
(buying, selling, price),
)
else:
- selling: PropertyType = (
+ selling = (
TR.stellar__selling,
format_amount(op.amount, selling_asset),
False,
)
- buying: PropertyType = (TR.stellar__buying, format_asset(buying_asset), False)
- price: PropertyType = (
+ buying = (TR.stellar__buying, format_asset(buying_asset), False)
+ price = (
TR.stellar__price_per_template.format(format_asset(buying_asset)),
str(op.price_n / op.price_d),
False,
@@ -304,7 +310,7 @@ async def confirm_set_options_op(op: StellarSetOptionsOp) -> None:
title = TR.stellar__add_signer
else:
title = TR.stellar__remove_signer
- data: str | bytes = ""
+ data: StrOrBytes = ""
if signer_type == StellarSignerType.ACCOUNT:
description = TR.words__account
data = helpers.address_from_public_key(signer_key)
diff --git a/core/src/apps/stellar/operations/serialize.py b/core/src/apps/stellar/operations/serialize.py
index a070aa07..133205ee 100644
--- a/core/src/apps/stellar/operations/serialize.py
+++ b/core/src/apps/stellar/operations/serialize.py
@@ -13,6 +13,8 @@ from ..writers import (
)
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import (
StellarAccountMergeOp,
StellarAllowTrustOp,
@@ -230,7 +232,7 @@ def _write_asset(w: Writer, asset: StellarAsset) -> None:
write_pubkey(w, asset.issuer)
-def _write_claimable_balance_id(w: Writer, claimable_balance_id: bytes) -> None:
+def _write_claimable_balance_id(w: Writer, claimable_balance_id: AnyBytes) -> None:
if len(claimable_balance_id) != 36: # 4 bytes type + 32 bytes data
raise DataError("Stellar: invalid claimable balance id length")
if claimable_balance_id[:4] != b"\x00\x00\x00\x00": # CLAIMABLE_BALANCE_ID_TYPE_V0
diff --git a/core/src/apps/stellar/writers.py b/core/src/apps/stellar/writers.py
index 741451cb..783cae20 100644
--- a/core/src/apps/stellar/writers.py
+++ b/core/src/apps/stellar/writers.py
@@ -8,12 +8,12 @@ write_uint32 = writers.write_uint32_be
write_uint64 = writers.write_uint64_be
if TYPE_CHECKING:
- from typing import AnyStr
+ from buffer_types import StrOrBytes
from trezor.utils import Writer
-def write_string(w: Writer, s: AnyStr) -> None:
+def write_string(w: Writer, s: StrOrBytes) -> None:
"""Write XDR string padded to a multiple of 4 bytes."""
# NOTE: 2 bytes smaller than if-else
buf = s.encode() if isinstance(s, str) else s
diff --git a/core/src/apps/tezos/helpers.py b/core/src/apps/tezos/helpers.py
index 50106979..5c2524e2 100644
--- a/core/src/apps/tezos/helpers.py
+++ b/core/src/apps/tezos/helpers.py
@@ -7,6 +7,8 @@ from trezor.wire import DataError
from apps.common.readers import read_uint32_be
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.utils import Writer
@@ -80,7 +82,7 @@ OP_TAG_DELEGATION = const(110)
_EP_TAG_NAMED = const(255)
-def base58_encode_check(payload: bytes, prefix: str | None = None) -> str:
+def base58_encode_check(payload: AnyBytes, prefix: str | None = None) -> str:
from trezor.crypto import base58
result = payload
@@ -101,7 +103,7 @@ def write_instruction(w: Writer, instruction: str) -> None:
write_bytes_unchecked(w, MICHELSON_INSTRUCTION_BYTES[instruction])
-def check_script_size(script: bytes) -> None:
+def check_script_size(script: AnyBytes) -> None:
try:
r = BufferReader(script)
n = read_uint32_be(r)
@@ -112,7 +114,7 @@ def check_script_size(script: bytes) -> None:
raise DataError("Invalid script")
-def check_tx_params_size(params: bytes) -> None:
+def check_tx_params_size(params: AnyBytes) -> None:
try:
r = BufferReader(params)
tag = r.get()
diff --git a/core/src/apps/tezos/sign_tx.py b/core/src/apps/tezos/sign_tx.py
index 5153657f..c39f6df4 100644
--- a/core/src/apps/tezos/sign_tx.py
+++ b/core/src/apps/tezos/sign_tx.py
@@ -16,6 +16,8 @@ from .helpers import ( # symbols used more than once
)
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.messages import (
TezosContractID,
TezosDelegationOp,
@@ -163,7 +165,7 @@ async def sign_tx(msg: TezosSignTx, keychain: Keychain) -> TezosSignedTx:
)
-def _get_address_by_tag(address_hash: bytes) -> str:
+def _get_address_by_tag(address_hash: AnyBytes) -> str:
prefixes = ["tz1", "tz2", "tz3"]
tag = int(address_hash[0])
@@ -343,7 +345,7 @@ def _encode_common(
def _encode_data_with_bool_prefix(
- w: Writer, data: bytes | None, expected_length: int
+ w: Writer, data: AnyBytes | None, expected_length: int
) -> None:
if data:
helpers.write_bool(w, True)
diff --git a/core/src/apps/thp/credential_manager.py b/core/src/apps/thp/credential_manager.py
index a2e6a050..39a37385 100644
--- a/core/src/apps/thp/credential_manager.py
+++ b/core/src/apps/thp/credential_manager.py
@@ -10,6 +10,8 @@ from trezor.messages import (
from trezor.wire.message_handler import wrap_protobuf_load
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from apps.common.paths import Slip21Path
_THP_CREDENTIAL_KEY_PATH_PREFIX = [b"TREZOR", b"THP credential authentication key"]
@@ -44,7 +46,7 @@ def invalidate_cred_auth_key() -> None:
def issue_credential(
- host_static_public_key: bytes,
+ host_static_public_key: AnyBytes,
credential_metadata: ThpCredentialMetadata,
) -> bytes:
"""
@@ -65,7 +67,7 @@ def issue_credential(
def decode_credential(
- encoded_pairing_credential_message: bytes,
+ encoded_pairing_credential_message: AnyBytes,
) -> ThpPairingCredential:
"""
Decode a protobuf encoded pairing credential.
@@ -78,7 +80,7 @@ def decode_credential(
def validate_credential(
credential: ThpPairingCredential,
- host_static_public_key: bytes,
+ host_static_public_key: AnyBytes,
) -> bool:
"""
Validate a pairing credential binded to the provided host static public key.
@@ -94,8 +96,8 @@ def validate_credential(
def decode_and_validate_credential(
- encoded_pairing_credential_message: bytes,
- host_static_public_key: bytes,
+ encoded_pairing_credential_message: AnyBytes,
+ host_static_public_key: AnyBytes,
) -> bool:
"""
Decode a protobuf encoded pairing credential and validate it
diff --git a/core/src/apps/webauthn/credential.py b/core/src/apps/webauthn/credential.py
index 669fd587..beb53f81 100644
--- a/core/src/apps/webauthn/credential.py
+++ b/core/src/apps/webauthn/credential.py
@@ -14,6 +14,7 @@ from apps.common.paths import HARDENED
from .common import COSE_ALG_EDDSA, COSE_ALG_ES256, COSE_CURVE_ED25519, COSE_CURVE_P256
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Iterable
from trezor.crypto import bip32
@@ -90,7 +91,7 @@ class Credential:
def sign(self, data: Iterable[bytes]) -> bytes:
raise NotImplementedError
- def _u2f_sign(self, data: Iterable[bytes]) -> bytes:
+ def _u2f_sign(self, data: Iterable[AnyBytes]) -> AnyBytes:
dig = hashlib.sha256()
for segment in data:
dig.update(segment)
@@ -217,7 +218,7 @@ class Fido2Credential(Credential):
get = data.get # local_cache_attribute
cred = cls()
- cred.rp_id = get(_CRED_ID_RP_ID, None)
+ cred.rp_id = get(_CRED_ID_RP_ID, "")
cred.rp_id_hash = rp_id_hash
cred.rp_name = get(_CRED_ID_RP_NAME, None)
cred.user_id = get(_CRED_ID_USER_ID, None)
@@ -329,7 +330,7 @@ class Fido2Credential(Credential):
)
raise TypeError
- def sign(self, data: Iterable[bytes]) -> bytes:
+ def sign(self, data: Iterable[bytes]) -> AnyBytes:
if (self.algorithm, self.curve) == (
COSE_ALG_ES256,
COSE_CURVE_P256,
@@ -345,7 +346,7 @@ class Fido2Credential(Credential):
raise TypeError
- def bogus_signature(self) -> bytes:
+ def bogus_signature(self) -> AnyBytes:
if (self.algorithm, self.curve) == (
COSE_ALG_ES256,
COSE_CURVE_P256,
@@ -398,10 +399,10 @@ class U2fCredential(Credential):
def public_key(self) -> bytes:
return nist256p1.publickey(self._private_key(), False)
- def sign(self, data: Iterable[bytes]) -> bytes:
+ def sign(self, data: Iterable[bytes]) -> AnyBytes:
return self._u2f_sign(data)
- def bogus_signature(self) -> bytes:
+ def bogus_signature(self) -> AnyBytes:
return der.encode_seq((b"\x0a" * 32, b"\x0a" * 32))
def generate_key_handle(self) -> None:
diff --git a/core/src/apps/webauthn/fido2.py b/core/src/apps/webauthn/fido2.py
index 4343b0d4..c6ec0baf 100644
--- a/core/src/apps/webauthn/fido2.py
+++ b/core/src/apps/webauthn/fido2.py
@@ -18,6 +18,7 @@ from . import common
from .credential import Credential, Fido2Credential
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Any, Awaitable, Callable, Coroutine, Iterable, Iterator
from .credential import U2fCredential
@@ -1303,7 +1304,7 @@ def _msg_register(req: Msg, dialog_mgr: DialogManager) -> Cmd:
return Cmd(cid, _CMD_MSG, buf)
-def basic_attestation_sign(data: Iterable[bytes]) -> bytes:
+def basic_attestation_sign(data: Iterable[AnyBytes]) -> AnyBytes:
from trezor.crypto import der
dig = hashlib.sha256()
diff --git a/core/src/apps/zcash/signer.py b/core/src/apps/zcash/signer.py
index f97110e5..b54b1e97 100644
--- a/core/src/apps/zcash/signer.py
+++ b/core/src/apps/zcash/signer.py
@@ -6,6 +6,7 @@ from trezor.wire import DataError
from apps.bitcoin.sign_tx.bitcoinlike import Bitcoinlike
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Sequence
from trezor.messages import PrevTx, SignTx, TxInput, TxOutput
@@ -64,7 +65,7 @@ class Zcash(Bitcoinlike):
async def sign_nonsegwit_input(self, i_sign: int) -> None:
await self.sign_nonsegwit_bip143_input(i_sign)
- def sign_bip143_input(self, i: int, txi: TxInput) -> tuple[bytes, bytes]:
+ def sign_bip143_input(self, i: int, txi: TxInput) -> tuple[AnyBytes, AnyBytes]:
from apps.bitcoin.common import ecdsa_sign
node = self.keychain.derive(txi.address_n)
@@ -121,7 +122,7 @@ class Zcash(Bitcoinlike):
# serialize Orchard bundle
write_compact_size(w, 0) # nActionsOrchard
- def output_derive_script(self, txo: TxOutput) -> bytes:
+ def output_derive_script(self, txo: TxOutput) -> AnyBytes:
from trezor.enums import OutputScriptType
from apps.bitcoin import scripts
diff --git a/core/src/apps/zcash/unified_addresses.py b/core/src/apps/zcash/unified_addresses.py
index c172c4cf..fb981c61 100644
--- a/core/src/apps/zcash/unified_addresses.py
+++ b/core/src/apps/zcash/unified_addresses.py
@@ -104,8 +104,8 @@ def decode(addr_str: str, coin: CoinInfo) -> dict[int, bytes]:
if encoding != Encoding.BECH32M:
raise DataError("Bech32m encoding required.")
- decoded = bytearray(convertbits(data, 5, 8, False))
- f4unjumble(memoryview(decoded))
+ decoded = memoryview(bytearray(convertbits(data, 5, 8, False)))
+ f4unjumble(decoded)
# check trailing padding bytes
if decoded[-16:] != padding(hrp):
diff --git a/core/src/storage/__init__.py b/core/src/storage/__init__.py
index 80e66c09..b62eff16 100644
--- a/core/src/storage/__init__.py
+++ b/core/src/storage/__init__.py
@@ -4,9 +4,7 @@ from typing import TYPE_CHECKING
from storage import cache, common, device
if TYPE_CHECKING:
- from typing import Tuple
-
- pass
+ from buffer_types import AnyBytes
def wipe(clear_cache: bool = True) -> None:
@@ -22,7 +20,7 @@ def wipe(clear_cache: bool = True) -> None:
cache.clear_all()
-def wipe_cache(excluded: Tuple[bytes, bytes] | None = None) -> None:
+def wipe_cache(excluded: tuple[AnyBytes, AnyBytes] | None = None) -> None:
cache.clear_all(excluded)
@@ -38,7 +36,7 @@ def init_unlocked() -> None:
common.set_bool(common.APP_DEVICE, device.INITIALIZED, True, public=True)
-def reset(excluded: Tuple[bytes, bytes] | None) -> None:
+def reset(excluded: tuple[AnyBytes, AnyBytes] | None) -> None:
"""
Wipes storage but keeps the device id, device secret, and credential counter unchanged.
"""
diff --git a/core/src/storage/cache.py b/core/src/storage/cache.py
index 6db224a7..d46e477e 100644
--- a/core/src/storage/cache.py
+++ b/core/src/storage/cache.py
@@ -6,9 +6,7 @@ from storage.cache_common import SESSIONLESS_FLAG, SessionlessCache
from trezor import utils
if TYPE_CHECKING:
- from typing import Tuple
-
- pass
+ from buffer_types import AnyBytes
# Cache initialization
_SESSIONLESS_CACHE = SessionlessCache()
@@ -29,7 +27,7 @@ _SESSIONLESS_CACHE.clear()
gc.collect()
-def clear_all(excluded: Tuple[bytes, bytes] | None = None) -> None:
+def clear_all(excluded: tuple[AnyBytes, AnyBytes] | None = None) -> None:
"""
Clears all data from both the protocol cache and the sessionless cache.
"""
diff --git a/core/src/storage/cache_codec.py b/core/src/storage/cache_codec.py
index f6402b4d..06d9f46f 100644
--- a/core/src/storage/cache_codec.py
+++ b/core/src/storage/cache_codec.py
@@ -6,6 +6,7 @@ from storage.cache_common import DataCache
from trezor import utils
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import TypeVar
T = TypeVar("T")
@@ -87,7 +88,7 @@ def get_active_session() -> SessionCache | None:
return _SESSIONS[_active_session_idx]
-def start_session(received_session_id: bytes | None = None) -> bytes:
+def start_session(received_session_id: AnyBytes | None = None) -> AnyBytes:
global _active_session_idx
global _session_usage_counter
diff --git a/core/src/storage/cache_common.py b/core/src/storage/cache_common.py
index dd87f5a0..c5c90ac2 100644
--- a/core/src/storage/cache_common.py
+++ b/core/src/storage/cache_common.py
@@ -24,6 +24,7 @@ APP_RECOVERY_REPEATED_BACKUP_UNLOCKED = const(6 | SESSIONLESS_FLAG)
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Sequence, TypeVar, overload
T = TypeVar("T")
@@ -76,7 +77,7 @@ class DataCache:
utils.ensure(key < len(self.fields))
return self.data[key][0] == 1
- def set(self, key: int, value: bytes | memoryview) -> None:
+ def set(self, key: int, value: AnyBytes) -> None:
utils.ensure(key < len(self.fields))
utils.ensure(len(value) <= self.fields[key])
self.data[key][0] = 1
diff --git a/core/src/storage/cache_thp.py b/core/src/storage/cache_thp.py
index 4cffddc7..dd14dbcc 100644
--- a/core/src/storage/cache_thp.py
+++ b/core/src/storage/cache_thp.py
@@ -1,6 +1,6 @@
import builtins
from micropython import const
-from typing import Sequence
+from typing import TYPE_CHECKING
from storage.cache_common import (
CHANNEL_HOST_STATIC_PUBKEY,
@@ -12,6 +12,10 @@ from storage.cache_common import (
DataCache,
)
+if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+ from typing import Sequence
+
# THP specific constants
_MAX_CHANNELS_COUNT = const(10)
_MAX_SESSIONS_COUNT = const(20)
@@ -162,14 +166,14 @@ def get_new_channel() -> ChannelCache:
return _CHANNELS[index]
-def update_channel_last_used(channel_id: bytes) -> None:
+def update_channel_last_used(channel_id: AnyBytes) -> None:
for channel in _CHANNELS:
if channel.channel_id == channel_id:
channel.last_usage = _get_usage_counter_and_increment()
return
-def update_session_last_used(channel_id: bytes, session_id: bytes) -> None:
+def update_session_last_used(channel_id: AnyBytes, session_id: AnyBytes) -> None:
for session in _SESSIONS:
if session.channel_id == channel_id and session.session_id == session_id:
session.last_usage = _get_usage_counter_and_increment()
@@ -384,7 +388,7 @@ def clear_all() -> None:
channel.clear()
-def clear_all_except_one_session_keys(excluded: tuple[bytes, bytes]) -> None:
+def clear_all_except_one_session_keys(excluded: tuple[AnyBytes, AnyBytes]) -> None:
cid, sid = excluded
for channel in _CHANNELS:
diff --git a/core/src/storage/common.py b/core/src/storage/common.py
index 649c656d..b3832201 100644
--- a/core/src/storage/common.py
+++ b/core/src/storage/common.py
@@ -1,7 +1,12 @@
from micropython import const
+from typing import TYPE_CHECKING
from trezor import config
+if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
+
# Namespaces:
# fmt: off
APP_DEVICE = const(0x01)
@@ -17,7 +22,7 @@ STORAGE_VERSION_01 = b"\x01"
STORAGE_VERSION_CURRENT = b"\x02"
-def set(app: int, key: int, data: bytes, public: bool = False) -> None:
+def set(app: int, key: int, data: AnyBytes, public: bool = False) -> None:
config.set(app, key, data, public)
diff --git a/core/src/storage/device.py b/core/src/storage/device.py
index 20caca94..4943c4f0 100644
--- a/core/src/storage/device.py
+++ b/core/src/storage/device.py
@@ -5,6 +5,8 @@ from storage import common
from trezor import utils
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+
from trezor.enums import BackupType, DisplayRotation
from typing_extensions import Literal
@@ -182,7 +184,7 @@ def set_passphrase_enabled(enable: bool) -> None:
set_passphrase_always_on_device(False)
-def set_homescreen(homescreen: bytes) -> None:
+def set_homescreen(homescreen: AnyBytes) -> None:
if len(homescreen) > utils.HOMESCREEN_MAXSIZE:
raise ValueError # homescreen too large
common.set(_NAMESPACE, _HOMESCREEN, homescreen, public=True)
@@ -455,7 +457,7 @@ def get_rgb_led() -> bool:
if utils.USE_THP:
- def set_thp_paired_cache(blob: bytes) -> None:
+ def set_thp_paired_cache(blob: AnyBytes) -> None:
"""
Set THP paired entries' cache (using protobuf serialization).
"""
diff --git a/core/src/storage/sd_salt.py b/core/src/storage/sd_salt.py
index 90714436..8f5b3499 100644
--- a/core/src/storage/sd_salt.py
+++ b/core/src/storage/sd_salt.py
@@ -6,6 +6,7 @@ from trezor import io, utils
from trezor.sdcard import with_filesystem
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import Callable, TypeVar
T = TypeVar("T", bound=Callable)
@@ -25,7 +26,7 @@ def is_enabled() -> bool:
return storage.device.get_sd_salt_auth_key() is not None
-def compute_auth_tag(salt: bytes, auth_key: bytes) -> bytes:
+def compute_auth_tag(salt: AnyBytes, auth_key: AnyBytes) -> bytes:
from trezor.crypto import hmac
digest = hmac(hmac.SHA256, auth_key, salt).digest()
diff --git a/core/src/trezor/_proto_messages.mako b/core/src/trezor/_proto_messages.mako
index 9a5f6315..adfa1789 100644
--- a/core/src/trezor/_proto_messages.mako
+++ b/core/src/trezor/_proto_messages.mako
@@ -15,6 +15,7 @@ def __getattr__(name: str) -> Any:
if TYPE_CHECKING:
+ from buffer_types import AnyBytes
from typing import TypeGuard
% for enum in sorted(enums, key=lambda e: e.name):
from trezor.enums import ${enum.name} # noqa: F401
@@ -26,14 +27,23 @@ required_fields = [f for f in message.fields if f.required]
repeated_fields = [f for f in message.fields if f.repeated]
optional_fields = [f for f in message.fields if f.optional]
+
+def python_type(field):
+ python_type = field.python_type
+ if python_type == "bytes":
+ python_type = "AnyBytes"
+ return python_type
+
+
def member_type(field):
+ typename = python_type(field)
if field.required:
- return field.python_type
+ return typename
if field.optional and field.default_value is not None:
- return field.python_type
+ return typename
if field.repeated:
- return f"list[{field.python_type}]"
- return f"{field.python_type} | None"
+ return f"list[{typename}]"
+ return f"{typename} | None"
%>\
class ${message.name}(protobuf.MessageType):
@@ -46,13 +56,13 @@ def member_type(field):
self,
*,
% for field in required_fields:
- ${field.name}: "${field.python_type}",
+ ${field.name}: "${python_type(field)}",
% endfor
% for field in repeated_fields:
- ${field.name}: "list[${field.python_type}] | None" = None,
+ ${field.name}: "list[${python_type(field)}] | None" = None,
% endfor
% for field in optional_fields:
- ${field.name}: "${field.python_type} | None" = None,
+ ${field.name}: "${python_type(field)} | None" = None,
% endfor
) -> None:
pass
diff --git a/core/src/trezor/crypto/base32.py b/core/src/trezor/crypto/base32.py
index f9b13e20..49360665 100644
--- a/core/src/trezor/crypto/base32.py
+++ b/core/src/trezor/crypto/base32.py
@@ -1,6 +1,10 @@
# Base32 implementation taken from the micropython-lib's base64 module
# https://github.com/micropython/micropython-lib/blob/master/base64/base64.py
#
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from buffer_types import AnyBytes
_b32alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
@@ -9,9 +13,10 @@ _b32tab = [ord(c) for c in _b32alphabet]
_b32rev = {ord(v): k for k, v in enumerate(_b32alphabet)}
-def encode(s: bytes) -> str:
+def encode(s: AnyBytes) -> str:
from ustruct import unpack
+ s = bytes(s)
quanta, leftover = divmod(len(s), 5)
# Pad the last quantum with zero bits if necessary
if leftover:
diff --git a/core/src/trezor/crypto/base58.py b/core/src/trezor/crypto/base58.py
index 9e294ed5..ef2e3d6c 100644
--- a/core/src/trezor/crypto/base58.py
+++ b/core/src/trezor/crypto/base58.py
@@ -13,16 +13,21 @@
# This module adds shiny packaging and support for python3.
#
-from typing import Callable
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from buffer_types import AnyBytes
+ from typing import Callable
# 58 character alphabet used
_alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
-def encode(data: bytes, alphabet: str = _alphabet) -> str:
+def encode(data: AnyBytes, alphabet: str = _alphabet) -> str:
"""
Convert bytes to base58 encoded string.
"""
+ data = bytes(data)
origlen = len(data)
data = data.lstrip(b"\0")
newlen = len(data)
@@ -61,41 +66,44 @@ def decode(string: str, alphabet: str = _alphabet) -> bytes:
return bytes((b for b in reversed(result + [0] * (origlen - newlen))))
-def sha256d_32(data: bytes) -> bytes:
+def sha256d_32(data: AnyBytes) -> bytes:
from .hashlib import sha256
return sha256(sha256(data).digest()).digest()[:4]
-def groestl512d_32(data: bytes) -> bytes:
+def groestl512d_32(data: AnyBytes) -> bytes:
from .hashlib import groestl512
return groestl512(groestl512(data).digest()).digest()[:4]
-def blake256d_32(data: bytes) -> bytes:
+def blake256d_32(data: AnyBytes) -> bytes:
from .hashlib import blake256
return blake256(blake256(data).digest()).digest()[:4]
-def keccak_32(data: bytes) -> bytes:
+def keccak_32(data: AnyBytes) -> bytes:
from .hashlib import sha3_256
return sha3_256(data, keccak=True).digest()[:4]
-def ripemd160_32(data: bytes) -> bytes:
+def ripemd160_32(data: AnyBytes) -> bytes:
from .hashlib import ripemd160
return ripemd160(data).digest()[:4]
-def encode_check(data: bytes, digestfunc: Callable[[bytes], bytes] = Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.