matejcik/build-mocks-draft
matejcik 11 months ago
parent 34a563018d
commit 3c965bbd6b

@ -317,6 +317,21 @@ impl TryFrom<Never> for Obj {
} }
} }
//# package: trezorui2
//#
//# from trezor import utils
//# class LayoutObj:
//# """Representation of a Rust-based layout object.
//# see `trezor::ui::layout::obj::LayoutObj`.
//# """
//# def attach_timer_fn(self, fn: Callable[[int, int], None]) -> None:
//# """Attach a timer setter function.
//#
//# The layout object can call the timer setter with two arguments,
//# `token` and `deadline`. When `deadline` is reached, the layout object
//# expects a callback to `self.timer(token)`.
//# """
extern "C" fn ui_layout_attach_timer_fn(this: Obj, timer_fn: Obj) -> Obj { extern "C" fn ui_layout_attach_timer_fn(this: Obj, timer_fn: Obj) -> Obj {
let block = || { let block = || {
let this: Gc<LayoutObj> = this.try_into()?; let this: Gc<LayoutObj> = this.try_into()?;
@ -328,6 +343,10 @@ extern "C" fn ui_layout_attach_timer_fn(this: Obj, timer_fn: Obj) -> Obj {
unsafe { util::try_or_raise(block) } unsafe { util::try_or_raise(block) }
} }
//# if utils.USE_TOUCH:
//# def touch_event(self, event: int, x: int, y: int) -> None:
//# """Receive a touch event `event` at coordinates `x`, `y`."""
#[cfg(feature = "touch")] #[cfg(feature = "touch")]
extern "C" fn ui_layout_touch_event(n_args: usize, args: *const Obj) -> Obj { extern "C" fn ui_layout_touch_event(n_args: usize, args: *const Obj) -> Obj {
let block = |args: &[Obj], _kwargs: &Map| { let block = |args: &[Obj], _kwargs: &Map| {
@ -351,6 +370,9 @@ extern "C" fn ui_layout_touch_event(_n_args: usize, _args: *const Obj) -> Obj {
Obj::const_none() Obj::const_none()
} }
//# if utils.USE_BUTTON:
//# def button_event(self, event: int, button: int) -> None:
//# """Receive a button event `event` for button `button`."""
#[cfg(feature = "button")] #[cfg(feature = "button")]
extern "C" fn ui_layout_button_event(n_args: usize, args: *const Obj) -> Obj { extern "C" fn ui_layout_button_event(n_args: usize, args: *const Obj) -> Obj {
let block = |args: &[Obj], _kwargs: &Map| { let block = |args: &[Obj], _kwargs: &Map| {
@ -370,6 +392,8 @@ extern "C" fn ui_layout_button_event(_n_args: usize, _args: *const Obj) -> Obj {
Obj::const_none() Obj::const_none()
} }
//# def progress_event(self, value: int, description: str) -> None:
//# """Receive a progress event."""
extern "C" fn ui_layout_progress_event(n_args: usize, args: *const Obj) -> Obj { extern "C" fn ui_layout_progress_event(n_args: usize, args: *const Obj) -> Obj {
let block = |args: &[Obj], _kwargs: &Map| { let block = |args: &[Obj], _kwargs: &Map| {
if args.len() != 3 { if args.len() != 3 {
@ -384,6 +408,8 @@ extern "C" fn ui_layout_progress_event(n_args: usize, args: *const Obj) -> Obj {
unsafe { util::try_with_args_and_kwargs(n_args, args, &Map::EMPTY, block) } unsafe { util::try_with_args_and_kwargs(n_args, args, &Map::EMPTY, block) }
} }
//# def usb_event(self, connected: bool) -> None:
//# """Receive a USB connect/disconnect event."""
extern "C" fn ui_layout_usb_event(n_args: usize, args: *const Obj) -> Obj { extern "C" fn ui_layout_usb_event(n_args: usize, args: *const Obj) -> Obj {
let block = |args: &[Obj], _kwargs: &Map| { let block = |args: &[Obj], _kwargs: &Map| {
if args.len() != 2 { if args.len() != 2 {
@ -397,6 +423,12 @@ extern "C" fn ui_layout_usb_event(n_args: usize, args: *const Obj) -> Obj {
unsafe { util::try_with_args_and_kwargs(n_args, args, &Map::EMPTY, block) } unsafe { util::try_with_args_and_kwargs(n_args, args, &Map::EMPTY, block) }
} }
//# def timer(self, token: int) -> None:
//# """Callback for the timer set by `attach_timer_fn`.
//#
//# This function should be called by the executor after the corresponding
//# deadline is reached.
//# """
extern "C" fn ui_layout_timer(this: Obj, token: Obj) -> Obj { extern "C" fn ui_layout_timer(this: Obj, token: Obj) -> Obj {
let block = || { let block = || {
let this: Gc<LayoutObj> = this.try_into()?; let this: Gc<LayoutObj> = this.try_into()?;
@ -407,6 +439,11 @@ extern "C" fn ui_layout_timer(this: Obj, token: Obj) -> Obj {
unsafe { util::try_or_raise(block) } unsafe { util::try_or_raise(block) }
} }
//# def paint(self) -> None:
//# """Paint the layout object on screen.
//#
//# Will only paint updated parts of the layout as required.
//# """
extern "C" fn ui_layout_paint(this: Obj) -> Obj { extern "C" fn ui_layout_paint(this: Obj) -> Obj {
let block = || { let block = || {
let this: Gc<LayoutObj> = this.try_into()?; let this: Gc<LayoutObj> = this.try_into()?;
@ -416,6 +453,11 @@ extern "C" fn ui_layout_paint(this: Obj) -> Obj {
unsafe { util::try_or_raise(block) } unsafe { util::try_or_raise(block) }
} }
//# def request_complete_repaint(self) -> None:
//# """Request a complete repaint of the screen.
//#
//# Does not repaint the screen, a subsequent call to `paint()` is required.
//# """
extern "C" fn ui_layout_request_complete_repaint(this: Obj) -> Obj { extern "C" fn ui_layout_request_complete_repaint(this: Obj) -> Obj {
let block = || { let block = || {
let this: Gc<LayoutObj> = this.try_into()?; let this: Gc<LayoutObj> = this.try_into()?;
@ -432,6 +474,8 @@ extern "C" fn ui_layout_request_complete_repaint(this: Obj) -> Obj {
unsafe { util::try_or_raise(block) } unsafe { util::try_or_raise(block) }
} }
//# def page_count(self) -> int:
//# """Return the number of pages in the layout object."""
extern "C" fn ui_layout_page_count(this: Obj) -> Obj { extern "C" fn ui_layout_page_count(this: Obj) -> Obj {
let block = || { let block = || {
let this: Gc<LayoutObj> = this.try_into()?; let this: Gc<LayoutObj> = this.try_into()?;
@ -446,6 +490,14 @@ pub extern "C" fn ui_debug_layout_type() -> &'static Type {
LayoutObj::obj_type() LayoutObj::obj_type()
} }
//# if __debug__:
//# def trace(self, tracer: Callable[[str], None]) -> None:
//# """Generate a JSON trace of the layout object.
//#
//# The JSON can be emitted as a sequence of calls to `tracer`, each of
//# which is not necessarily a valid JSON chunk. The caller must
//# reassemble the chunks to get a sensible result.
//# """
#[cfg(feature = "ui_debug")] #[cfg(feature = "ui_debug")]
extern "C" fn ui_layout_trace(this: Obj, callback: Obj) -> Obj { extern "C" fn ui_layout_trace(this: Obj, callback: Obj) -> Obj {
let block = || { let block = || {
@ -461,6 +513,9 @@ extern "C" fn ui_layout_trace(_this: Obj, _callback: Obj) -> Obj {
Obj::const_none() Obj::const_none()
} }
//# if __debug__:
//# def bounds(self) -> None:
//# """Paint bounds of individual components on screen."""
#[cfg(feature = "ui_bounds")] #[cfg(feature = "ui_bounds")]
extern "C" fn ui_layout_bounds(this: Obj) -> Obj { extern "C" fn ui_layout_bounds(this: Obj) -> Obj {
let block = || { let block = || {

@ -1594,415 +1594,416 @@ extern "C" fn draw_welcome_screen() -> Obj {
#[no_mangle] #[no_mangle]
pub static mp_module_trezorui2: Module = obj_module! { pub static mp_module_trezorui2: Module = obj_module! {
//# package: trezorui2
Qstr::MP_QSTR___name__ => Qstr::MP_QSTR_trezorui2.to_obj(), Qstr::MP_QSTR___name__ => Qstr::MP_QSTR_trezorui2.to_obj(),
/// CONFIRMED: object //# CONFIRMED: object
Qstr::MP_QSTR_CONFIRMED => CONFIRMED.as_obj(), Qstr::MP_QSTR_CONFIRMED => CONFIRMED.as_obj(),
/// CANCELLED: object //# CANCELLED: object
Qstr::MP_QSTR_CANCELLED => CANCELLED.as_obj(), Qstr::MP_QSTR_CANCELLED => CANCELLED.as_obj(),
/// INFO: object //# INFO: object
Qstr::MP_QSTR_INFO => INFO.as_obj(), Qstr::MP_QSTR_INFO => INFO.as_obj(),
/// def disable_animation(disable: bool) -> None: //# def disable_animation(disable: bool) -> None:
/// """Disable animations, debug builds only.""" //# """Disable animations, debug builds only."""
Qstr::MP_QSTR_disable_animation => obj_fn_1!(upy_disable_animation).as_obj(), Qstr::MP_QSTR_disable_animation => obj_fn_1!(upy_disable_animation).as_obj(),
/// def jpeg_info(data: bytes) -> tuple[int, int, int]: //# def jpeg_info(data: bytes) -> tuple[int, int, int]:
/// """Get JPEG image dimensions (width: int, height: int, mcu_height: int).""" //# """Get JPEG image dimensions (width: int, height: int, mcu_height: int)."""
Qstr::MP_QSTR_jpeg_info => obj_fn_1!(upy_jpeg_info).as_obj(), Qstr::MP_QSTR_jpeg_info => obj_fn_1!(upy_jpeg_info).as_obj(),
/// def jpeg_test(data: bytes) -> bool: //# def jpeg_test(data: bytes) -> bool:
/// """Test JPEG image.""" //# """Test JPEG image."""
Qstr::MP_QSTR_jpeg_test => obj_fn_1!(upy_jpeg_test).as_obj(), Qstr::MP_QSTR_jpeg_test => obj_fn_1!(upy_jpeg_test).as_obj(),
/// def confirm_action( //# def confirm_action(
/// *, //# *,
/// title: str, //# title: str,
/// action: str | None, //# action: str | None,
/// description: str | None, //# description: str | None,
/// verb: str | None = None, //# verb: str | None = None,
/// verb_cancel: str | None = None, //# verb_cancel: str | None = None,
/// hold: bool = False, //# hold: bool = False,
/// hold_danger: bool = False, //# hold_danger: bool = False,
/// reverse: bool = False, //# reverse: bool = False,
/// ) -> object: //# ) -> LayoutObj:
/// """Confirm action.""" //# """Confirm action."""
Qstr::MP_QSTR_confirm_action => obj_fn_kw!(0, new_confirm_action).as_obj(), Qstr::MP_QSTR_confirm_action => obj_fn_kw!(0, new_confirm_action).as_obj(),
/// def confirm_emphasized( //# def confirm_emphasized(
/// *, //# *,
/// title: str, //# title: str,
/// items: Iterable[str | tuple[bool, str]], //# items: Iterable[str | tuple[bool, str]],
/// verb: str | None = None, //# verb: str | None = None,
/// ) -> object: //# ) -> LayoutObj:
/// """Confirm formatted text that has been pre-split in python. For tuples //# """Confirm formatted text that has been pre-split in python. For tuples
/// the first component is a bool indicating whether this part is emphasized.""" //# the first component is a bool indicating whether this part is emphasized."""
Qstr::MP_QSTR_confirm_emphasized => obj_fn_kw!(0, new_confirm_emphasized).as_obj(), Qstr::MP_QSTR_confirm_emphasized => obj_fn_kw!(0, new_confirm_emphasized).as_obj(),
/// def confirm_homescreen( //# def confirm_homescreen(
/// *, //# *,
/// title: str, //# title: str,
/// image: bytes, //# image: bytes,
/// ) -> object: //# ) -> LayoutObj:
/// """Confirm homescreen.""" //# """Confirm homescreen."""
Qstr::MP_QSTR_confirm_homescreen => obj_fn_kw!(0, new_confirm_homescreen).as_obj(), Qstr::MP_QSTR_confirm_homescreen => obj_fn_kw!(0, new_confirm_homescreen).as_obj(),
/// def confirm_blob( //# def confirm_blob(
/// *, //# *,
/// title: str, //# title: str,
/// data: str | bytes, //# data: str | bytes,
/// description: str | None, //# description: str | None,
/// extra: str | None, //# extra: str | None,
/// verb: str | None = None, //# verb: str | None = None,
/// verb_cancel: str | None = None, //# verb_cancel: str | None = None,
/// hold: bool = False, //# hold: bool = False,
/// ) -> object: //# ) -> LayoutObj:
/// """Confirm byte sequence data.""" //# """Confirm byte sequence data."""
Qstr::MP_QSTR_confirm_blob => obj_fn_kw!(0, new_confirm_blob).as_obj(), Qstr::MP_QSTR_confirm_blob => obj_fn_kw!(0, new_confirm_blob).as_obj(),
/// def confirm_address( //# def confirm_address(
/// *, //# *,
/// title: str, //# title: str,
/// data: str | bytes, //# data: str | bytes,
/// description: str | None, //# description: str | None,
/// extra: str | None, //# extra: str | None,
/// ) -> object: //# ) -> LayoutObj:
/// """Confirm address. Similar to `confirm_blob` but has corner info button //# """Confirm address. Similar to `confirm_blob` but has corner info button
/// and allows left swipe which does the same thing as the button.""" //# and allows left swipe which does the same thing as the button."""
Qstr::MP_QSTR_confirm_address => obj_fn_kw!(0, new_confirm_address).as_obj(), Qstr::MP_QSTR_confirm_address => obj_fn_kw!(0, new_confirm_address).as_obj(),
/// def confirm_properties( //# def confirm_properties(
/// *, //# *,
/// title: str, //# title: str,
/// items: list[tuple[str | None, str | bytes | None, bool]], //# items: list[tuple[str | None, str | bytes | None, bool]],
/// hold: bool = False, //# hold: bool = False,
/// ) -> object: //# ) -> LayoutObj:
/// """Confirm list of key-value pairs. The third component in the tuple should be True if //# """Confirm list of key-value pairs. The third component in the tuple should be True if
/// the value is to be rendered as binary with monospace font, False otherwise.""" //# the value is to be rendered as binary with monospace font, False otherwise."""
Qstr::MP_QSTR_confirm_properties => obj_fn_kw!(0, new_confirm_properties).as_obj(), Qstr::MP_QSTR_confirm_properties => obj_fn_kw!(0, new_confirm_properties).as_obj(),
/// def confirm_reset_device( //# def confirm_reset_device(
/// *, //# *,
/// title: str, //# title: str,
/// button: str, //# button: str,
/// ) -> object: //# ) -> LayoutObj:
/// """Confirm TOS before device setup.""" //# """Confirm TOS before device setup."""
Qstr::MP_QSTR_confirm_reset_device => obj_fn_kw!(0, new_confirm_reset_device).as_obj(), Qstr::MP_QSTR_confirm_reset_device => obj_fn_kw!(0, new_confirm_reset_device).as_obj(),
/// def show_address_details( //# def show_address_details(
/// *, //# *,
/// address: str, //# address: str,
/// case_sensitive: bool, //# case_sensitive: bool,
/// account: str | None, //# account: str | None,
/// path: str | None, //# path: str | None,
/// xpubs: list[tuple[str, str]], //# xpubs: list[tuple[str, str]],
/// ) -> object: //# ) -> LayoutObj:
/// """Show address details - QR code, account, path, cosigner xpubs.""" //# """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(), Qstr::MP_QSTR_show_address_details => obj_fn_kw!(0, new_show_address_details).as_obj(),
/// def show_spending_details( //# def show_spending_details(
/// *, //# *,
/// title: str = "INFORMATION", //# title: str = "INFORMATION",
/// account: str | None, //# account: str | None,
/// fee_rate: str | None, //# fee_rate: str | None,
/// fee_rate_title: str = "Fee rate:", //# fee_rate_title: str = "Fee rate:",
/// ) -> object: //# ) -> LayoutObj:
/// """Show metadata when for outgoing transaction.""" //# """Show metadata when for outgoing transaction."""
Qstr::MP_QSTR_show_spending_details => obj_fn_kw!(0, new_show_spending_details).as_obj(), Qstr::MP_QSTR_show_spending_details => obj_fn_kw!(0, new_show_spending_details).as_obj(),
/// def confirm_value( //# def confirm_value(
/// *, //# *,
/// title: str, //# title: str,
/// value: str, //# value: str,
/// description: str | None, //# description: str | None,
/// subtitle: str | None, //# subtitle: str | None,
/// verb: str | None = None, //# verb: str | None = None,
/// verb_cancel: str | None = None, //# verb_cancel: str | None = None,
/// info_button: bool = False, //# info_button: bool = False,
/// hold: bool = False, //# hold: bool = False,
/// ) -> object: //# ) -> LayoutObj:
/// """Confirm value. Merge of confirm_total and confirm_output.""" //# """Confirm value. Merge of confirm_total and confirm_output."""
Qstr::MP_QSTR_confirm_value => obj_fn_kw!(0, new_confirm_value).as_obj(), Qstr::MP_QSTR_confirm_value => obj_fn_kw!(0, new_confirm_value).as_obj(),
/// def confirm_total( //# def confirm_total(
/// *, //# *,
/// title: str, //# title: str,
/// items: list[tuple[str, str]], //# items: list[tuple[str, str]],
/// info_button: bool = False, //# info_button: bool = False,
/// ) -> object: //# ) -> LayoutObj:
/// """Transaction summary. Always hold to confirm.""" //# """Transaction summary. Always hold to confirm."""
Qstr::MP_QSTR_confirm_total => obj_fn_kw!(0, new_confirm_total).as_obj(), Qstr::MP_QSTR_confirm_total => obj_fn_kw!(0, new_confirm_total).as_obj(),
/// def confirm_modify_output( //# def confirm_modify_output(
/// *, //# *,
/// address: str, # ignored //# address: str, # ignored
/// sign: int, //# sign: int,
/// amount_change: str, //# amount_change: str,
/// amount_new: str, //# amount_new: str,
/// ) -> object: //# ) -> LayoutObj:
/// """Decrease or increase amount for given address.""" //# """Decrease or increase amount for given address."""
Qstr::MP_QSTR_confirm_modify_output => obj_fn_kw!(0, new_confirm_modify_output).as_obj(), Qstr::MP_QSTR_confirm_modify_output => obj_fn_kw!(0, new_confirm_modify_output).as_obj(),
/// def confirm_modify_fee( //# def confirm_modify_fee(
/// *, //# *,
/// title: str, //# title: str,
/// sign: int, //# sign: int,
/// user_fee_change: str, //# user_fee_change: str,
/// total_fee_new: str, //# total_fee_new: str,
/// fee_rate_amount: str | None, # ignored //# fee_rate_amount: str | None, # ignored
/// ) -> object: //# ) -> LayoutObj:
/// """Decrease or increase transaction fee.""" //# """Decrease or increase transaction fee."""
Qstr::MP_QSTR_confirm_modify_fee => obj_fn_kw!(0, new_confirm_modify_fee).as_obj(), Qstr::MP_QSTR_confirm_modify_fee => obj_fn_kw!(0, new_confirm_modify_fee).as_obj(),
/// def confirm_fido( //# def confirm_fido(
/// *, //# *,
/// title: str, //# title: str,
/// app_name: str, //# app_name: str,
/// icon_name: str | None, //# icon_name: str | None,
/// accounts: list[str | None], //# accounts: list[str | None],
/// ) -> int | object: //# ) -> int | object:
/// """FIDO confirmation. //# """FIDO confirmation.
/// //#
/// Returns page index in case of confirmation and CANCELLED otherwise. //# Returns page index in case of confirmation and CANCELLED otherwise.
/// """ //# """
Qstr::MP_QSTR_confirm_fido => obj_fn_kw!(0, new_confirm_fido).as_obj(), Qstr::MP_QSTR_confirm_fido => obj_fn_kw!(0, new_confirm_fido).as_obj(),
/// def show_error( //# def show_error(
/// *, //# *,
/// title: str, //# title: str,
/// button: str = "CONTINUE", //# button: str = "CONTINUE",
/// description: str = "", //# description: str = "",
/// allow_cancel: bool = False, //# allow_cancel: bool = False,
/// time_ms: int = 0, //# time_ms: int = 0,
/// ) -> object: //# ) -> LayoutObj:
/// """Error modal. No buttons shown when `button` is empty string.""" //# """Error modal. No buttons shown when `button` is empty string."""
Qstr::MP_QSTR_show_error => obj_fn_kw!(0, new_show_error).as_obj(), Qstr::MP_QSTR_show_error => obj_fn_kw!(0, new_show_error).as_obj(),
/// def show_warning( //# def show_warning(
/// *, //# *,
/// title: str, //# title: str,
/// button: str = "CONTINUE", //# button: str = "CONTINUE",
/// description: str = "", //# description: str = "",
/// allow_cancel: bool = False, //# allow_cancel: bool = False,
/// time_ms: int = 0, //# time_ms: int = 0,
/// ) -> object: //# ) -> LayoutObj:
/// """Warning modal. No buttons shown when `button` is empty string.""" //# """Warning modal. No buttons shown when `button` is empty string."""
Qstr::MP_QSTR_show_warning => obj_fn_kw!(0, new_show_warning).as_obj(), Qstr::MP_QSTR_show_warning => obj_fn_kw!(0, new_show_warning).as_obj(),
/// def show_success( //# def show_success(
/// *, //# *,
/// title: str, //# title: str,
/// button: str = "CONTINUE", //# button: str = "CONTINUE",
/// description: str = "", //# description: str = "",
/// allow_cancel: bool = False, //# allow_cancel: bool = False,
/// time_ms: int = 0, //# time_ms: int = 0,
/// ) -> object: //# ) -> LayoutObj:
/// """Success modal. No buttons shown when `button` is empty string.""" //# """Success modal. No buttons shown when `button` is empty string."""
Qstr::MP_QSTR_show_success => obj_fn_kw!(0, new_show_success).as_obj(), Qstr::MP_QSTR_show_success => obj_fn_kw!(0, new_show_success).as_obj(),
/// def show_info( //# def show_info(
/// *, //# *,
/// title: str, //# title: str,
/// button: str = "CONTINUE", //# button: str = "CONTINUE",
/// description: str = "", //# description: str = "",
/// allow_cancel: bool = False, //# allow_cancel: bool = False,
/// time_ms: int = 0, //# time_ms: int = 0,
/// ) -> object: //# ) -> LayoutObj:
/// """Info modal. No buttons shown when `button` is empty string.""" //# """Info modal. No buttons shown when `button` is empty string."""
Qstr::MP_QSTR_show_info => obj_fn_kw!(0, new_show_info).as_obj(), Qstr::MP_QSTR_show_info => obj_fn_kw!(0, new_show_info).as_obj(),
/// def show_mismatch() -> object: //# def show_mismatch() -> LayoutObj:
/// """Warning modal, receiving address mismatch.""" //# """Warning modal, receiving address mismatch."""
Qstr::MP_QSTR_show_mismatch => obj_fn_0!(new_show_mismatch).as_obj(), Qstr::MP_QSTR_show_mismatch => obj_fn_0!(new_show_mismatch).as_obj(),
/// def show_simple( //# def show_simple(
/// *, //# *,
/// title: str | None, //# title: str | None,
/// description: str = "", //# description: str = "",
/// button: str = "", //# button: str = "",
/// ) -> object: //# ) -> LayoutObj:
/// """Simple dialog with text and one button.""" //# """Simple dialog with text and one button."""
Qstr::MP_QSTR_show_simple => obj_fn_kw!(0, new_show_simple).as_obj(), Qstr::MP_QSTR_show_simple => obj_fn_kw!(0, new_show_simple).as_obj(),
/// def confirm_with_info( //# def confirm_with_info(
/// *, //# *,
/// title: str, //# title: str,
/// button: str, //# button: str,
/// info_button: str, //# info_button: str,
/// items: Iterable[tuple[int, str]], //# items: Iterable[tuple[int, str]],
/// ) -> object: //# ) -> LayoutObj:
/// """Confirm given items but with third button. Always single page //# """Confirm given items but with third button. Always single page
/// without scrolling.""" //# without scrolling."""
Qstr::MP_QSTR_confirm_with_info => obj_fn_kw!(0, new_confirm_with_info).as_obj(), Qstr::MP_QSTR_confirm_with_info => obj_fn_kw!(0, new_confirm_with_info).as_obj(),
/// def confirm_more( //# def confirm_more(
/// *, //# *,
/// title: str, //# title: str,
/// button: str, //# button: str,
/// items: Iterable[tuple[int, str]], //# items: Iterable[tuple[int, str]],
/// ) -> object: //# ) -> LayoutObj:
/// """Confirm long content with the possibility to go back from any page. //# """Confirm long content with the possibility to go back from any page.
/// Meant to be used with confirm_with_info.""" //# Meant to be used with confirm_with_info."""
Qstr::MP_QSTR_confirm_more => obj_fn_kw!(0, new_confirm_more).as_obj(), Qstr::MP_QSTR_confirm_more => obj_fn_kw!(0, new_confirm_more).as_obj(),
/// def confirm_coinjoin( //# def confirm_coinjoin(
/// *, //# *,
/// max_rounds: str, //# max_rounds: str,
/// max_feerate: str, //# max_feerate: str,
/// ) -> object: //# ) -> LayoutObj:
/// """Confirm coinjoin authorization.""" //# """Confirm coinjoin authorization."""
Qstr::MP_QSTR_confirm_coinjoin => obj_fn_kw!(0, new_confirm_coinjoin).as_obj(), Qstr::MP_QSTR_confirm_coinjoin => obj_fn_kw!(0, new_confirm_coinjoin).as_obj(),
/// def request_pin( //# def request_pin(
/// *, //# *,
/// prompt: str, //# prompt: str,
/// subprompt: str, //# subprompt: str,
/// allow_cancel: bool = True, //# allow_cancel: bool = True,
/// wrong_pin: bool = False, //# wrong_pin: bool = False,
/// ) -> str | object: //# ) -> str | object:
/// """Request pin on device.""" //# """Request pin on device."""
Qstr::MP_QSTR_request_pin => obj_fn_kw!(0, new_request_pin).as_obj(), Qstr::MP_QSTR_request_pin => obj_fn_kw!(0, new_request_pin).as_obj(),
/// def request_passphrase( //# def request_passphrase(
/// *, //# *,
/// prompt: str, //# prompt: str,
/// max_len: int, //# max_len: int,
/// ) -> str | object: //# ) -> str | object:
/// """Passphrase input keyboard.""" //# """Passphrase input keyboard."""
Qstr::MP_QSTR_request_passphrase => obj_fn_kw!(0, new_request_passphrase).as_obj(), Qstr::MP_QSTR_request_passphrase => obj_fn_kw!(0, new_request_passphrase).as_obj(),
/// def request_bip39( //# def request_bip39(
/// *, //# *,
/// prompt: str, //# prompt: str,
/// ) -> str: //# ) -> str:
/// """BIP39 word input keyboard.""" //# """BIP39 word input keyboard."""
Qstr::MP_QSTR_request_bip39 => obj_fn_kw!(0, new_request_bip39).as_obj(), Qstr::MP_QSTR_request_bip39 => obj_fn_kw!(0, new_request_bip39).as_obj(),
/// def request_slip39( //# def request_slip39(
/// *, //# *,
/// prompt: str, //# prompt: str,
/// ) -> str: //# ) -> str:
/// """SLIP39 word input keyboard.""" //# """SLIP39 word input keyboard."""
Qstr::MP_QSTR_request_slip39 => obj_fn_kw!(0, new_request_slip39).as_obj(), Qstr::MP_QSTR_request_slip39 => obj_fn_kw!(0, new_request_slip39).as_obj(),
/// def select_word( //# def select_word(
/// *, //# *,
/// title: str, //# title: str,
/// description: str, //# description: str,
/// words: Iterable[str], //# words: Iterable[str],
/// ) -> int: //# ) -> int:
/// """Select mnemonic word from three possibilities - seed check after backup. The //# """Select mnemonic word from three possibilities - seed check after backup. The
/// iterable must be of exact size. Returns index in range `0..3`.""" //# iterable must be of exact size. Returns index in range `0..3`."""
Qstr::MP_QSTR_select_word => obj_fn_kw!(0, new_select_word).as_obj(), Qstr::MP_QSTR_select_word => obj_fn_kw!(0, new_select_word).as_obj(),
/// def show_share_words( //# def show_share_words(
/// *, //# *,
/// title: str, //# title: str,
/// pages: Iterable[str], //# pages: Iterable[str],
/// ) -> object: //# ) -> LayoutObj:
/// """Show mnemonic for backup. Expects the words pre-divided into individual pages.""" //# """Show mnemonic for backup. Expects the words pre-divided into individual pages."""
Qstr::MP_QSTR_show_share_words => obj_fn_kw!(0, new_show_share_words).as_obj(), Qstr::MP_QSTR_show_share_words => obj_fn_kw!(0, new_show_share_words).as_obj(),
/// def request_number( //# def request_number(
/// *, //# *,
/// title: str, //# title: str,
/// count: int, //# count: int,
/// min_count: int, //# min_count: int,
/// max_count: int, //# max_count: int,
/// description: Callable[[int], str] | None = None, //# description: Callable[[int], str] | None = None,
/// ) -> object: //# ) -> LayoutObj:
/// """Number input with + and - buttons, description, and info button.""" //# """Number input with + and - buttons, description, and info button."""
Qstr::MP_QSTR_request_number => obj_fn_kw!(0, new_request_number).as_obj(), Qstr::MP_QSTR_request_number => obj_fn_kw!(0, new_request_number).as_obj(),
/// def show_checklist( //# def show_checklist(
/// *, //# *,
/// title: str, //# title: str,
/// items: Iterable[str], //# items: Iterable[str],
/// active: int, //# active: int,
/// button: str, //# button: str,
/// ) -> object: //# ) -> LayoutObj:
/// """Checklist of backup steps. Active index is highlighted, previous items have check //# """Checklist of backup steps. Active index is highlighted, previous items have check
/// mark next to them.""" //# mark next to them."""
Qstr::MP_QSTR_show_checklist => obj_fn_kw!(0, new_show_checklist).as_obj(), Qstr::MP_QSTR_show_checklist => obj_fn_kw!(0, new_show_checklist).as_obj(),
/// def confirm_recovery( //# def confirm_recovery(
/// *, //# *,
/// title: str, //# title: str,
/// description: str, //# description: str,
/// button: str, //# button: str,
/// dry_run: bool, //# dry_run: bool,
/// info_button: bool = False, //# info_button: bool = False,
/// ) -> object: //# ) -> LayoutObj:
/// """Device recovery homescreen.""" //# """Device recovery homescreen."""
Qstr::MP_QSTR_confirm_recovery => obj_fn_kw!(0, new_confirm_recovery).as_obj(), Qstr::MP_QSTR_confirm_recovery => obj_fn_kw!(0, new_confirm_recovery).as_obj(),
/// def select_word_count( //# def select_word_count(
/// *, //# *,
/// dry_run: bool, //# dry_run: bool,
/// ) -> int | str: # TT returns int //# ) -> int | str: # TT returns int
/// """Select mnemonic word count from (12, 18, 20, 24, 33).""" //# """Select mnemonic word count from (12, 18, 20, 24, 33)."""
Qstr::MP_QSTR_select_word_count => obj_fn_kw!(0, new_select_word_count).as_obj(), Qstr::MP_QSTR_select_word_count => obj_fn_kw!(0, new_select_word_count).as_obj(),
/// def show_group_share_success( //# def show_group_share_success(
/// *, //# *,
/// lines: Iterable[str] //# lines: Iterable[str]
/// ) -> int: //# ) -> int:
/// """Shown after successfully finishing a group.""" //# """Shown after successfully finishing a group."""
Qstr::MP_QSTR_show_group_share_success => obj_fn_kw!(0, new_show_group_share_success).as_obj(), Qstr::MP_QSTR_show_group_share_success => obj_fn_kw!(0, new_show_group_share_success).as_obj(),
/// def show_remaining_shares( //# def show_remaining_shares(
/// *, //# *,
/// pages: Iterable[tuple[str, str]], //# pages: Iterable[tuple[str, str]],
/// ) -> int: //# ) -> int:
/// """Shows SLIP39 state after info button is pressed on `confirm_recovery`.""" //# """Shows SLIP39 state after info button is pressed on `confirm_recovery`."""
Qstr::MP_QSTR_show_remaining_shares => obj_fn_kw!(0, new_show_remaining_shares).as_obj(), Qstr::MP_QSTR_show_remaining_shares => obj_fn_kw!(0, new_show_remaining_shares).as_obj(),
/// def show_progress( //# def show_progress(
/// *, //# *,
/// title: str, //# title: str,
/// indeterminate: bool = False, //# indeterminate: bool = False,
/// description: str = "", //# description: str = "",
/// ) -> object: //# ) -> LayoutObj:
/// """Show progress loader. Please note that the number of lines reserved on screen for //# """Show progress loader. Please note that the number of lines reserved on screen for
/// description is determined at construction time. If you want multiline descriptions //# description is determined at construction time. If you want multiline descriptions
/// make sure the initial description has at least that amount of lines.""" //# make sure the initial description has at least that amount of lines."""
Qstr::MP_QSTR_show_progress => obj_fn_kw!(0, new_show_progress).as_obj(), Qstr::MP_QSTR_show_progress => obj_fn_kw!(0, new_show_progress).as_obj(),
/// def show_progress_coinjoin( //# def show_progress_coinjoin(
/// *, //# *,
/// title: str, //# title: str,
/// indeterminate: bool = False, //# indeterminate: bool = False,
/// time_ms: int = 0, //# time_ms: int = 0,
/// skip_first_paint: bool = False, //# skip_first_paint: bool = False,
/// ) -> object: //# ) -> LayoutObj:
/// """Show progress loader for coinjoin. Returns CANCELLED after a specified time when //# """Show progress loader for coinjoin. Returns CANCELLED after a specified time when
/// time_ms timeout is passed.""" //# time_ms timeout is passed."""
Qstr::MP_QSTR_show_progress_coinjoin => obj_fn_kw!(0, new_show_progress_coinjoin).as_obj(), Qstr::MP_QSTR_show_progress_coinjoin => obj_fn_kw!(0, new_show_progress_coinjoin).as_obj(),
/// def show_homescreen( //# def show_homescreen(
/// *, //# *,
/// label: str | None, //# label: str | None,
/// hold: bool, //# hold: bool,
/// notification: str | None, //# notification: str | None,
/// notification_level: int = 0, //# notification_level: int = 0,
/// skip_first_paint: bool, //# skip_first_paint: bool,
/// ) -> CANCELLED: //# ) -> CANCELLED:
/// """Idle homescreen.""" //# """Idle homescreen."""
Qstr::MP_QSTR_show_homescreen => obj_fn_kw!(0, new_show_homescreen).as_obj(), Qstr::MP_QSTR_show_homescreen => obj_fn_kw!(0, new_show_homescreen).as_obj(),
/// def show_lockscreen( //# def show_lockscreen(
/// *, //# *,
/// label: str | None, //# label: str | None,
/// bootscreen: bool, //# bootscreen: bool,
/// skip_first_paint: bool, //# skip_first_paint: bool,
/// ) -> CANCELLED: //# ) -> CANCELLED:
/// """Homescreen for locked device.""" //# """Homescreen for locked device."""
Qstr::MP_QSTR_show_lockscreen => obj_fn_kw!(0, new_show_lockscreen).as_obj(), Qstr::MP_QSTR_show_lockscreen => obj_fn_kw!(0, new_show_lockscreen).as_obj(),
/// def draw_welcome_screen() -> None: //# def draw_welcome_screen() -> None:
/// """Show logo icon with the model name at the bottom and return.""" //# """Show logo icon with the model name at the bottom and return."""
Qstr::MP_QSTR_draw_welcome_screen => obj_fn_0!(draw_welcome_screen).as_obj(), Qstr::MP_QSTR_draw_welcome_screen => obj_fn_0!(draw_welcome_screen).as_obj(),
}; };

@ -1,7 +1,4 @@
from typing import * from typing import *
# extmod/modtrezorconfig/modtrezorconfig.c
def init( def init(
ui_wait_callback: Callable[[int, int, str], bool] | None = None ui_wait_callback: Callable[[int, int, str], bool] | None = None
) -> None: ) -> None:
@ -9,53 +6,32 @@ def init(
Initializes the storage. Must be called before any other method is Initializes the storage. Must be called before any other method is
called from this module! called from this module!
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def unlock(pin: str, ext_salt: bytes | None) -> bool: def unlock(pin: str, ext_salt: bytes | None) -> bool:
""" """
Attempts to unlock the storage with the given PIN and external salt. Attempts to unlock the storage with the given PIN and external salt.
Returns True on success, False on failure. Returns True on success, False on failure.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def check_pin(pin: str, ext_salt: bytes | None) -> bool: def check_pin(pin: str, ext_salt: bytes | None) -> bool:
""" """
Check the given PIN with the given external salt. Check the given PIN with the given external salt.
Returns True on success, False on failure. Returns True on success, False on failure.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def lock() -> None: def lock() -> None:
""" """
Locks the storage. Locks the storage.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def is_unlocked() -> bool: def is_unlocked() -> bool:
""" """
Returns True if storage is unlocked, False otherwise. Returns True if storage is unlocked, False otherwise.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def has_pin() -> bool: def has_pin() -> bool:
""" """
Returns True if storage has a configured PIN, False otherwise. Returns True if storage has a configured PIN, False otherwise.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def get_pin_rem() -> int: def get_pin_rem() -> int:
""" """
Returns the number of remaining PIN entry attempts. Returns the number of remaining PIN entry attempts.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def change_pin( def change_pin(
oldpin: str, oldpin: str,
newpin: str, newpin: str,
@ -65,23 +41,14 @@ def change_pin(
""" """
Change PIN and external salt. Returns True on success, False on failure. Change PIN and external salt. Returns True on success, False on failure.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def ensure_not_wipe_code(pin: str) -> None: def ensure_not_wipe_code(pin: str) -> None:
""" """
Wipes the device if the entered PIN is the wipe code. Wipes the device if the entered PIN is the wipe code.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def has_wipe_code() -> bool: def has_wipe_code() -> bool:
""" """
Returns True if storage has a configured wipe code, False otherwise. Returns True if storage has a configured wipe code, False otherwise.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def change_wipe_code( def change_wipe_code(
pin: str, pin: str,
ext_salt: bytes | None, ext_salt: bytes | None,
@ -90,43 +57,28 @@ def change_wipe_code(
""" """
Change wipe code. Returns True on success, False on failure. Change wipe code. Returns True on success, False on failure.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def get(app: int, key: int, public: bool = False) -> bytes | None: def get(app: int, key: int, public: bool = False) -> bytes | None:
""" """
Gets the value of the given key for the given app (or None if not set). Gets the value of the given key for the given app (or None if not set).
Raises a RuntimeError if decryption or authentication of the stored Raises a RuntimeError if decryption or authentication of the stored
value fails. value fails.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def set(app: int, key: int, value: bytes, public: bool = False) -> None: def set(app: int, key: int, value: bytes, public: bool = False) -> None:
""" """
Sets a value of given key for given app. Sets a value of given key for given app.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def delete( def delete(
app: int, key: int, public: bool = False, writable_locked: bool = False app: int, key: int, public: bool = False, writable_locked: bool = False
) -> bool: ) -> bool:
""" """
Deletes the given key of the given app. Deletes the given key of the given app.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def set_counter( def set_counter(
app: int, key: int, count: int, writable_locked: bool = False app: int, key: int, count: int, writable_locked: bool = False
) -> None: ) -> None:
""" """
Sets the given key of the given app as a counter with the given value. Sets the given key of the given app as a counter with the given value.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def next_counter( def next_counter(
app: int, key: int, writable_locked: bool = False, app: int, key: int, writable_locked: bool = False,
) -> int: ) -> int:
@ -134,9 +86,6 @@ def next_counter(
Increments the counter stored under the given key of the given app and Increments the counter stored under the given key of the given app and
returns the new value. returns the new value.
""" """
# extmod/modtrezorconfig/modtrezorconfig.c
def wipe() -> None: def wipe() -> None:
""" """
Erases the whole config. Use with caution! Erases the whole config. Use with caution!

@ -1,17 +1,13 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-aes.h
class aes: class aes:
""" """
AES context. AES context.
""" """
ECB: int ECB: int
CBC: int CBC: int
CFB: int CFB: int
OFB: int OFB: int
CTR: int CTR: int
def __init__( def __init__(
self, self,
mode: int, mode: int,
@ -21,50 +17,38 @@ class aes:
""" """
Initialize AES context. Initialize AES context.
""" """
def encrypt(self, data: bytes) -> bytes: def encrypt(self, data: bytes) -> bytes:
""" """
Encrypt data and update AES context. Encrypt data and update AES context.
""" """
def decrypt(self, data: bytes) -> bytes: def decrypt(self, data: bytes) -> bytes:
""" """
Decrypt data and update AES context. Decrypt data and update AES context.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-blake256.h
class blake256: class blake256:
""" """
Blake256 context. Blake256 context.
""" """
block_size: int block_size: int
digest_size: int digest_size: int
def __init__(self, __data: AnyStr | None = None) -> None: def __init__(self, __data: AnyStr | None = None) -> None:
""" """
Creates a hash context object. Creates a hash context object.
""" """
def update(self, __data: AnyStr) -> None: def update(self, __data: AnyStr) -> None:
""" """
Update the hash context with hashed data. Update the hash context with hashed data.
""" """
def digest(self) -> bytes: def digest(self) -> bytes:
""" """
Returns the digest of hashed data. Returns the digest of hashed data.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-blake2b.h
class blake2b: class blake2b:
""" """
Blake2b context. Blake2b context.
""" """
block_size: int block_size: int
digest_size: int digest_size: int
def __init__( def __init__(
self, self,
data: bytes | None = None, data: bytes | None = None,
@ -75,26 +59,20 @@ class blake2b:
""" """
Creates a hash context object. Creates a hash context object.
""" """
def update(self, __data: AnyStr) -> None: def update(self, __data: AnyStr) -> None:
""" """
Update the hash context with hashed data. Update the hash context with hashed data.
""" """
def digest(self) -> bytes: def digest(self) -> bytes:
""" """
Returns the digest of hashed data. Returns the digest of hashed data.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-blake2s.h
class blake2s: class blake2s:
""" """
Blake2s context. Blake2s context.
""" """
block_size: int block_size: int
digest_size: int digest_size: int
def __init__( def __init__(
self, self,
data: bytes | None = None, data: bytes | None = None,
@ -105,87 +83,67 @@ class blake2s:
""" """
Creates a hash context object. Creates a hash context object.
""" """
def update(self, __data: AnyStr) -> None: def update(self, __data: AnyStr) -> None:
""" """
Update the hash context with hashed data. Update the hash context with hashed data.
""" """
def digest(self) -> bytes: def digest(self) -> bytes:
""" """
Returns the digest of hashed data. Returns the digest of hashed data.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-chacha20poly1305.h
class chacha20poly1305: class chacha20poly1305:
""" """
ChaCha20Poly1305 context. ChaCha20Poly1305 context.
""" """
def __init__(self, key: bytes, nonce: bytes) -> None: def __init__(self, key: bytes, nonce: bytes) -> None:
""" """
Initialize the ChaCha20 + Poly1305 context for encryption or decryption Initialize the ChaCha20 + Poly1305 context for encryption or decryption
using a 32 byte key and 12 byte nonce as in the RFC 7539 style. 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: bytes) -> bytes:
""" """
Encrypt data (length of data must be divisible by 64 except for the Encrypt data (length of data must be divisible by 64 except for the
final value). final value).
""" """
def decrypt(self, data: bytes) -> bytes: def decrypt(self, data: bytes) -> bytes:
""" """
Decrypt data (length of data must be divisible by 64 except for the Decrypt data (length of data must be divisible by 64 except for the
final value). final value).
""" """
def auth(self, data: bytes) -> None: def auth(self, data: bytes) -> None:
""" """
Include authenticated data in the Poly1305 MAC using the RFC 7539 Include authenticated data in the Poly1305 MAC using the RFC 7539
style with 16 byte padding. This must only be called once and prior style with 16 byte padding. This must only be called once and prior
to encryption or decryption. to encryption or decryption.
""" """
def finish(self) -> bytes: def finish(self) -> bytes:
""" """
Compute RFC 7539-style Poly1305 MAC. Compute RFC 7539-style Poly1305 MAC.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-groestl.h
class groestl512: class groestl512:
""" """
GROESTL512 context. GROESTL512 context.
""" """
block_size: int block_size: int
digest_size: int digest_size: int
def __init__(self, __data: AnyStr | None = None) -> None: def __init__(self, __data: AnyStr | None = None) -> None:
""" """
Creates a hash context object. Creates a hash context object.
""" """
def update(self, __data: AnyStr) -> None: def update(self, __data: AnyStr) -> None:
""" """
Update the hash context with hashed data. Update the hash context with hashed data.
""" """
def digest(self) -> bytes: def digest(self) -> bytes:
""" """
Returns the digest of hashed data. Returns the digest of hashed data.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-hmac.h
class hmac: class hmac:
""" """
HMAC context. HMAC context.
""" """
SHA256: int SHA256: int
SHA512: int SHA512: int
def __init__( def __init__(
self, self,
hashtype: int, hashtype: int,
@ -195,26 +153,20 @@ class hmac:
""" """
Create a HMAC context. Create a HMAC context.
""" """
def update(self, message: bytes) -> None: def update(self, message: bytes) -> None:
""" """
Update a HMAC context. Update a HMAC context.
""" """
def digest(self) -> bytes: def digest(self) -> bytes:
""" """
Return the digest of processed data so far. Return the digest of processed data so far.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-pbkdf2.h
class pbkdf2: class pbkdf2:
""" """
PBKDF2 context. PBKDF2 context.
""" """
HMAC_SHA256: int HMAC_SHA256: int
HMAC_SHA512: int HMAC_SHA512: int
def __init__( def __init__(
self, self,
prf: int, prf: int,
@ -226,98 +178,74 @@ class pbkdf2:
""" """
Create a PBKDF2 context. Create a PBKDF2 context.
""" """
def update(self, iterations: int) -> None: def update(self, iterations: int) -> None:
""" """
Update a PBKDF2 context. Update a PBKDF2 context.
""" """
def key(self) -> bytes: def key(self) -> bytes:
""" """
Retrieve derived key. Retrieve derived key.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-ripemd160.h
class ripemd160: class ripemd160:
""" """
RIPEMD160 context. RIPEMD160 context.
""" """
block_size: int block_size: int
digest_size: int digest_size: int
def __init__(self, __data: AnyStr | None = None) -> None: def __init__(self, __data: AnyStr | None = None) -> None:
""" """
Creates a hash context object. Creates a hash context object.
""" """
def update(self, __data: AnyStr) -> None: def update(self, __data: AnyStr) -> None:
""" """
Update the hash context with hashed data. Update the hash context with hashed data.
""" """
def digest(self) -> bytes: def digest(self) -> bytes:
""" """
Returns the digest of hashed data. Returns the digest of hashed data.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-sha1.h
class sha1: class sha1:
""" """
SHA1 context. SHA1 context.
""" """
block_size: int block_size: int
digest_size: int digest_size: int
def __init__(self, __data: AnyStr | None = None) -> None: def __init__(self, __data: AnyStr | None = None) -> None:
""" """
Creates a hash context object. Creates a hash context object.
""" """
def update(self, __data: AnyStr) -> None: def update(self, __data: AnyStr) -> None:
""" """
Update the hash context with hashed data. Update the hash context with hashed data.
""" """
def digest(self) -> bytes: def digest(self) -> bytes:
""" """
Returns the digest of hashed data. Returns the digest of hashed data.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-sha256.h
class sha256: class sha256:
""" """
SHA256 context. SHA256 context.
""" """
block_size: int block_size: int
digest_size: int digest_size: int
def __init__(self, __data: AnyStr | None = None) -> None: def __init__(self, __data: AnyStr | None = None) -> None:
""" """
Creates a hash context object. Creates a hash context object.
""" """
def update(self, __data: AnyStr) -> None: def update(self, __data: AnyStr) -> None:
""" """
Update the hash context with hashed data. Update the hash context with hashed data.
""" """
def digest(self) -> bytes: def digest(self) -> bytes:
""" """
Returns the digest of hashed data. Returns the digest of hashed data.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-sha3-256.h
class sha3_256: class sha3_256:
""" """
SHA3_256 context. SHA3_256 context.
""" """
block_size: int block_size: int
digest_size: int digest_size: int
def __init__( def __init__(
self, self,
data: bytes | None = None, data: bytes | None = None,
@ -326,31 +254,24 @@ class sha3_256:
""" """
Creates a hash context object. Creates a hash context object.
""" """
def update(self, __data: AnyStr) -> None: def update(self, __data: AnyStr) -> None:
""" """
Update the hash context with hashed data. Update the hash context with hashed data.
""" """
def digest(self) -> bytes: def digest(self) -> bytes:
""" """
Returns the digest of hashed data. Returns the digest of hashed data.
""" """
def copy(self) -> sha3_256: def copy(self) -> sha3_256:
""" """
Returns the copy of the digest object with the current state Returns the copy of the digest object with the current state
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-sha3-512.h
class sha3_512: class sha3_512:
""" """
SHA3_512 context. SHA3_512 context.
""" """
block_size: int block_size: int
digest_size: int digest_size: int
def __init__( def __init__(
self, self,
data: bytes | None = None, data: bytes | None = None,
@ -359,41 +280,32 @@ class sha3_512:
""" """
Creates a hash context object. Creates a hash context object.
""" """
def update(self, __data: AnyStr) -> None: def update(self, __data: AnyStr) -> None:
""" """
Update the hash context with hashed data. Update the hash context with hashed data.
""" """
def digest(self) -> bytes: def digest(self) -> bytes:
""" """
Returns the digest of hashed data. Returns the digest of hashed data.
""" """
def copy(self) -> sha3_512: def copy(self) -> sha3_512:
""" """
Returns the copy of the digest object with the current state Returns the copy of the digest object with the current state
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-sha512.h
class sha512: class sha512:
""" """
SHA512 context. SHA512 context.
""" """
block_size: int block_size: int
digest_size: int digest_size: int
def __init__(self, __data: AnyStr | None = None) -> None: def __init__(self, __data: AnyStr | None = None) -> None:
""" """
Creates a hash context object. Creates a hash context object.
""" """
def update(self, __data: AnyStr) -> None: def update(self, __data: AnyStr) -> None:
""" """
Update the hash context with hashed data. Update the hash context with hashed data.
""" """
def digest(self) -> bytes: def digest(self) -> bytes:
""" """
Returns the digest of hashed data. Returns the digest of hashed data.

@ -1,7 +1,4 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-bech32.h
def decode( def decode(
bech: str, bech: str,
max_bech_len: int = 90, max_bech_len: int = 90,

@ -1,12 +1,8 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-bip32.h
class HDNode: class HDNode:
""" """
BIP0032 HD node structure. BIP0032 HD node structure.
""" """
def __init__( def __init__(
self, self,
depth: int, depth: int,
@ -19,92 +15,73 @@ class HDNode:
) -> None: ) -> None:
""" """
""" """
def derive(self, index: int, public: bool = False) -> None: def derive(self, index: int, public: bool = False) -> None:
""" """
Derive a BIP0032 child node in place. Derive a BIP0032 child node in place.
""" """
def derive_path(self, path: Sequence[int]) -> None: def derive_path(self, path: Sequence[int]) -> None:
""" """
Go through a list of indexes and iteratively derive a child node in Go through a list of indexes and iteratively derive a child node in
place. place.
""" """
def serialize_public(self, version: int) -> str: def serialize_public(self, version: int) -> str:
""" """
Serialize the public info from HD node to base58 string. Serialize the public info from HD node to base58 string.
""" """
def clone(self) -> HDNode: def clone(self) -> HDNode:
""" """
Returns a copy of the HD node. Returns a copy of the HD node.
""" """
def depth(self) -> int: def depth(self) -> int:
""" """
Returns a depth of the HD node. Returns a depth of the HD node.
""" """
def fingerprint(self) -> int: def fingerprint(self) -> int:
""" """
Returns a fingerprint of the HD node (hash of the parent public key). Returns a fingerprint of the HD node (hash of the parent public key).
""" """
def child_num(self) -> int: def child_num(self) -> int:
""" """
Returns a child index of the HD node. Returns a child index of the HD node.
""" """
def chain_code(self) -> bytes: def chain_code(self) -> bytes:
""" """
Returns a chain code of the HD node. Returns a chain code of the HD node.
""" """
def private_key(self) -> bytes: def private_key(self) -> bytes:
""" """
Returns a private key of the HD node. Returns a private key of the HD node.
""" """
def private_key_ext(self) -> bytes: def private_key_ext(self) -> bytes:
""" """
Returns a private key extension of the HD node. Returns a private key extension of the HD node.
""" """
def public_key(self) -> bytes: def public_key(self) -> bytes:
""" """
Returns a public key of the HD node. Returns a public key of the HD node.
""" """
def address(self, version: int) -> str: def address(self, version: int) -> str:
""" """
Compute a base58-encoded address string from the HD node. Compute a base58-encoded address string from the HD node.
""" """
def nem_address(self, network: int) -> str: def nem_address(self, network: int) -> str:
""" """
Compute a NEM address string from the HD node. Compute a NEM address string from the HD node.
""" """
def nem_encrypt( def nem_encrypt(
self, transfer_public_key: bytes, iv: bytes, salt: bytes, payload: bytes self, transfer_public_key: bytes, iv: bytes, salt: bytes, payload: bytes
) -> bytes: ) -> bytes:
""" """
Encrypts payload using the transfer's public key Encrypts payload using the transfer's public key
""" """
def ethereum_pubkeyhash(self) -> bytes: def ethereum_pubkeyhash(self) -> bytes:
""" """
Compute an Ethereum pubkeyhash (aka address) from the HD node. Compute an Ethereum pubkeyhash (aka address) from the HD node.
""" """
def __del__(self) -> None: def __del__(self) -> None:
""" """
Cleans up sensitive memory. Cleans up sensitive memory.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-bip32.h
def from_seed(seed: bytes, curve_name: str) -> HDNode: def from_seed(seed: bytes, curve_name: str) -> HDNode:
""" """
Construct a BIP0032 HD node from a BIP0039 seed value. Construct a BIP0032 HD node from a BIP0039 seed value.

@ -1,21 +1,12 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-bip340.h
def generate_secret() -> bytes: def generate_secret() -> bytes:
""" """
Generate secret key. Generate secret key.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-bip340.h
def publickey(secret_key: bytes) -> bytes: def publickey(secret_key: bytes) -> bytes:
""" """
Computes public key from secret key. Computes public key from secret key.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-bip340.h
def sign( def sign(
secret_key: bytes, secret_key: bytes,
digest: bytes, digest: bytes,
@ -23,25 +14,16 @@ def sign(
""" """
Uses secret key to produce the signature of the digest. Uses secret key to produce the signature of the digest.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-bip340.h
def verify_publickey(public_key: bytes) -> bool: def verify_publickey(public_key: bytes) -> bool:
""" """
Verifies whether the public key is valid. Verifies whether the public key is valid.
Returns True on success. Returns True on success.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-bip340.h
def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool: def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool:
""" """
Uses public key to verify the signature of the digest. Uses public key to verify the signature of the digest.
Returns True on success. Returns True on success.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-bip340.h
def tweak_public_key( def tweak_public_key(
public_key: bytes, public_key: bytes,
root_hash: bytes | None = None, root_hash: bytes | None = None,
@ -49,9 +31,6 @@ def tweak_public_key(
""" """
Tweaks the public key with the specified root_hash. Tweaks the public key with the specified root_hash.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-bip340.h
def tweak_secret_key( def tweak_secret_key(
secret_key: bytes, secret_key: bytes,
root_hash: bytes | None = None, root_hash: bytes | None = None,

@ -1,28 +1,16 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-bip39.h
def generate(strength: int) -> str: def generate(strength: int) -> str:
""" """
Generate a mnemonic of given strength (128, 160, 192, 224 and 256 bits). Generate a mnemonic of given strength (128, 160, 192, 224 and 256 bits).
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-bip39.h
def from_data(data: bytes) -> str: def from_data(data: bytes) -> str:
""" """
Generate a mnemonic from given data (of 16, 20, 24, 28 and 32 bytes). Generate a mnemonic from given data (of 16, 20, 24, 28 and 32 bytes).
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-bip39.h
def check(mnemonic: str) -> bool: def check(mnemonic: str) -> bool:
""" """
Check whether given mnemonic is valid. Check whether given mnemonic is valid.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-bip39.h
def seed( def seed(
mnemonic: str, mnemonic: str,
passphrase: str, passphrase: str,

@ -1,8 +1,5 @@
from typing import * from typing import *
from trezorcrypto.bip32 import HDNode from trezorcrypto.bip32 import HDNode
# extmod/modtrezorcrypto/modtrezorcrypto-cardano.h
def derive_icarus( def derive_icarus(
mnemonic: str, mnemonic: str,
passphrase: str, passphrase: str,
@ -15,23 +12,14 @@ def derive_icarus(
If `trezor_derivation` is True, the Icarus-Trezor variant is used (see If `trezor_derivation` is True, the Icarus-Trezor variant is used (see
CIP-3). CIP-3).
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-cardano.h
def from_secret(secret: bytes) -> HDNode: def from_secret(secret: bytes) -> HDNode:
""" """
Creates a Cardano HD node from a master secret. Creates a Cardano HD node from a master secret.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-cardano.h
def from_seed_slip23(seed: bytes) -> HDNode: def from_seed_slip23(seed: bytes) -> HDNode:
""" """
Creates a Cardano HD node from a seed via SLIP-23 derivation. Creates a Cardano HD node from a seed via SLIP-23 derivation.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-cardano.h
def from_seed_ledger(seed: bytes) -> HDNode: def from_seed_ledger(seed: bytes) -> HDNode:
""" """
Creates a Cardano HD node from a seed via Ledger derivation. Creates a Cardano HD node from a seed via Ledger derivation.

@ -1,7 +1,4 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-crc.h
def crc32(data: bytes, crc: int = 0) -> int: def crc32(data: bytes, crc: int = 0) -> int:
""" """
Computes a CRC32 checksum of `data`. Computes a CRC32 checksum of `data`.

@ -1,21 +1,12 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-curve25519.h
def generate_secret() -> bytes: def generate_secret() -> bytes:
""" """
Generate secret key. Generate secret key.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-curve25519.h
def publickey(secret_key: bytes) -> bytes: def publickey(secret_key: bytes) -> bytes:
""" """
Computes public key from secret key. Computes public key from secret key.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-curve25519.h
def multiply(secret_key: bytes, public_key: bytes) -> bytes: def multiply(secret_key: bytes, public_key: bytes) -> bytes:
""" """
Multiplies point defined by public_key with scalar defined by Multiplies point defined by public_key with scalar defined by

@ -1,66 +1,39 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h
def generate_secret() -> bytes: def generate_secret() -> bytes:
""" """
Generate secret key. Generate secret key.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h
def publickey(secret_key: bytes) -> bytes: def publickey(secret_key: bytes) -> bytes:
""" """
Computes public key from secret key. Computes public key from secret key.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h
def sign(secret_key: bytes, message: bytes, hasher: str = "") -> bytes: def sign(secret_key: bytes, message: bytes, hasher: str = "") -> bytes:
""" """
Uses secret key to produce the signature of message. Uses secret key to produce the signature of message.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h
def sign_ext( def sign_ext(
secret_key: bytes, secret_extension: bytes, message: bytes secret_key: bytes, secret_extension: bytes, message: bytes
) -> bytes: ) -> bytes:
""" """
Uses secret key to produce the cardano signature of message. Uses secret key to produce the cardano signature of message.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h
def verify(public_key: bytes, signature: bytes, message: bytes) -> bool: def verify(public_key: bytes, signature: bytes, message: bytes) -> bool:
""" """
Uses public key to verify the signature of the message. Uses public key to verify the signature of the message.
Returns True on success. Returns True on success.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h
def cosi_combine_publickeys(public_keys: list[bytes]) -> bytes: def cosi_combine_publickeys(public_keys: list[bytes]) -> bytes:
""" """
Combines a list of public keys used in COSI cosigning scheme. Combines a list of public keys used in COSI cosigning scheme.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h
def cosi_combine_signatures(R: bytes, signatures: list[bytes]) -> bytes: def cosi_combine_signatures(R: bytes, signatures: list[bytes]) -> bytes:
""" """
Combines a list of signatures used in COSI cosigning scheme. Combines a list of signatures used in COSI cosigning scheme.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h
def cosi_commit() -> tuple[bytes, bytes]: def cosi_commit() -> tuple[bytes, bytes]:
""" """
Generate a nonce and commitment for the CoSi cosigning scheme. Generate a nonce and commitment for the CoSi cosigning scheme.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-ed25519.h
def cosi_sign( def cosi_sign(
secret_key: bytes, secret_key: bytes,
message: bytes, message: bytes,

@ -1,269 +1,183 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
class Point: class Point:
"""
EC point on ED25519
"""
def __init__(self, x: Point | bytes | None = None):
""" """
Constructor EC point on ED25519
""" """
def __init__(self, x: Point | bytes | None = None):
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h """
Constructor
"""
class Scalar: class Scalar:
"""
EC scalar on SC25519
"""
def __init__(self, x: Scalar | bytes | int | None = None):
""" """
Constructor EC scalar on SC25519
""" """
def __init__(self, x: Scalar | bytes | int | None = None):
"""
Constructor
"""
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
class Hasher: class Hasher:
"""
XMR hasher
"""
def __init__(self, x: bytes | None = None):
"""
Constructor
"""
def update(self, buffer: bytes) -> None:
"""
Update hasher
""" """
def digest(self) -> bytes: XMR hasher
"""
Computes digest
"""
def copy(self) -> Hasher:
"""
Creates copy of the hasher, preserving the state
""" """
def __init__(self, x: bytes | None = None):
"""
Constructor
"""
def update(self, buffer: bytes) -> None:
"""
Update hasher
"""
def digest(self) -> bytes:
"""
Computes digest
"""
def copy(self) -> Hasher:
"""
Creates copy of the hasher, preserving the state
"""
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def sc_copy( def sc_copy(
dst: Scalar | None, val: int | bytes | Scalar dst: Scalar | None, val: int | bytes | Scalar
) -> Scalar: ) -> Scalar:
""" """
Initializes a scalar Initializes a scalar
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def sc_check(val: Scalar) -> None: def sc_check(val: Scalar) -> None:
""" """
Throws exception if scalar is invalid Throws exception if scalar is invalid
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def sc_iszero(val: Scalar) -> bool: def sc_iszero(val: Scalar) -> bool:
""" """
Returns False if the scalar is zero Returns False if the scalar is zero
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def sc_eq(a: Scalar, b: Scalar) -> int: def sc_eq(a: Scalar, b: Scalar) -> int:
""" """
Compares scalars, returns 1 on the same value Compares scalars, returns 1 on the same value
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def sc_add_into(r: Scalar | None, a: Scalar, b: Scalar) -> Scalar: def sc_add_into(r: Scalar | None, a: Scalar, b: Scalar) -> Scalar:
""" """
Scalar addition Scalar addition
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def sc_sub_into(r: Scalar | None, a: Scalar, b: Scalar) -> Scalar: def sc_sub_into(r: Scalar | None, a: Scalar, b: Scalar) -> Scalar:
""" """
Scalar subtraction Scalar subtraction
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def sc_mul_into(r: Scalar | None, a: Scalar, b: Scalar) -> Scalar: def sc_mul_into(r: Scalar | None, a: Scalar, b: Scalar) -> Scalar:
""" """
Scalar multiplication Scalar multiplication
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def sc_mulsub_into( def sc_mulsub_into(
r: Scalar | None, a: Scalar, b: Scalar, c: Scalar r: Scalar | None, a: Scalar, b: Scalar, c: Scalar
) -> Scalar: ) -> Scalar:
""" """
c - a*b c - a*b
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def sc_muladd_into( def sc_muladd_into(
r: Scalar | None, a: Scalar, b: Scalar, c: Scalar r: Scalar | None, a: Scalar, b: Scalar, c: Scalar
) -> Scalar: ) -> Scalar:
""" """
c + a*b c + a*b
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def sc_inv_into(r: Scalar | None, a: Scalar) -> Scalar: def sc_inv_into(r: Scalar | None, a: Scalar) -> Scalar:
""" """
Scalar modular inversion Scalar modular inversion
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def encodeint_into( def encodeint_into(
r: bytes | None, a: Scalar, offset: int | None = 0 r: bytes | None, a: Scalar, offset: int | None = 0
) -> bytes: ) -> bytes:
""" """
Scalar compression Scalar compression
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def decodeint_into( def decodeint_into(
r: Scalar | None, a: bytes, offset: int = 0 r: Scalar | None, a: bytes, offset: int = 0
) -> Scalar: ) -> Scalar:
""" """
Scalar decompression Scalar decompression
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def decodeint_into_noreduce( def decodeint_into_noreduce(
r: Scalar | None, a: bytes, offset: int = 0 r: Scalar | None, a: bytes, offset: int = 0
) -> Scalar: ) -> Scalar:
""" """
Scalar decompression, raw, without modular reduction Scalar decompression, raw, without modular reduction
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def identity_into(r: Point | None = None) -> Point: def identity_into(r: Point | None = None) -> Point:
""" """
Sets neutral point Sets neutral point
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_H(r: Point | None = None) -> Point: def xmr_H(r: Point | None = None) -> Point:
""" """
Sets H point Sets H point
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def ge25519_check(r: Point) -> None: def ge25519_check(r: Point) -> None:
""" """
Checks point, throws if not on curve Checks point, throws if not on curve
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def point_eq(a: Point, b: Point) -> bool: def point_eq(a: Point, b: Point) -> bool:
""" """
Compares EC points Compares EC points
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def point_add_into(r: Point | None, a: Point, b: Point) -> Point: def point_add_into(r: Point | None, a: Point, b: Point) -> Point:
""" """
Adds EC points Adds EC points
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def point_sub_into(r: Point | None, a: Point, b: Point) -> Point: def point_sub_into(r: Point | None, a: Point, b: Point) -> Point:
""" """
Subtracts EC points Subtracts EC points
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def ge25519_mul8(r: Point | None, p: Point) -> Point: def ge25519_mul8(r: Point | None, p: Point) -> Point:
""" """
EC point * 8 EC point * 8
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def ge25519_double_scalarmult_vartime_into( def ge25519_double_scalarmult_vartime_into(
r: Point | None, p1: Point, s1: Scalar, s2: Scalar r: Point | None, p1: Point, s1: Scalar, s2: Scalar
) -> Point: ) -> Point:
""" """
s1 * G + s2 * p1 s1 * G + s2 * p1
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def scalarmult_base_into( def scalarmult_base_into(
r: Point | None, s: Scalar | int r: Point | None, s: Scalar | int
) -> Point: ) -> Point:
""" """
s * G s * G
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def scalarmult_into( def scalarmult_into(
r: Point | None, p: Point, s: Scalar | int r: Point | None, p: Point, s: Scalar | int
) -> Point: ) -> Point:
""" """
s * p s * p
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def encodepoint_into(r: bytes | None, p: Point, offset: int = 0) -> bytes: def encodepoint_into(r: bytes | None, p: Point, offset: int = 0) -> bytes:
""" """
Point compression Point compression
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def decodepoint_into( def decodepoint_into(
r: Point | None, buff: bytes, offset: int = 0 r: Point | None, buff: bytes, offset: int = 0
) -> Point: ) -> Point:
""" """
Point decompression Point decompression
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_base58_addr_encode_check(tag: int, buff: bytes) -> str: def xmr_base58_addr_encode_check(tag: int, buff: bytes) -> str:
""" """
Monero block base 58 encoding Monero block base 58 encoding
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_base58_addr_decode_check(buff: bytes) -> tuple[bytes, int]: def xmr_base58_addr_decode_check(buff: bytes) -> tuple[bytes, int]:
""" """
Monero block base 58 decoding, returning (decoded, tag) or raising on Monero block base 58 decoding, returning (decoded, tag) or raising on
error. error.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def random_scalar(r: Scalar | None = None) -> Scalar: def random_scalar(r: Scalar | None = None) -> Scalar:
""" """
Generates a random scalar Generates a random scalar
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def fast_hash_into( def fast_hash_into(
r: bytes | None, r: bytes | None,
buff: bytes, buff: bytes,
@ -273,9 +187,6 @@ def fast_hash_into(
""" """
XMR fast hash XMR fast hash
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def hash_to_point_into( def hash_to_point_into(
r: Point | None, r: Point | None,
buff: bytes, buff: bytes,
@ -285,9 +196,6 @@ def hash_to_point_into(
""" """
XMR hashing to EC point XMR hashing to EC point
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def hash_to_scalar_into( def hash_to_scalar_into(
r: Scalar | None, r: Scalar | None,
buff: bytes, buff: bytes,
@ -297,79 +205,52 @@ def hash_to_scalar_into(
""" """
XMR hashing to EC scalar XMR hashing to EC scalar
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_derivation_to_scalar( def xmr_derivation_to_scalar(
r: Scalar | None, p: Point, output_index: int r: Scalar | None, p: Point, output_index: int
) -> Scalar: ) -> Scalar:
""" """
H_s(derivation || varint(output_index)) H_s(derivation || varint(output_index))
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_generate_key_derivation( def xmr_generate_key_derivation(
r: Point | None, A: Point, b: Scalar r: Point | None, A: Point, b: Scalar
) -> Point: ) -> Point:
""" """
8*(key2*key1) 8*(key2*key1)
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_derive_private_key( def xmr_derive_private_key(
r: Scalar | None, deriv: Point, idx: int, base: Scalar r: Scalar | None, deriv: Point, idx: int, base: Scalar
) -> Scalar: ) -> Scalar:
""" """
base + H_s(derivation || varint(output_index)) base + H_s(derivation || varint(output_index))
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_derive_public_key( def xmr_derive_public_key(
r: Point | None, deriv: Point, idx: int, base: Point r: Point | None, deriv: Point, idx: int, base: Point
) -> Point: ) -> Point:
""" """
H_s(derivation || varint(output_index))G + base H_s(derivation || varint(output_index))G + base
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def add_keys2_into( def add_keys2_into(
r: Point | None, a: Scalar, b: Scalar, B: Point r: Point | None, a: Scalar, b: Scalar, B: Point
) -> Point: ) -> Point:
""" """
aG + bB, G is basepoint aG + bB, G is basepoint
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def add_keys3_into( def add_keys3_into(
r: Point | None, a: Scalar, A: Point, b: Scalar, B: Point r: Point | None, a: Scalar, A: Point, b: Scalar, B: Point
) -> Point: ) -> Point:
""" """
aA + bB aA + bB
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def xmr_get_subaddress_secret_key( def xmr_get_subaddress_secret_key(
r: Scalar | None, major: int, minor: int, m: Scalar r: Scalar | None, major: int, minor: int, m: Scalar
) -> Scalar: ) -> Scalar:
""" """
Hs(SubAddr || a || index_major || index_minor) Hs(SubAddr || a || index_major || index_minor)
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def gen_commitment_into(r: Point | None, a: Scalar, amount: int) -> Point: def gen_commitment_into(r: Point | None, a: Scalar, amount: int) -> Point:
""" """
aG + amount * H aG + amount * H
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-monero.h
def ct_equals(a: bytes, b: bytes) -> bool: def ct_equals(a: bytes, b: bytes) -> bool:
""" """
Constant time buffer comparison Constant time buffer comparison

@ -1,14 +1,8 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-nem.h
def validate_address(address: str, network: int) -> bool: def validate_address(address: str, network: int) -> bool:
""" """
Validate a NEM address Validate a NEM address
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-nem.h
def compute_address(public_key: bytes, network: int) -> str: def compute_address(public_key: bytes, network: int) -> str:
""" """
Compute a NEM address from a public key Compute a NEM address from a public key

@ -1,46 +1,28 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
def generate_secret() -> bytes: def generate_secret() -> bytes:
""" """
Generate secret key. Generate secret key.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
def publickey(secret_key: bytes, compressed: bool = True) -> bytes: def publickey(secret_key: bytes, compressed: bool = True) -> bytes:
""" """
Computes public key from secret key. Computes public key from secret key.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
def sign( def sign(
secret_key: bytes, digest: bytes, compressed: bool = True secret_key: bytes, digest: bytes, compressed: bool = True
) -> bytes: ) -> bytes:
""" """
Uses secret key to produce the signature of the digest. Uses secret key to produce the signature of the digest.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool: def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool:
""" """
Uses public key to verify the signature of the digest. Uses public key to verify the signature of the digest.
Returns True on success. Returns True on success.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
def verify_recover(signature: bytes, digest: bytes) -> bytes: def verify_recover(signature: bytes, digest: bytes) -> bytes:
""" """
Uses signature of the digest to verify the digest and recover the public 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. key. Returns public key on success, None if the signature is invalid.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-nist256p1.h
def multiply(secret_key: bytes, public_key: bytes) -> bytes: def multiply(secret_key: bytes, public_key: bytes) -> bytes:
""" """
Multiplies point defined by public_key with scalar defined by Multiplies point defined by public_key with scalar defined by

@ -1,29 +1,17 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-random.h
def uniform(n: int) -> int: def uniform(n: int) -> int:
""" """
Compute uniform random number from interval 0 ... n - 1. Compute uniform random number from interval 0 ... n - 1.
""" """
import builtins import builtins
# extmod/modtrezorcrypto/modtrezorcrypto-random.h
def bytes(len: int) -> builtins.bytes: def bytes(len: int) -> builtins.bytes:
""" """
Generate random bytes sequence of length len. Generate random bytes sequence of length len.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-random.h
def shuffle(data: list) -> None: def shuffle(data: list) -> None:
""" """
Shuffles items of given list (in-place). Shuffles items of given list (in-place).
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-random.h
def reseed(value: int) -> None: def reseed(value: int) -> None:
""" """
Re-seed the RNG with given value. Re-seed the RNG with given value.

@ -1,23 +1,14 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
def generate_secret() -> bytes: def generate_secret() -> bytes:
""" """
Generate secret key. Generate secret key.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
def publickey(secret_key: bytes, compressed: bool = True) -> bytes: def publickey(secret_key: bytes, compressed: bool = True) -> bytes:
""" """
Computes public key from secret key. Computes public key from secret key.
""" """
CANONICAL_SIG_ETHEREUM: int = 1 CANONICAL_SIG_ETHEREUM: int = 1
CANONICAL_SIG_EOS: int = 2 CANONICAL_SIG_EOS: int = 2
# extmod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
def sign( def sign(
secret_key: bytes, secret_key: bytes,
digest: bytes, digest: bytes,
@ -27,25 +18,16 @@ def sign(
""" """
Uses secret key to produce the signature of the digest. Uses secret key to produce the signature of the digest.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool: def verify(public_key: bytes, signature: bytes, digest: bytes) -> bool:
""" """
Uses public key to verify the signature of the digest. Uses public key to verify the signature of the digest.
Returns True on success. Returns True on success.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
def verify_recover(signature: bytes, digest: bytes) -> bytes: def verify_recover(signature: bytes, digest: bytes) -> bytes:
""" """
Uses signature of the digest to verify the digest and recover the public 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. key. Returns public key on success, None if the signature is invalid.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-secp256k1.h
def multiply(secret_key: bytes, public_key: bytes) -> bytes: def multiply(secret_key: bytes, public_key: bytes) -> bytes:
""" """
Multiplies point defined by public_key with scalar defined by Multiplies point defined by public_key with scalar defined by

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

@ -1,15 +1,9 @@
from typing import * from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-slip39.h
def word_index(word: str) -> int: def word_index(word: str) -> int:
""" """
Finds index of given word. Finds index of given word.
Raises ValueError if not found. Raises ValueError if not found.
""" """
# extmod/modtrezorcrypto/modtrezorcrypto-slip39.h
def get_word(index: int) -> str: def get_word(index: int) -> str:
""" """
Returns word on position 'index'. Returns word on position 'index'.

@ -1,42 +1,30 @@
from typing import * from typing import *
# extmod/modtrezorio/modtrezorio-flash.h
class FlashOTP: class FlashOTP:
""" """
""" """
def __init__(self) -> None: def __init__(self) -> None:
""" """
""" """
def write(self, block: int, offset: int, data: bytes) -> None: def write(self, block: int, offset: int, data: bytes) -> None:
""" """
Writes data to OTP flash Writes data to OTP flash
""" """
def read(self, block: int, offset: int, data: bytearray) -> None: def read(self, block: int, offset: int, data: bytearray) -> None:
""" """
Reads data from OTP flash Reads data from OTP flash
""" """
def lock(self, block: int) -> None: def lock(self, block: int) -> None:
""" """
Lock OTP flash block Lock OTP flash block
""" """
def is_locked(self, block: int) -> bool: def is_locked(self, block: int) -> bool:
""" """
Is OTP flash block locked? Is OTP flash block locked?
""" """
# extmod/modtrezorio/modtrezorio-hid.h
class HID: class HID:
""" """
USB HID interface configuration. USB HID interface configuration.
""" """
def __init__( def __init__(
self, self,
iface_num: int, iface_num: int,
@ -51,59 +39,46 @@ class HID:
) -> None: ) -> None:
""" """
""" """
def iface_num(self) -> int: def iface_num(self) -> int:
""" """
Returns the configured number of this interface. Returns the configured number of this interface.
""" """
def write(self, msg: bytes) -> int: def write(self, msg: bytes) -> int:
""" """
Sends message using USB HID (device) or UDP (emulator). Sends message using USB HID (device) or UDP (emulator).
""" """
def write_blocking(self, msg: bytes, timeout_ms: int) -> int: def write_blocking(self, msg: bytes, timeout_ms: int) -> int:
""" """
Sends message using USB HID (device) or UDP (emulator). Sends message using USB HID (device) or UDP (emulator).
""" """
# extmod/modtrezorio/modtrezorio-poll.h
def poll(ifaces: Iterable[int], list_ref: list, timeout_ms: int) -> bool: def poll(ifaces: Iterable[int], list_ref: list, timeout_ms: int) -> bool:
""" """
Wait until one of `ifaces` is ready to read or write (using masks Wait until one of `ifaces` is ready to read or write (using masks
`list_ref`: `list_ref`:
`list_ref[0]` - the interface number, including the mask `list_ref[0]` - the interface number, including the mask
`list_ref[1]` - for touch event, tuple of: `list_ref[1]` - for touch event, tuple of:
(event_type, x_position, y_position) (event_type, x_position, y_position)
- for button event (T1), tuple of: - for button event (T1), tuple of:
(event type, button number) (event type, button number)
- for USB read event, received bytes - for USB read event, received bytes
If timeout occurs, False is returned, True otherwise. If timeout occurs, False is returned, True otherwise.
""" """
# extmod/modtrezorio/modtrezorio-sbu.h
class SBU: class SBU:
""" """
""" """
def __init__(self) -> None: def __init__(self) -> None:
""" """
""" """
def set(self, sbu1: bool, sbu2: bool) -> None: def set(self, sbu1: bool, sbu2: bool) -> None:
""" """
Sets SBU wires to sbu1 and sbu2 values respectively Sets SBU wires to sbu1 and sbu2 values respectively
""" """
# extmod/modtrezorio/modtrezorio-usb.h
class USB: class USB:
""" """
USB device configuration. USB device configuration.
""" """
def __init__( def __init__(
self, self,
vendor_id: int, vendor_id: int,
@ -120,29 +95,22 @@ class USB:
) -> None: ) -> None:
""" """
""" """
def add(self, iface: HID | VCP | WebUSB) -> None: def add(self, iface: HID | VCP | WebUSB) -> None:
""" """
Registers passed interface into the USB stack. Registers passed interface into the USB stack.
""" """
def open(self, serial_number: str) -> None: def open(self, serial_number: str) -> None:
""" """
Initializes the USB stack. Initializes the USB stack.
""" """
def close(self) -> None: def close(self) -> None:
""" """
Cleans up the USB stack. Cleans up the USB stack.
""" """
# extmod/modtrezorio/modtrezorio-vcp.h
class VCP: class VCP:
""" """
USB VCP interface configuration. USB VCP interface configuration.
""" """
def __init__( def __init__(
self, self,
iface_num: int, iface_num: int,
@ -154,19 +122,14 @@ class VCP:
) -> None: ) -> None:
""" """
""" """
def iface_num(self) -> int: def iface_num(self) -> int:
""" """
Returns the configured number of this interface. Returns the configured number of this interface.
""" """
# extmod/modtrezorio/modtrezorio-webusb.h
class WebUSB: class WebUSB:
""" """
USB WebUSB interface configuration. USB WebUSB interface configuration.
""" """
def __init__( def __init__(
self, self,
iface_num: int, iface_num: int,
@ -180,12 +143,10 @@ class WebUSB:
) -> None: ) -> None:
""" """
""" """
def iface_num(self) -> int: def iface_num(self) -> int:
""" """
Returns the configured number of this interface. Returns the configured number of this interface.
""" """
def write(self, msg: bytes) -> int: def write(self, msg: bytes) -> int:
""" """
Sends message using USB WebUSB (device) or UDP (emulator). Sends message using USB WebUSB (device) or UDP (emulator).
@ -193,6 +154,7 @@ class WebUSB:
from . import fatfs, sdcard from . import fatfs, sdcard
POLL_READ: int # wait until interface is readable and return read data POLL_READ: int # wait until interface is readable and return read data
POLL_WRITE: int # wait until interface is writable POLL_WRITE: int # wait until interface is writable
TOUCH: int # interface id of the touch events TOUCH: int # interface id of the touch events
TOUCH_START: int # event id of touch start event TOUCH_START: int # event id of touch start event
TOUCH_MOVE: int # event id of touch move event TOUCH_MOVE: int # event id of touch move event

@ -21,35 +21,21 @@ FR_TOO_MANY_OPEN_FILES: int # (18) Number of open files > FF_FS_LOCK
FR_INVALID_PARAMETER: int # (19) Given parameter is invalid FR_INVALID_PARAMETER: int # (19) Given parameter is invalid
# nonstandard value: # nonstandard value:
FR_NO_SPACE: int # (64) No space left on device FR_NO_SPACE: int # (64) No space left on device
# extmod/modtrezorio/modtrezorio-fatfs.h
class FatFSError(OSError): class FatFSError(OSError):
pass pass
# extmod/modtrezorio/modtrezorio-fatfs.h
class NotMounted(FatFSError): class NotMounted(FatFSError):
pass pass
# extmod/modtrezorio/modtrezorio-fatfs.h
class NoFilesystem(FatFSError): class NoFilesystem(FatFSError):
pass pass
# extmod/modtrezorio/modtrezorio-fatfs.h
class FatFSFile: class FatFSFile:
""" """
Class encapsulating file Class encapsulating file
""" """
def __enter__(self) -> FatFSFile: def __enter__(self) -> FatFSFile:
""" """
Return an open file object Return an open file object
""" """
from types import TracebackType from types import TracebackType
def __exit__( def __exit__(
self, type: type[BaseException] | None, self, type: type[BaseException] | None,
value: BaseException | None, value: BaseException | None,
@ -58,121 +44,78 @@ class FatFSFile:
""" """
Close an open file object Close an open file object
""" """
def close(self) -> None: def close(self) -> None:
""" """
Close an open file object Close an open file object
""" """
def read(self, data: bytearray) -> int: def read(self, data: bytearray) -> int:
""" """
Read data from the file Read data from the file
""" """
def write(self, data: bytes | bytearray) -> int: def write(self, data: bytes | bytearray) -> int:
""" """
Write data to the file Write data to the file
""" """
def seek(self, offset: int) -> None: def seek(self, offset: int) -> None:
""" """
Move file pointer of the file object Move file pointer of the file object
""" """
def truncate(self) -> None: def truncate(self) -> None:
""" """
Truncate the file Truncate the file
""" """
def sync(self) -> None: def sync(self) -> None:
""" """
Flush cached data of the writing file Flush cached data of the writing file
""" """
# extmod/modtrezorio/modtrezorio-fatfs.h
class FatFSDir(Iterator[tuple[int, str, str]]): class FatFSDir(Iterator[tuple[int, str, str]]):
""" """
Class encapsulating directory Class encapsulating directory
""" """
def __next__(self) -> tuple[int, str, str]: def __next__(self) -> tuple[int, str, str]:
""" """
Read an entry in the directory Read an entry in the directory
""" """
# extmod/modtrezorio/modtrezorio-fatfs.h
def open(path: str, flags: str) -> FatFSFile: def open(path: str, flags: str) -> FatFSFile:
""" """
Open or create a file Open or create a file
""" """
# extmod/modtrezorio/modtrezorio-fatfs.h
def listdir(path: str) -> FatFSDir: def listdir(path: str) -> FatFSDir:
""" """
List a directory (return generator) List a directory (return generator)
""" """
# extmod/modtrezorio/modtrezorio-fatfs.h
def mkdir(path: str, exist_ok: bool=False) -> None: def mkdir(path: str, exist_ok: bool=False) -> None:
""" """
Create a sub directory Create a sub directory
""" """
# extmod/modtrezorio/modtrezorio-fatfs.h
def unlink(path: str) -> None: def unlink(path: str) -> None:
""" """
Delete an existing file or directory Delete an existing file or directory
""" """
# extmod/modtrezorio/modtrezorio-fatfs.h
def stat(path: str) -> tuple[int, str, str]: def stat(path: str) -> tuple[int, str, str]:
""" """
Get file status Get file status
""" """
# extmod/modtrezorio/modtrezorio-fatfs.h
def rename(oldpath: str, newpath: str) -> None: def rename(oldpath: str, newpath: str) -> None:
""" """
Rename/Move a file or directory Rename/Move a file or directory
""" """
# extmod/modtrezorio/modtrezorio-fatfs.h
def mount() -> None: def mount() -> None:
""" """
Mount the SD card filesystem. Mount the SD card filesystem.
""" """
# extmod/modtrezorio/modtrezorio-fatfs.h
def unmount() -> None: def unmount() -> None:
""" """
Unmount the SD card filesystem. Unmount the SD card filesystem.
""" """
# extmod/modtrezorio/modtrezorio-fatfs.h
def is_mounted() -> bool: def is_mounted() -> bool:
""" """
Check if the filesystem is mounted. Check if the filesystem is mounted.
""" """
# extmod/modtrezorio/modtrezorio-fatfs.h
def mkfs() -> None: def mkfs() -> None:
""" """
Create a FAT volume on the SD card, Create a FAT volume on the SD card,
""" """
# extmod/modtrezorio/modtrezorio-fatfs.h
def setlabel(label: str) -> None: def setlabel(label: str) -> None:
""" """
Set volume label Set volume label

@ -1,47 +1,29 @@
from typing import * from typing import *
BLOCK_SIZE: int # size of SD card block BLOCK_SIZE: int # size of SD card block
# extmod/modtrezorio/modtrezorio-sdcard.h
def is_present() -> bool: def is_present() -> bool:
""" """
Returns True if SD card is detected, False otherwise. Returns True if SD card is detected, False otherwise.
""" """
# extmod/modtrezorio/modtrezorio-sdcard.h
def power_on() -> None: def power_on() -> None:
""" """
Power on the SD card interface. Power on the SD card interface.
Raises OSError if the SD card cannot be powered on, e.g., when there Raises OSError if the SD card cannot be powered on, e.g., when there
is no SD card inserted. is no SD card inserted.
""" """
# extmod/modtrezorio/modtrezorio-sdcard.h
def power_off() -> None: def power_off() -> None:
""" """
Power off the SD card interface. Power off the SD card interface.
""" """
# extmod/modtrezorio/modtrezorio-sdcard.h
def capacity() -> int: def capacity() -> int:
""" """
Returns capacity of the SD card in bytes, or zero if not present. Returns capacity of the SD card in bytes, or zero if not present.
""" """
# extmod/modtrezorio/modtrezorio-sdcard.h
def read(block_num: int, buf: bytearray) -> None: def read(block_num: int, buf: bytearray) -> None:
""" """
Reads blocks starting with block_num from the SD card into buf. Reads blocks starting with block_num from the SD card into buf.
Number of bytes read is length of buf rounded down to multiply of Number of bytes read is length of buf rounded down to multiply of
SDCARD_BLOCK_SIZE. Returns True if in case of success, False otherwise. SDCARD_BLOCK_SIZE. Returns True if in case of success, False otherwise.
""" """
# extmod/modtrezorio/modtrezorio-sdcard.h
def write(block_num: int, buf: bytes) -> None: def write(block_num: int, buf: bytes) -> None:
""" """
Writes blocks starting with block_num from buf to the SD card. Writes blocks starting with block_num from buf to the SD card.

@ -1,39 +1,33 @@
from typing import * from typing import *
# extmod/modtrezorui/modtrezorui-display.h
class Display: class Display:
""" """
Provide access to device display. Provide access to device display.
""" """
WIDTH: int # display width in pixels
HEIGHT: int # display height in pixels WIDTH: int # display width in pixels
FONT_MONO: int # id of monospace font HEIGHT: int # display height in pixels
FONT_NORMAL: int # id of normal-width font FONT_MONO: int # id of monospace font
FONT_BOLD: int # id of bold-width font FONT_NORMAL: int # id of normal-width font
FONT_DEMIBOLD: int # id of demibold font FONT_BOLD: int # id of bold-width font
FONT_DEMIBOLD: int # id of demibold font
def __init__(self) -> None: def __init__(self) -> None:
""" """
Initialize the display. Initialize the display.
""" """
def clear(self) -> None: def clear(self) -> None:
""" """
Clear display with black color. Clear display with black color.
""" """
def refresh(self) -> None: def refresh(self) -> None:
""" """
Refresh display (update screen). Refresh display (update screen).
""" """
def bar(self, x: int, y: int, w: int, h: int, color: int) -> None: def bar(self, x: int, y: int, w: int, h: int, color: int) -> None:
""" """
Renders a bar at position (x,y = upper left corner) with width w and Renders a bar at position (x,y = upper left corner) with width w and
height h of color color. height h of color color.
""" """
def orientation(self, degrees: int | None = None) -> int: def orientation(self, degrees: int | None = None) -> int:
""" """
Sets display orientation to 0, 90, 180 or 270 degrees. Sets display orientation to 0, 90, 180 or 270 degrees.
@ -41,18 +35,15 @@ class Display:
Call without the degrees parameter to just perform the read of the Call without the degrees parameter to just perform the read of the
value. value.
""" """
def backlight(self, val: int | None = None) -> int: def backlight(self, val: int | None = None) -> int:
""" """
Sets backlight intensity to the value specified in val. Sets backlight intensity to the value specified in val.
Call without the val parameter to just perform the read of the value. Call without the val parameter to just perform the read of the value.
""" """
def save(self, prefix: str) -> None: def save(self, prefix: str) -> None:
""" """
Saves current display contents to PNG file with given prefix. Saves current display contents to PNG file with given prefix.
""" """
def clear_save(self) -> None: def clear_save(self) -> None:
""" """
Clears buffers in display saving. Clears buffers in display saving.

@ -1,122 +1,4 @@
from typing import * from typing import *
CONFIRMED: object
CANCELLED: object
INFO: object
# rust/src/ui/model_tr/layout.rs
def disable_animation(disable: bool) -> None:
"""Disable animations, debug builds only."""
# rust/src/ui/model_tr/layout.rs
def toif_info(data: bytes) -> tuple[int, int, bool]:
"""Get TOIF image dimensions and format (width: int, height: int, is_grayscale: bool)."""
# rust/src/ui/model_tr/layout.rs
def confirm_action(
*,
title: str,
action: str | None,
description: str | None,
verb: str = "CONFIRM",
verb_cancel: str | None = None,
hold: bool = False,
hold_danger: bool = False, # unused on TR
reverse: bool = False,
) -> object:
"""Confirm action."""
# rust/src/ui/model_tr/layout.rs
def confirm_blob(
*,
title: str,
data: str | bytes,
description: str | None,
extra: str | None,
verb: str = "CONFIRM",
verb_cancel: str | None = None,
hold: bool = False,
) -> object:
"""Confirm byte sequence data."""
# rust/src/ui/model_tr/layout.rs
def confirm_address(
*,
title: str,
data: str,
description: str | None, # unused on TR
extra: str | None, # unused on TR
) -> object:
"""Confirm address."""
# rust/src/ui/model_tr/layout.rs
def confirm_properties(
*,
title: str,
items: list[tuple[str | None, str | bytes | None, bool]],
hold: bool = False,
) -> object:
"""Confirm list of key-value pairs. The third component in the tuple should be True if
the value is to be rendered as binary with monospace font, False otherwise.
This only concerns the text style, you need to decode the value to UTF-8 in python."""
# rust/src/ui/model_tr/layout.rs
def confirm_reset_device(
*,
title: str,
button: str,
) -> object:
"""Confirm TOS before device setup."""
# rust/src/ui/model_tr/layout.rs
def show_address_details(
*,
address: str,
case_sensitive: bool,
account: str | None,
path: str | None,
xpubs: list[tuple[str, str]],
) -> object:
"""Show address details - QR code, account, path, cosigner xpubs."""
# rust/src/ui/model_tr/layout.rs
def confirm_value(
*,
title: str,
description: str,
value: str,
verb: str | None = None,
hold: bool = False,
) -> object:
"""Confirm value."""
# rust/src/ui/model_tr/layout.rs
def confirm_joint_total(
*,
spending_amount: str,
total_amount: str,
) -> object:
"""Confirm total if there are external inputs."""
# rust/src/ui/model_tr/layout.rs
def confirm_modify_output(
*,
address: str,
sign: int,
amount_change: str,
amount_new: str,
) -> object:
"""Decrease or increase amount for given address."""
# rust/src/ui/model_tr/layout.rs # rust/src/ui/model_tr/layout.rs
@ -368,25 +250,25 @@ def show_lockscreen(
def draw_welcome_screen() -> None: def draw_welcome_screen() -> None:
"""Show logo icon with the model name at the bottom and return.""" """Show logo icon with the model name at the bottom and return."""
CONFIRMED: object CONFIRMED: object
# rust/src/ui/model_tt/layout.rs
CANCELLED: object CANCELLED: object
INFO: object
# rust/src/ui/model_tt/layout.rs
INFO: object
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def disable_animation(disable: bool) -> None: def disable_animation(disable: bool) -> None:
"""Disable animations, debug builds only.""" """Disable animations, debug builds only."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def jpeg_info(data: bytes) -> tuple[int, int, int]: def jpeg_info(data: bytes) -> tuple[int, int, int]:
"""Get JPEG image dimensions (width: int, height: int, mcu_height: int).""" """Get JPEG image dimensions (width: int, height: int, mcu_height: int)."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def jpeg_test(data: bytes) -> bool: def jpeg_test(data: bytes) -> bool:
"""Test JPEG image.""" """Test JPEG image."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_action( def confirm_action(
*, *,
@ -401,7 +283,6 @@ def confirm_action(
) -> object: ) -> object:
"""Confirm action.""" """Confirm action."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_emphasized( def confirm_emphasized(
*, *,
@ -412,7 +293,6 @@ def confirm_emphasized(
"""Confirm formatted text that has been pre-split in python. For tuples """Confirm formatted text that has been pre-split in python. For tuples
the first component is a bool indicating whether this part is emphasized.""" the first component is a bool indicating whether this part is emphasized."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_homescreen( def confirm_homescreen(
*, *,
@ -421,7 +301,6 @@ def confirm_homescreen(
) -> object: ) -> object:
"""Confirm homescreen.""" """Confirm homescreen."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_blob( def confirm_blob(
*, *,
@ -435,7 +314,6 @@ def confirm_blob(
) -> object: ) -> object:
"""Confirm byte sequence data.""" """Confirm byte sequence data."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_address( def confirm_address(
*, *,
@ -447,7 +325,6 @@ def confirm_address(
"""Confirm address. Similar to `confirm_blob` but has corner info button """Confirm address. Similar to `confirm_blob` but has corner info button
and allows left swipe which does the same thing as the button.""" and allows left swipe which does the same thing as the button."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_properties( def confirm_properties(
*, *,
@ -458,7 +335,6 @@ def confirm_properties(
"""Confirm list of key-value pairs. The third component in the tuple should be True if """Confirm list of key-value pairs. The third component in the tuple should be True if
the value is to be rendered as binary with monospace font, False otherwise.""" the value is to be rendered as binary with monospace font, False otherwise."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_reset_device( def confirm_reset_device(
*, *,
@ -467,7 +343,6 @@ def confirm_reset_device(
) -> object: ) -> object:
"""Confirm TOS before device setup.""" """Confirm TOS before device setup."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_address_details( def show_address_details(
*, *,
@ -479,7 +354,6 @@ def show_address_details(
) -> object: ) -> object:
"""Show address details - QR code, account, path, cosigner xpubs.""" """Show address details - QR code, account, path, cosigner xpubs."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_spending_details( def show_spending_details(
*, *,
@ -490,7 +364,6 @@ def show_spending_details(
) -> object: ) -> object:
"""Show metadata when for outgoing transaction.""" """Show metadata when for outgoing transaction."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_value( def confirm_value(
*, *,
@ -505,7 +378,6 @@ def confirm_value(
) -> object: ) -> object:
"""Confirm value. Merge of confirm_total and confirm_output.""" """Confirm value. Merge of confirm_total and confirm_output."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_total( def confirm_total(
*, *,
@ -515,7 +387,6 @@ def confirm_total(
) -> object: ) -> object:
"""Transaction summary. Always hold to confirm.""" """Transaction summary. Always hold to confirm."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_modify_output( def confirm_modify_output(
*, *,
@ -526,7 +397,6 @@ def confirm_modify_output(
) -> object: ) -> object:
"""Decrease or increase amount for given address.""" """Decrease or increase amount for given address."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_modify_fee( def confirm_modify_fee(
*, *,
@ -538,7 +408,6 @@ def confirm_modify_fee(
) -> object: ) -> object:
"""Decrease or increase transaction fee.""" """Decrease or increase transaction fee."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_fido( def confirm_fido(
*, *,
@ -548,10 +417,10 @@ def confirm_fido(
accounts: list[str | None], accounts: list[str | None],
) -> int | object: ) -> int | object:
"""FIDO confirmation. """FIDO confirmation.
Returns page index in case of confirmation and CANCELLED otherwise. Returns page index in case of confirmation and CANCELLED otherwise.
""" """
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_error( def show_error(
*, *,
@ -563,7 +432,6 @@ def show_error(
) -> object: ) -> object:
"""Error modal. No buttons shown when `button` is empty string.""" """Error modal. No buttons shown when `button` is empty string."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_warning( def show_warning(
*, *,
@ -575,7 +443,6 @@ def show_warning(
) -> object: ) -> object:
"""Warning modal. No buttons shown when `button` is empty string.""" """Warning modal. No buttons shown when `button` is empty string."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_success( def show_success(
*, *,
@ -587,7 +454,6 @@ def show_success(
) -> object: ) -> object:
"""Success modal. No buttons shown when `button` is empty string.""" """Success modal. No buttons shown when `button` is empty string."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_info( def show_info(
*, *,
@ -599,12 +465,10 @@ def show_info(
) -> object: ) -> object:
"""Info modal. No buttons shown when `button` is empty string.""" """Info modal. No buttons shown when `button` is empty string."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_mismatch() -> object: def show_mismatch() -> object:
"""Warning modal, receiving address mismatch.""" """Warning modal, receiving address mismatch."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_simple( def show_simple(
*, *,
@ -614,7 +478,6 @@ def show_simple(
) -> object: ) -> object:
"""Simple dialog with text and one button.""" """Simple dialog with text and one button."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_with_info( def confirm_with_info(
*, *,
@ -626,7 +489,6 @@ def confirm_with_info(
"""Confirm given items but with third button. Always single page """Confirm given items but with third button. Always single page
without scrolling.""" without scrolling."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_more( def confirm_more(
*, *,
@ -637,7 +499,6 @@ def confirm_more(
"""Confirm long content with the possibility to go back from any page. """Confirm long content with the possibility to go back from any page.
Meant to be used with confirm_with_info.""" Meant to be used with confirm_with_info."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_coinjoin( def confirm_coinjoin(
*, *,
@ -646,7 +507,6 @@ def confirm_coinjoin(
) -> object: ) -> object:
"""Confirm coinjoin authorization.""" """Confirm coinjoin authorization."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def request_pin( def request_pin(
*, *,
@ -657,7 +517,6 @@ def request_pin(
) -> str | object: ) -> str | object:
"""Request pin on device.""" """Request pin on device."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def request_passphrase( def request_passphrase(
*, *,
@ -666,7 +525,6 @@ def request_passphrase(
) -> str | object: ) -> str | object:
"""Passphrase input keyboard.""" """Passphrase input keyboard."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def request_bip39( def request_bip39(
*, *,
@ -674,7 +532,6 @@ def request_bip39(
) -> str: ) -> str:
"""BIP39 word input keyboard.""" """BIP39 word input keyboard."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def request_slip39( def request_slip39(
*, *,
@ -682,7 +539,6 @@ def request_slip39(
) -> str: ) -> str:
"""SLIP39 word input keyboard.""" """SLIP39 word input keyboard."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def select_word( def select_word(
*, *,
@ -693,7 +549,6 @@ def select_word(
"""Select mnemonic word from three possibilities - seed check after backup. The """Select mnemonic word from three possibilities - seed check after backup. The
iterable must be of exact size. Returns index in range `0..3`.""" iterable must be of exact size. Returns index in range `0..3`."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_share_words( def show_share_words(
*, *,
@ -702,7 +557,6 @@ def show_share_words(
) -> object: ) -> object:
"""Show mnemonic for backup. Expects the words pre-divided into individual pages.""" """Show mnemonic for backup. Expects the words pre-divided into individual pages."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def request_number( def request_number(
*, *,
@ -714,7 +568,6 @@ def request_number(
) -> object: ) -> object:
"""Number input with + and - buttons, description, and info button.""" """Number input with + and - buttons, description, and info button."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_checklist( def show_checklist(
*, *,
@ -726,7 +579,6 @@ def show_checklist(
"""Checklist of backup steps. Active index is highlighted, previous items have check """Checklist of backup steps. Active index is highlighted, previous items have check
mark next to them.""" mark next to them."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def confirm_recovery( def confirm_recovery(
*, *,
@ -738,7 +590,6 @@ def confirm_recovery(
) -> object: ) -> object:
"""Device recovery homescreen.""" """Device recovery homescreen."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def select_word_count( def select_word_count(
*, *,
@ -746,7 +597,6 @@ def select_word_count(
) -> int | str: # TT returns int ) -> int | str: # TT returns int
"""Select mnemonic word count from (12, 18, 20, 24, 33).""" """Select mnemonic word count from (12, 18, 20, 24, 33)."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_group_share_success( def show_group_share_success(
*, *,
@ -754,7 +604,6 @@ def show_group_share_success(
) -> int: ) -> int:
"""Shown after successfully finishing a group.""" """Shown after successfully finishing a group."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_remaining_shares( def show_remaining_shares(
*, *,
@ -762,7 +611,6 @@ def show_remaining_shares(
) -> int: ) -> int:
"""Shows SLIP39 state after info button is pressed on `confirm_recovery`.""" """Shows SLIP39 state after info button is pressed on `confirm_recovery`."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_progress( def show_progress(
*, *,
@ -774,7 +622,6 @@ def show_progress(
description is determined at construction time. If you want multiline descriptions description is determined at construction time. If you want multiline descriptions
make sure the initial description has at least that amount of lines.""" make sure the initial description has at least that amount of lines."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_progress_coinjoin( def show_progress_coinjoin(
*, *,
@ -786,7 +633,6 @@ def show_progress_coinjoin(
"""Show progress loader for coinjoin. Returns CANCELLED after a specified time when """Show progress loader for coinjoin. Returns CANCELLED after a specified time when
time_ms timeout is passed.""" time_ms timeout is passed."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_homescreen( def show_homescreen(
*, *,
@ -798,7 +644,6 @@ def show_homescreen(
) -> CANCELLED: ) -> CANCELLED:
"""Idle homescreen.""" """Idle homescreen."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def show_lockscreen( def show_lockscreen(
*, *,
@ -808,7 +653,8 @@ def show_lockscreen(
) -> CANCELLED: ) -> CANCELLED:
"""Homescreen for locked device.""" """Homescreen for locked device."""
# rust/src/ui/model_tt/layout.rs # rust/src/ui/model_tt/layout.rs
def draw_welcome_screen() -> None: def draw_welcome_screen() -> None:
"""Show logo icon with the model name at the bottom and return.""" """Show logo icon with the model name at the bottom and return."""
# rust/src/ui/model_tt/layout.rs

@ -1,15 +1,9 @@
from typing import * from typing import *
# extmod/modtrezorutils/modtrezorutils-meminfo.h
def meminfo(filename: str) -> None: def meminfo(filename: str) -> None:
"""Dumps map of micropython GC arena to a file. """Dumps map of micropython GC arena to a file.
The JSON file can be decoded by analyze.py The JSON file can be decoded by analyze.py
Only available in the emulator. Only available in the emulator.
""" """
# extmod/modtrezorutils/modtrezorutils.c
def consteq(sec: bytes, pub: bytes) -> bool: def consteq(sec: bytes, pub: bytes) -> bool:
""" """
Compares the private information in `sec` with public, user-provided Compares the private information in `sec` with public, user-provided
@ -17,9 +11,6 @@ def consteq(sec: bytes, pub: bytes) -> bool:
of `pub`. Can access memory behind valid length of `sec`, caller is of `pub`. Can access memory behind valid length of `sec`, caller is
expected to avoid any invalid memory access. expected to avoid any invalid memory access.
""" """
# extmod/modtrezorutils/modtrezorutils.c
def memcpy( def memcpy(
dst: bytearray | memoryview, dst: bytearray | memoryview,
dst_ofs: int, dst_ofs: int,
@ -33,16 +24,10 @@ def memcpy(
copied bytes. If `n` is not specified, tries to copy copied bytes. If `n` is not specified, tries to copy
as much as possible. as much as possible.
""" """
# extmod/modtrezorutils/modtrezorutils.c
def halt(msg: str | None = None) -> None: def halt(msg: str | None = None) -> None:
""" """
Halts execution. Halts execution.
""" """
# extmod/modtrezorutils/modtrezorutils.c
def firmware_hash( def firmware_hash(
challenge: bytes | None = None, challenge: bytes | None = None,
callback: Callable[[int, int], None] | None = None, callback: Callable[[int, int], None] | None = None,
@ -51,30 +36,18 @@ def firmware_hash(
Computes the Blake2s hash of the firmware with an optional challenge as Computes the Blake2s hash of the firmware with an optional challenge as
the key. the key.
""" """
# extmod/modtrezorutils/modtrezorutils.c
def firmware_vendor() -> str: def firmware_vendor() -> str:
""" """
Returns the firmware vendor string from the vendor header. Returns the firmware vendor string from the vendor header.
""" """
# extmod/modtrezorutils/modtrezorutils.c
def unit_color() -> int | None: def unit_color() -> int | None:
""" """
Returns the color of the unit. Returns the color of the unit.
""" """
# extmod/modtrezorutils/modtrezorutils.c
def unit_btconly() -> bool | None: def unit_btconly() -> bool | None:
""" """
Returns True if the unit is BTConly. Returns True if the unit is BTConly.
""" """
# extmod/modtrezorutils/modtrezorutils.c
def reboot_to_bootloader() -> None: def reboot_to_bootloader() -> None:
""" """
Reboots to bootloader. Reboots to bootloader.

@ -1,4 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from __future__ import annotations
import os import os
import shutil import shutil
import subprocess import subprocess
@ -6,64 +8,74 @@ import sys
import tempfile import tempfile
from pathlib import Path from pathlib import Path
import typing as t
CORE_DIR = Path(__file__).resolve().parent.parent CORE_DIR = Path(__file__).resolve().parent.parent
EXTMOD_PATH = CORE_DIR / "embed" / "extmod" EXTMOD_PATH = CORE_DIR / "embed" / "extmod"
RUSTMOD_PATH = CORE_DIR / "embed" / "rust" / "src" RUSTMOD_PATH = CORE_DIR / "embed" / "rust" / "src"
MOCKS_PATH = CORE_DIR / "mocks" / "generated" MOCKS_PATH = CORE_DIR / "mocks" / "generated"
COMMENT_PREFIX = "/// " COMMENT_PREFIX = "///"
COMMENT_PREFIX_RS = "//#"
current_indent = 0 in_class = False
current_class = None
current_method = None
current_package = None current_package = None
current_method_is_overload = False current_method_is_overload = False
def process_file(lines_iter: t.Iterator[str], block_prefix: str) -> t.Iterator[tuple[str, str]]:
in_class = False
package = None
def process_block() -> t.Iterator[tuple[str, str]]:
"""Process a single block of comment-prefixed lines."""
block_indent = "" if not in_class else " " * 4
nonlocal package
nonlocal in_class
for line in lines_iter:
line = line.strip()
if not line.startswith(block_prefix):
return
line = line[len(block_prefix) + 1 :].rstrip()
if line.startswith("package: "):
package = line[len("package: ") :].strip()
continue
def split_to_parts(line, mod_desc=None): if package is None:
global current_indent raise ValueError("No package set (use 'package: <name>')")
global current_class
global current_method if not in_class:
yield package, f"\n# {mod_desc}"
for line in block:
if not line.strip():
continue
yield package, line
def split_to_parts(line):
global in_class
global current_package global current_package
global current_method_is_overload global current_method_is_overload
if line.startswith("package: "): if line.startswith("package: "):
current_package = line[9:].strip() current_package = line[len("package: ") :].strip()
return return
if current_package is None:
raise ValueError("No package set (use 'package: <name>')")
if line.startswith("mock:global"): if line.startswith("mock:global"):
current_indent = 0 in_class = False
current_class = None
return return
if line == "@overload\n": indent = "" if not in_class else " " * 4
current_method_is_overload = True yield (current_package, (indent + line).rstrip())
return
if line.startswith("class "): if line.startswith("class "):
current_class = line[6:].split("(")[0].strip(":") in_class = True
current_indent = 0
yield (current_package, "\n\n")
yield (current_package, "# " + mod_desc + "\n")
elif line.startswith("def "):
current_method = line[4:].split("(")[0]
if current_class is None:
yield (current_package, "\n\n")
yield (current_package, "# " + mod_desc + "\n")
else:
yield (current_package, "\n")
current_indent = 4
if current_method_is_overload:
yield (current_package, current_indent * " " + "@overload\n")
current_method_is_overload = False
line = current_indent * " " + line
yield (current_package, line)
def store_to_file(dest, parts): def store_to_file(dest, parts):
@ -76,8 +88,8 @@ def store_to_file(dest, parts):
dirpath.mkdir(parents=True, exist_ok=True) dirpath.mkdir(parents=True, exist_ok=True)
if (dest / package).is_dir(): if (dest / package).is_dir():
if not line.strip(): # if not line.strip():
continue # continue
print(f"Package exists: {package}") print(f"Package exists: {package}")
print(f"You should set 'package:' in {line.strip()}") print(f"You should set 'package:' in {line.strip()}")
sys.exit(1) sys.exit(1)
@ -86,12 +98,12 @@ def store_to_file(dest, parts):
filepath.write_text("from typing import *\n") filepath.write_text("from typing import *\n")
with open(filepath, "a") as f: with open(filepath, "a") as f:
f.write(line) f.write(line + "\n")
def build_module(mod_file, dest): def build_module(mod_file, dest):
global current_indent global current_indent
global current_class global in_class
global current_package global current_package
assert mod_file.name.startswith("mod") assert mod_file.name.startswith("mod")
@ -100,47 +112,51 @@ def build_module(mod_file, dest):
name = mod_file.name[3:-2] name = mod_file.name[3:-2]
current_indent = 0 current_indent = 0
current_class = None in_class = None
current_package = name.split("-")[0] current_package = name.split("-")[0]
mod_desc = str(mod_file.relative_to(CORE_DIR / "embed")) mod_desc = str(mod_file.relative_to(CORE_DIR / "embed"))
for l in open(mod_file): for l in open(mod_file):
l = l.strip()
if not l.startswith(COMMENT_PREFIX): if not l.startswith(COMMENT_PREFIX):
continue continue
l = l[len(COMMENT_PREFIX) :] # .strip() l = l[len(COMMENT_PREFIX) + 1 :] # account for space after ///
store_to_file(dest, split_to_parts(l, mod_desc)) store_to_file(dest, split_to_parts(l, mod_desc))
def build_rsmodule(mod_file, dest): def build_rsmodule(mod_file):
global current_indent global current_indent
global current_class global in_class
global current_package global current_package
assert mod_file.suffix == ".rs" assert mod_file.suffix == ".rs"
start_prefix = "pub static mp_module_"
comment_prefix = f" {COMMENT_PREFIX}"
in_module = False
current_indent = 0 current_indent = 0
current_class = None in_class = False
current_package = None
mod_desc = str(mod_file.relative_to(CORE_DIR / "embed")) mod_desc = str(mod_file.relative_to(CORE_DIR / "embed"))
yield_sep = False
for l in open(mod_file): for l in open(mod_file):
if l.startswith(start_prefix): l = l.strip()
in_module = True if not l.startswith(COMMENT_PREFIX_RS):
current_package = l[len(start_prefix) : ].split(":")[0] if yield_sep:
elif l.startswith("}"): if in_class:
in_module = False yield current_package, ""
else:
if not in_module: yield current_package, f"\n# {mod_desc}"
continue yield_sep = False
if not l.startswith(comment_prefix):
continue continue
l = l[len(comment_prefix) :] l = l[len(COMMENT_PREFIX_RS) + 1 :] # account for space after //#
store_to_file(dest, split_to_parts(l, mod_desc)) try:
yield from split_to_parts(l, mod_desc)
yield_sep = True
except ValueError as e:
print(f"Error in {mod_file}: {e}")
print(f"Line: {l}")
sys.exit(1)
def place_symlinks(dest): def place_symlinks(dest):
@ -154,7 +170,7 @@ def build_directory(dest):
for modfile in sorted(EXTMOD_PATH.glob("**/mod*.[ch]")): for modfile in sorted(EXTMOD_PATH.glob("**/mod*.[ch]")):
build_module(modfile, dest) build_module(modfile, dest)
for modfile in sorted(RUSTMOD_PATH.glob("**/*.rs")): for modfile in sorted(RUSTMOD_PATH.glob("**/*.rs")):
build_rsmodule(modfile, dest) store_to_file(dest, build_rsmodule(modfile))
place_symlinks(dest) place_symlinks(dest)

Loading…
Cancel
Save