What changed, and why it matters
This commit adds a brand-new Rust SDK crate (trezor-app-sdk) for building third-party applications that run on Trezor hardware wallets. It is a feature addition: it provides the runtime, memory allocator, error handling, logging, and stable-ABI wrappers for crypto, UI, and host communication. There is no bug fix, no mention of any security issue, and no patch of existing vulnerable behavior.
No security action required. Treat as a normal feature addition. If reviewing for security, focus on the new stable-ABI boundary, allocator forwarding, and panic/abort paths in later reviews; this initial commit does not itself fix or introduce a known vulnerability.
Security signals we found
No strong security signals were identified.
Evidence from the diff
Commit 666a797 introduces sdk/crates/trezor-app-sdk, a no_std Rust library for Trezor ‘extapps’. It adds the app entry point (#[trezor_app_sdk::app]), a global allocator that forwards to Core’s heap, Result/Error types with optional debug context, wire/codec helpers, logging macros, UI/crypto/wire/syslog trait wrappers over a stabby-based stable ABI, host-side mocks for unit tests, and CI jobs for fmt/clippy/test/audit/vet. The diff is entirely new code; no existing code is modified except the SDK workflow file.
Changed components
sdk/crates/trezor-app-sdk (new crate).github/workflows/sdk.ymlInspect captured patch +6167 / −2
### .github/workflows/sdk.yml
@@ -3,9 +3,10 @@ name: SDK
# Release-gating checks for the `trezor-app-tool` crate
# (sdk/crates/trezor-app-tool), the build/test/format driver for modular Trezor
# apps (invoked from sdk/apps as `cargo app-tool <cmd>`, or via `xtask apps <cmd>`
-# from core/embed/xtask, which just spawns it), and the `trezor-app-build` crate
+# from core/embed/xtask, which just spawns it), the `trezor-app-build` crate
# (sdk/crates/trezor-app-build), the build-script helpers the apps use for
-# protobuf, translation and linker setup.
+# protobuf, translation and linker setup, and the `trezor-app-sdk` crate
+# (sdk/crates/trezor-app-sdk), the no_std runtime library the apps link against.
# See sdk/doc/development.md for background on their roles.
on:
@@ -49,6 +50,7 @@ jobs:
- uses: ./.github/actions/environment
- run: nix-shell --run "cd sdk/crates/trezor-app-tool && cargo fmt --check && cargo clippy --all-targets -- -D warnings && RUSTDOCFLAGS='-D warnings' cargo doc --no-deps"
- run: nix-shell --run "cd sdk/crates/trezor-app-build && cargo fmt --check && cargo clippy --all-targets -- -D warnings && RUSTDOCFLAGS='-D warnings' cargo doc --no-deps"
+ - run: nix-shell --run "cd sdk/crates/trezor-app-sdk && cargo fmt --check && cargo clippy --no-default-features && cargo clippy --all-features && cargo doc --no-deps --all-features"
test:
name: Unit tests
@@ -61,6 +63,7 @@ jobs:
- uses: ./.github/actions/environment
- run: nix-shell --run "cd sdk/crates/trezor-app-tool && cargo test"
- run: nix-shell --run "cd sdk/crates/trezor-app-build && cargo test"
+ - run: nix-shell --run "cd sdk/crates/trezor-app-sdk && cargo test --features test"
deps_check:
name: Dependency check (audit, vet)
@@ -73,3 +76,4 @@ jobs:
- uses: ./.github/actions/environment
- run: nix-shell --run "cd sdk/crates/trezor-app-tool && cargo audit && cargo vet --locked"
- run: nix-shell --run "cd sdk/crates/trezor-app-build && cargo audit && cargo vet --locked"
+ - run: nix-shell --run "cd sdk/crates/trezor-app-sdk && cargo audit && cargo vet --locked"
### sdk/crates/trezor-app-sdk/.gitignore
@@ -0,0 +1,2 @@
+/target
+Cargo.lock
### sdk/crates/trezor-app-sdk/Cargo.toml
@@ -0,0 +1,54 @@
+
+[package]
+name = "trezor-app-sdk"
+version = "0.1.0"
+edition = "2024"
+description = "no_std SDK for developing Trezor extapps in Rust"
+license = "GPL-3.0-only"
+exclude = ["supply-chain/"]
+
+[package.metadata.trezor]
+sdk-version = "0.1.0"
+
+[lib]
+crate-type = ["rlib"]
+
+[dependencies]
+rkyv = { version = "0.8", default-features = false }
+ufmt = "0.2.0"
+spin = "0.10.0"
+cty = "0.2.2"
+num_enum = { version = "0.7.5", default-features = false }
+mock_sha3 = { package = "sha3", version = "0.11", optional = true }
+mock_hmac_sha256 = { package = "hmac-sha256", version = "1.1", optional = true }
+mock_hmac_sha512 = { package = "hmac-sha512", version = "1.1", optional = true }
+stabby = { version = "72.1.8", default-features = false, features = [
+ "alloc-rs",
+], path = "../../../vendor/stabby/stabby" }
+
+[features]
+# --------------------------------------------------------------------------
+# Log level features
+# --------------------------------------------------------------------------
+log_level_error = []
+log_level_warn = []
+log_level_info = []
+log_level_debug = []
+
+debug = []
+
+app = ["rkyv/alloc", "rkyv/bytecheck"]
+app_runtime = []
+
+# Enables use of unstable (nightly-only) language/library features
+# (`core_intrinsics`, `lang_items`). Required for the default panic/abort
+# machinery under the `debug` feature. Disable on stable toolchains; the
+# affected code paths fall back to stable-compatible implementations.
+nightly = []
+
+default = ["app", "nightly"]
+
+# --------------------------------------------------------------------------
+# Selectable features
+# --------------------------------------------------------------------------
+test = ["app", "mock_sha3", "mock_hmac_sha256", "mock_hmac_sha512"]
### sdk/crates/trezor-app-sdk/README.md
@@ -0,0 +1,209 @@
+# trezor-app-sdk
+
+`trezor-app-sdk` is the `no_std` Rust library for writing Trezor apps:
+programs that Trezor Core loads and runs on the device in their own task.
+It gives an app access to Core's UI, crypto, host communication (wire) and
+logging over a stable, [`stabby`](https://crates.io/crates/stabby)-based ABI,
+and provides the app's runtime: the entry point, the global allocator and error
+handling.
+
+> ⚠️ Work in progress: the SDK is under active development, and its API can
+> change at any time.
+
+## Requirements
+
+- A nightly Rust toolchain. The app entry point uses `extern_item_impls`.
+- A `build.rs` that calls `trezor_app_build::link()` from the companion
+ `trezor-app-build` crate, which sets up the app's linker script.
+- The `trezor-app-tool` cargo subcommand (`cargo app-tool`) to build the app.
+ It compiles the app for the target device model and turns the ELF into the
+ image format Core loads.
+
+## A Minimal App
+
+`Cargo.toml` declares the SDK, the app's identity and resources, the
+features the build selects, and the two profiles `cargo app-tool` builds with:
+
+```toml
+cargo-features = ["panic-immediate-abort"]
+
+[package]
+name = "hello"
+version = "0.1.0"
+edition = "2024"
+
+[package.metadata.trezor]
+id = "hello.example.com"
+name = "Hello"
+vendor = "Example"
+stack-size = 16384
+heap-size = 32768
+app-ring = 2
+curves = ["secp256k1"]
+paths = ["m/44'/1'/account'/change/address_index/**"]
+
+[dependencies]
+trezor-app-sdk = "0.1"
+
+[build-dependencies]
+anyhow = "1"
+trezor-app-build = "0.1"
+
+[features]
+model_t3t1 = []
+model_t3w1 = []
+# one per language the app is translated to
+lang_en = []
+log_level_error = ["trezor-app-sdk/log_level_error"]
+log_level_warn = ["trezor-app-sdk/log_level_warn"]
+log_level_info = ["trezor-app-sdk/log_level_info"]
+log_level_debug = ["trezor-app-sdk/log_level_debug"]
+emulator = []
+debug = ["trezor-app-sdk/debug"]
+test = ["trezor-app-sdk/test"]
+dev_keys = []
+
+[workspace]
+
+[profile.debug-fw]
+inherits = "dev"
+split-debuginfo = "off"
+debug = 2
+strip = "none"
+panic = "abort"
+
+[profile.release-fw]
+inherits = "release"
+opt-level = "z"
+lto = "fat"
+codegen-units = 1
+split-debuginfo = "off"
+debug = 0
+debug-assertions = false
+overflow-checks = false
+incremental = false
+panic = "immediate-abort"
+```
+
+`build.rs`:
+
+```rust,ignore
+fn main() -> anyhow::Result<()> {
+ trezor_app_build::link()
+}
+```
+
+`src/main.rs`. Core starts the app for each host request; the app reads the
+request, answers it and returns:
+
+```rust,ignore
+#![cfg_attr(not(test), no_std)]
+#![cfg_attr(not(test), no_main)]
+
+extern crate alloc;
+
+use trezor_app_sdk::{Result, ResultExt, wire_receive};
+
+#[trezor_app_sdk::app]
+fn app() -> Result<()> {
+ let (id, data) = wire_receive().c()?;
+ handle(id, data.as_ref()).c()
+}
+```
+
+An app has exactly one `#[trezor_app_sdk::app]` function; a missing one is a
+compile error.
+
+## Talking to the Host
+
+The SDK does not pick a serializer. An app implements `WireDecode` and
+`WireEncode` for its message types on a codec type of its own, for example
+with [`prost`](https://crates.io/crates/prost):
+
+```rust,ignore
+use trezor_app_sdk::{Error, Result, WireDecode, WireEncode, wire_handler};
+
+struct ProstCodec;
+
+impl<T: prost::Message + Default> WireDecode<T> for ProstCodec {
+ fn decode(data: &[u8]) -> Result<T> {
+ T::decode(data).map_err(|_| Error::InvalidMessage)
+ }
+}
+
+impl<T: prost::Message> WireEncode<T> for ProstCodec {
+ fn encode(val: &T) -> alloc::vec::Vec<u8> {
+ val.encode_to_vec()
+ }
+}
+
+// `handle_sign_tx(data)` decodes a `SignTx`, calls `sign_tx` and sends its
+// result as `MessageType::TxSignature`, or sends the error it returned.
+wire_handler!(handle_sign_tx, ProstCodec, SignTx, MessageType::TxSignature, sign_tx);
+
+fn handle(id: u16, data: &[u8]) -> Result<()> {
+ match id {
+ x if x == MessageType::SignTx as u16 => handle_sign_tx(data),
+ _ => Err(Error::InvalidMessage),
+ }
+}
+```
+
+The wire functions at the crate root are:
+
+| Function | Purpose |
+| -------- | ------- |
+| `wire_receive` | Wait for the next message from the host |
+| `wire_send` | Send a message to the host |
+| `wire_call` | Send a message and wait for the host's answer, mid-flow |
+| `wire_error` | Send a failure (`FailureKind` and message) to the host; for an SDK `Error`, call `Error::send_to_host()` |
+| `wire_request` | Typed `wire_call`; pair request and response types with `wire_request_type!` |
+
+## Modules
+
+| Module | Contents |
+| ------ | -------- |
+| `ui` | Screens and user interaction: confirmations, warnings, progress, and more |
+| `crypto` | Key derivation and signing (done by Core), plus hashing, HMAC, Base58, signature verification and CoSi (done locally) |
+| `log` | The `error!`, `warn!`, `info!` and `debug!` macros |
+| `error` | The `Error` and `Result` types, and `ResultExt` for call-site context |
+| `util` | Small helpers, such as `Timeout` and `systick_ms` |
+| `structs`, `traits` | The types and interfaces shared with Core |
+| `mock` | Mock implementations of Core's services (`test` feature) |
+
+## Logging
+
+Values passed to the log macros must implement `ufmt::uDebug`; for a `String`,
+log `s.as_str()`:
+
+```rust,ignore
+use trezor_app_sdk::{debug, info};
+
+info!("Application started");
+debug!("Address: {}", address.as_str());
+```
+
+The log level is chosen at build time with one of the `log_level_*` features
+(`cargo app-tool build --log-level <level>` sets it). Each level includes the
+ones above it, and lower levels are compiled out. Without any of them, all log
+output is compiled out.
+
+## Features
+
+| Feature | Effect |
+| ------- | ------ |
+| `app` (default) | Everything an app needs. Without it, only `structs` and `traits` are available, for code that shares the ABI types with apps |
+| `nightly` (default) | Nightly-only language features used by the panic and abort machinery |
+| `log_level_error` / `_warn` / `_info` / `_debug` | Compile in log output up to that level |
+| `debug` | Error context chains via `ResultExt` and file/line panic messages, at the cost of binary size |
+| `test` | Mock implementations of Core's services, for host-side unit tests (implies `app`) |
+
+## Unit Tests
+
+With the `test` feature, the SDK runs on the host with mocked Core services.
+Call `trezor_app_sdk::mock::sdk_init()` at the start of a test that uses
+SDK functions backed by Core.
+
+## License
+
+GPL-3.0-only.
### sdk/crates/trezor-app-sdk/rustfmt.toml
@@ -0,0 +1,2 @@
+group_imports = "StdExternalCrate"
+imports_granularity = "Module"
### sdk/crates/trezor-app-sdk/src/app_runtime/allocator.rs
@@ -0,0 +1,44 @@
+use core::alloc::{GlobalAlloc, Layout};
+
+use crate::traits::allocator::{GlobalAllocatorV1Dyn as _, GlobalAllocatorV1Ref};
+
+// Under `test`, this crate is a normal `std` build running as one of many
+// independent unit tests in a shared process — most of them never call
+// `applet_main`/`mock::sdk_init` at all, so routing every allocation through
+// `get_api_or_die()` would panic on the very first allocation the test
+// harness itself makes. Let `std`'s default allocator handle test binaries.
+#[cfg(not(feature = "test"))]
+#[global_allocator]
+static REMOTE_ALLOCATOR: RedirAllocator = RedirAllocator;
+
+/// Global allocator that forwards every allocation to Core's allocator for
+/// this app's heap.
+pub struct RedirAllocator;
+
+impl RedirAllocator {
+ fn allocator(&self) -> GlobalAllocatorV1Ref<'_> {
+ super::get_api_or_die().allocator
+ }
+}
+
+unsafe impl GlobalAlloc for RedirAllocator {
+ unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
+ let remote = self.allocator();
+ unsafe { remote.alloc(layout.into()) }
+ }
+
+ unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
+ let remote = self.allocator();
+ unsafe { remote.dealloc(ptr, layout.into()) }
+ }
+
+ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
+ let remote = self.allocator();
+ unsafe { remote.alloc_zeroed(layout.into()) }
+ }
+
+ unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
+ let remote = self.allocator();
+ unsafe { remote.realloc(ptr, layout.into(), new_size) }
+ }
+}
### sdk/crates/trezor-app-sdk/src/app_runtime/mod.rs
@@ -0,0 +1,147 @@
+use stabby::str::Str;
+
+use crate::debug;
+use crate::traits::ApiVariant as ApiVersion;
+use crate::traits::crypto::StaticCryptoV1;
+use crate::traits::syslog::StaticSyslogV1;
+use crate::traits::trezor_v1::{TrezorApiV1Dyn as _, TrezorApiV1Struct};
+use crate::traits::ui::StaticUiV1;
+use crate::traits::wire::StaticWireV1;
+
+/// The global allocator, backed by the heap Core gives the app.
+pub mod allocator;
+
+static API: spin::Once<&'static TrezorApiV1Struct> = spin::Once::new();
+
+const API_VERSION: u32 = 1;
+
+/// The app's entry point, implemented by the app as
+/// `#[trezor_app_sdk::app] fn app() -> Result<()>`.
+#[cfg(not(feature = "test"))]
+#[eii]
+pub fn app() -> crate::error::Result<()>;
+
+/// Under `test`, a default so unit tests and doctests link without an app.
+#[cfg(feature = "test")]
+#[eii]
+pub fn app() -> crate::error::Result<()> {
+ panic!("App item called from test suite")
+}
+
+/// This app's entry point — but not the first thing to run on its task.
+///
+/// Core starts the task in `coreapp_app_entry` (`core/embed/api/src/lib.rs`)
+/// and passes this function to it. Before calling in here Core points its
+/// global allocator at this app's heap region and registers this app's
+/// `WireV1` inbox, sized from the `ipc-buffer-size` the app declared in its
+/// manifest. So the heap behind [`allocator::RedirAllocator`] is already live
+/// on entry and the wire is already usable; an app may allocate as soon as
+/// `API` below is populated — the very first statement.
+#[unsafe(no_mangle)]
+pub extern "C" fn applet_main(api_get: crate::traits::ApiGetter) -> core::ffi::c_int {
+ init(api_get);
+
+ match app() {
+ Ok(()) => system_exit(),
+ // a stop requested by Core is a normal exit
+ Err(e) if e.is_stopped() => system_exit(),
+ Err(e) => {
+ let mut error_buf = [0u8; 256];
+ let mut writer = crate::util::SliceWriter::new(&mut error_buf);
+ _ = ufmt::uwrite!(writer, "{}", e);
+ crate::error!("{}", writer.as_ref());
+ system_exit_error("Error", writer.as_ref(), "");
+ }
+ }
+}
+
+/// Stores the API Core hands to the app. Only the first call counts.
+pub(crate) fn init(api_get: crate::traits::ApiGetter) {
+ match api_get(API_VERSION) {
+ ApiVersion::V1(api) => {
+ API.call_once(|| api);
+ }
+ }
+
+ debug!(
+ "Applet main entry point called, API version: {}",
+ API_VERSION
+ );
+}
+
+pub(crate) fn get_api_or_die() -> &'static TrezorApiV1Struct {
+ API.get().expect("API not initialized")
+}
+
+pub(crate) fn systick_ms() -> u32 {
+ get_api_or_die().api.systick_ms()
+}
+
+pub(crate) fn sleep(timeout_ms: u32) {
+ get_api_or_die().api.sleep(timeout_ms);
+}
+
+pub(crate) fn try_get_syslog() -> Option<StaticSyslogV1> {
+ API.get().map(|api| api.syslog)
+}
+
+/// Local, no-IPC crypto vtable (hashing, signature verification, `base58*`) —
+/// see [`crate::traits::crypto::CryptoV1`].
+pub(crate) fn get_crypto_or_die() -> StaticCryptoV1 {
+ get_api_or_die().crypto
+}
+
+pub(crate) fn get_wire_or_die() -> StaticWireV1 {
+ get_api_or_die().wire
+}
+
+/// UI/progress vtable — see [`crate::traits::ui::UiV1`].
+pub(crate) fn get_ui_or_die() -> StaticUiV1 {
+ get_api_or_die().ui
+}
+
+/// Terminates the app normally.
+pub(crate) fn system_exit() -> ! {
+ get_api_or_die().api.system_exit()
+}
+
+/// Terminates the app, showing an error screen with `title`/`message`/`footer`.
+pub(crate) fn system_exit_error(title: &str, message: &str, footer: &str) -> ! {
+ get_api_or_die()
+ .api
+ .system_exit_error(Str::from(title), Str::from(message), Str::from(footer))
+}
+
+/// Terminates the app after an unrecoverable (e.g. panic) failure.
+pub(crate) fn system_exit_fatal(message: &str, file: &str, line: u32) -> ! {
+ get_api_or_die()
+ .api
+ .system_exit_fatal(Str::from(message), Str::from(file), line)
+}
+
+#[cfg(all(feature = "debug", not(feature = "test"), feature = "nightly"))]
+#[lang = "eh_personality"]
+fn eh_personality() -> ! {
+ loop {}
+}
+
+#[cfg(all(feature = "debug", not(feature = "test"), feature = "nightly"))]
+#[unsafe(no_mangle)]
+unsafe extern "C" fn _Unwind_Resume() {
+ unsafe { core::hint::unreachable_unchecked() };
+}
+
+#[cfg(all(feature = "debug", not(feature = "test")))]
+#[panic_handler]
+fn panic_handler(info: &core::panic::PanicInfo<'_>) -> ! {
+ let msg = info.message().as_str().unwrap_or("PANIC");
+ let (file, line) = info
+ .location()
+ .map(|loc| {
+ let file = loc.file();
+ let file_short = file.rsplit('/').next().unwrap_or(file);
+ (file_short, loc.line())
+ })
+ .unwrap_or(("<unknown>", 0));
+ system_exit_fatal(msg, file, line);
+}
### sdk/crates/trezor-app-sdk/src/codec.rs
@@ -0,0 +1,177 @@
+//! Serializer-agnostic message encoding on top of the [`crate::wire`]
+//! transport: [`WireDecode`]/[`WireEncode`], [`wire_request`] and the
+//! `wire_handler!`/`wire_request_type!` macros.
+//!
+//! This module has no dependency on any particular message encoding (e.g.
+//! prost). Apps select their serializer by implementing [`WireDecode`] and
+//! [`WireEncode`] for a codec marker type of their own, and declare each
+//! request's response type and wire id once via the `wire_request_type!`
+//! macro instead of repeating both at every call site.
+
+use alloc::vec::Vec;
+
+use crate::wire::wire_call;
+use crate::{Error, Result};
+
+/// Decodes a wire message body into `T` using the implementing codec.
+pub trait WireDecode<T> {
+ /// Decodes `data` into a `T`.
+ fn decode(data: &[u8]) -> Result<T>;
+}
+
+/// Encodes `T` into a wire message body using the implementing codec.
+pub trait WireEncode<T> {
+ /// Encodes `val` into a message body.
+ fn encode(val: &T) -> Vec<u8>;
+}
+
+/// Associates a request type with its response type and wire id.
+///
+/// Implemented once per request type via the `wire_request_type!` macro, so
+/// [`wire_request`] call sites don't need to repeat the response type
+/// annotation and the message id in lockstep — a common source of copy-paste
+/// mismatches when they're passed as two independent arguments/annotations.
+pub trait WireRequest {
+ /// The type the host answers this request with.
+ type Response;
+ /// The wire message id of this request.
+ const ID: u16;
+ /// The wire message id the host answers with.
+ const RESPONSE_ID: u16;
+}
+
+/// Sends `req` to the host using `Codec` and decodes the response.
+///
+/// `Req`'s response type and wire id come from its [`WireRequest`] impl
+/// rather than being repeated at the call site.
+pub fn wire_request<Codec, Req>(req: &Req) -> Result<Req::Response>
+where
+ Req: WireRequest,
+ Codec: WireEncode<Req> + WireDecode<Req::Response>,
+{
+ let req_bytes = Codec::encode(req);
+ let (id, resp_bytes) = wire_call(Req::ID, &req_bytes)?;
+ decode_response::<Codec, Req>(id, resp_bytes.as_ref())
+}
+
+/// Decodes the host's answer to `Req`. Another message id is rejected before
+/// decoding, since a lenient codec (e.g. protobuf) could accept its bytes.
+fn decode_response<Codec, Req>(id: u16, data: &[u8]) -> Result<Req::Response>
+where
+ Req: WireRequest,
+ Codec: WireDecode<Req::Response>,
+{
+ if id != Req::RESPONSE_ID {
+ crate::warn!(
+ "Unexpected response id {}, expected {}",
+ id,
+ Req::RESPONSE_ID
+ );
+ return Err(Error::InvalidMessage);
+ }
+ Codec::decode(data)
+}
+
+/// Macro to generate handler functions.
+///
+/// `$codec` selects the wire serializer: a type implementing
+/// [`WireDecode<$request_type>`](crate::WireDecode) and `WireEncode` for
+/// whatever the handler returns. Apps own this type, so the SDK itself has
+/// no dependency on any particular serializer.
+#[macro_export]
+macro_rules! wire_handler {
+ ($handler_name:ident, $codec:ty, $request_type:ty, $response_msg:expr, $handler_fn:path) => {
+ #[inline(never)]
+ fn $handler_name(request_data: &[u8]) -> $crate::Result<()> {
+ // a malformed request is the host's error, the app keeps running
+ let decoded = <$codec as $crate::WireDecode<$request_type>>::decode(request_data);
+ let request = match $crate::ResultExt::c(decoded) {
+ Ok(request) => request,
+ Err(e) => return $crate::Error::send_to_host(&e),
+ };
+
+ match $handler_fn(request) {
+ Ok(resp) => {
+ let response_bytes = <$codec as $crate::WireEncode<_>>::encode(&resp);
+ $crate::wire_send($response_msg as u16, &response_bytes)
+ }
+ // a stop never reaches the host, the app's entry point exits
+ Err(e) if e.is_stopped() => Err(e),
+ Err(e) => $crate::Error::send_to_host(&e),
+ }
+ }
+ };
+}
+
+/// Declares `$req`'s response type, its wire id and the response's wire id
+/// for [`$crate::wire_request`], so callers don't have to repeat them at every
+/// call site.
+#[macro_export]
+macro_rules! wire_request_type {
+ ($req:ty => $resp:ty, $id:expr, $response_id:expr) => {
+ impl $crate::WireRequest for $req {
+ type Response = $resp;
+ const ID: u16 = $id as u16;
+ const RESPONSE_ID: u16 = $response_id as u16;
+ }
+ };
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ struct Ping;
+ wire_request_type!(Ping => u8, 1, 2);
+
+ /// Decodes the first byte, accepting any message.
+ struct FirstByte;
+
+ impl WireDecode<u8> for FirstByte {
+ fn decode(data: &[u8]) -> Result<u8> {
+ data.first().copied().ok_or(Error::InvalidMessage)
+ }
+ }
+
+ impl WireEncode<u8> for FirstByte {
+ fn encode(val: &u8) -> Vec<u8> {
+ alloc::vec![*val]
+ }
+ }
+
+ fn stop(_: u8) -> Result<u8> {
+ Err(Error::Stopped)
+ }
+
+ wire_handler!(handle_stop, FirstByte, u8, 5u16, stop);
+
+ fn fail(_: u8) -> Result<u8> {
+ Err(Error::DataError("bad"))
+ }
+
+ wire_handler!(handle_fail, FirstByte, u8, 5u16, fail);
+
+ #[test]
+ fn wire_handler_sends_other_errors_to_host() {
+ crate::mock::sdk_init();
+ // reaching the mock's `wire_error`, which fails, shows as a service error
+ assert!(handle_fail(&[1]).is_err_and(|e| e.error_type() == "ServiceError"));
+ }
+
+ #[test]
+ fn wire_handler_returns_stop() {
+ crate::mock::sdk_init();
+ // not sent to the host (the mock's `wire_error` would fail)
+ assert!(handle_stop(&[1]).is_err_and(|e| e.is_stopped()));
+ }
+
+ #[test]
+ fn decode_response_checks_the_id() {
+ crate::mock::sdk_init();
+ assert!(matches!(decode_response::<FirstByte, Ping>(2, &[7]), Ok(7)));
+ assert!(matches!(
+ decode_response::<FirstByte, Ping>(3, &[7]),
+ Err(Error::InvalidMessage)
+ ));
+ }
+}
### sdk/crates/trezor-app-sdk/src/crypto.rs
@@ -0,0 +1,287 @@
+//! High-level crypto API
+//!
+//! This module provides user-friendly functions for interacting with the Trezor crypto.
+//!
+//! [`get_address_mac`] and friends round-trip through Core over IPC (via the
+//! stable-ABI [`CryptoV1`](crate::traits::crypto::CryptoV1) vtable handed to
+//! this app), since they touch key material Core alone holds.
+//!
+//! [`get_hasher`]/[`get_hmac`] are local (non-IPC) — hashing needs no secret
+//! material, so instead of Core they call straight through the local
+//! `CryptoV1::get_hasher`/`get_hmac` vtable, returning a [`BoxedHasher`]:
+//! update it and read the digest via [`HasherExt`], which — unlike the
+//! underlying stable-ABI [`Hasher`](crate::traits::crypto::Hasher) trait —
+//! takes and returns plain bytes (`&[u8]`, `impl AsRef<[u8]>`), so call sites don't need
+//! their own dependency on `stabby` (the SDK crate is the only dependency
+//! apps should need).
+
+use alloc::string::String;
+use alloc::vec::Vec;
+
+use stabby::slice::Slice;
+
+use crate::app_runtime::get_crypto_or_die;
+pub use crate::traits::crypto::{
+ BoxedHasher, CanonicalSig, Curve, EcdsaCurve, HashingAlgorithm, HmacAlgorithm, XPUB_RAW_LEN,
+};
+use crate::traits::crypto::{CryptoV1Dyn as _, HasherDynMut};
+use crate::util::Bytes;
+use crate::{IntoAppResult, Result, ResultExt};
+
+/// A local (non-IPC) streaming hasher for `algorithm` — see the module docs.
+pub fn get_hasher(algorithm: HashingAlgorithm) -> BoxedHasher {
+ get_crypto_or_die().get_hasher(algorithm)
+}
+
+/// A local (non-IPC) HMAC hasher (over `algorithm`, one of the SHA-2 family)
+/// keyed with `key` — see the module docs.
+pub fn get_hmac(algorithm: HmacAlgorithm, key: &[u8]) -> BoxedHasher {
+ get_crypto_or_die().get_hmac(algorithm, key.into())
+}
+
+/// Ergonomic, `stabby`-free wrapper around [`BoxedHasher`]'s stable-ABI
+/// methods — see the module docs.
+pub trait HasherExt {
+ /// Feeds more input into the hash state.
+ fn update(&mut self, input: &[u8]);
+ /// Returns the digest. Consumes the hasher, so it can't be used again:
+ ///
+ /// ```compile_fail
+ /// # use trezor_app_sdk::crypto::{self, HasherExt, HashingAlgorithm};
+ /// let mut hasher = crypto::get_hasher(HashingAlgorithm::Sha256);
+ /// hasher.finalize();
+ /// hasher.update(b"more");
+ /// ```
+ fn finalize(self) -> impl AsRef<[u8]>;
+}
+
+impl HasherExt for BoxedHasher {
+ fn update(&mut self, input: &[u8]) {
+ HasherDynMut::update(self, Slice::from(input));
+ }
+
+ fn finalize(mut self) -> impl AsRef<[u8]> {
+ Bytes(HasherDynMut::finalize(&mut self))
+ }
+}
+
+/// A derived public node: the fields of a serialized xpub.
+#[derive(Clone, PartialEq, Eq)]
+pub struct PublicNode {
+ /// Depth in the derivation tree, 0 for the master node.
+ pub depth: u8,
+ /// Fingerprint of the parent node.
+ pub fingerprint: u32,
+ /// Index within the parent; hardened indices have the top bit set.
+ pub child_num: u32,
+ /// Chain code, needed to derive child public keys.
+ pub chain_code: [u8; 32],
+ /// Compressed public key.
+ pub public_key: [u8; 33],
+}
+
+impl PublicNode {
+ fn from_raw(raw: &[u8; XPUB_RAW_LEN]) -> Self {
+ // the field sizes add up to `XPUB_RAW_LEN`, so the unwraps cannot fail
+ const _: () = assert!(XPUB_RAW_LEN == 1 + 4 + 4 + 32 + 33);
+ let (depth, rest) = raw.split_first_chunk::<1>().unwrap();
+ let (fingerprint, rest) = rest.split_first_chunk::<4>().unwrap();
+ let (child_num, rest) = rest.split_first_chunk::<4>().unwrap();
+ let (chain_code, public_key) = rest.split_first_chunk::<32>().unwrap();
+ Self {
+ depth: depth[0],
+ fingerprint: u32::from_be_bytes(*fingerprint),
+ child_num: u32::from_be_bytes(*child_num),
+ chain_code: *chain_code,
+ public_key: public_key.try_into().unwrap(),
+ }
+ }
+
+ /// The node serialized as an xpub with `version` as its version bytes,
+ /// before base58check encoding.
+ pub fn serialize(&self, version: u32) -> [u8; 4 + XPUB_RAW_LEN] {
+ let mut data = [0u8; 4 + XPUB_RAW_LEN];
+ data[..4].copy_from_slice(&version.to_be_bytes());
+ data[4] = self.depth;
+ data[5..9].copy_from_slice(&self.fingerprint.to_be_bytes());
+ data[9..13].copy_from_slice(&self.child_num.to_be_bytes());
+ data[13..45].copy_from_slice(&self.chain_code);
+ data[45..].copy_from_slice(&self.public_key);
+ data
+ }
+
+ /// The node as a base58check xpub with `version` as its version bytes
+ /// (e.g. the "xpub"/"ypub"/"zpub" prefix for the coin/script type in use).
+ pub fn to_xpub(&self, version: u32) -> String {
+ base58check_encode(&self.serialize(version))
+ }
+}
+
+/// Derives the public node for `address_n` on `curve`.
+pub fn get_public_node(curve: Curve, address_n: &[u32]) -> Result<PublicNode> {
+ get_crypto_or_die()
+ .get_xpub(curve, address_n.into())
+ .into_app_result()
+ .c()
+ .map(|raw| PublicNode::from_raw(&raw))
+}
+
+/// Derives the extended public key (xpub) for `address_n` on `curve`,
+/// base58check-encoded with `version` as its version bytes (e.g. the
+/// "xpub"/"ypub"/"zpub" prefix bytes for the coin/script type in use).
+pub fn get_xpub(curve: Curve, address_n: &[u32], version: u32) -> Result<String> {
+ Ok(get_public_node(curve, address_n)?.to_xpub(version))
+}
+
+/// Derives the public key for `address_n` on `curve`.
+pub fn get_public_key(curve: Curve, address_n: &[u32], compressed: bool) -> Result<Vec<u8>> {
+ get_crypto_or_die()
+ .get_public_key(curve, address_n.into(), compressed)
+ .into_app_result()
+ .c()
+ .map(|b| b.as_ref().to_vec())
+}
+
+/// Signs a raw 32-byte digest with the ECDSA key at `address_n` on `curve`,
+/// returning the 65-byte recoverable signature. Ed25519 has no digest
+/// signing, see [`ed25519_sign`].
+///
+/// `canonical` constrains a secp256k1 signature further, e.g.
+/// [`CanonicalSig::Ethereum`] for Ethereum transactions and messages. Other
+/// curves only accept [`CanonicalSig::Any`].
+pub fn ecdsa_sign_digest(
+ curve: EcdsaCurve,
+ address_n: &[u32],
+ digest: &[u8; 32],
+ compressed: bool,
+ canonical: CanonicalSig,
+) -> Result<[u8; 65]> {
+ get_crypto_or_die()
+ .ecdsa_sign_digest(curve, address_n.into(), digest, compressed, canonical)
+ .into_app_result()
+ .c()
+}
+
+/// Signs `message` with the Ed25519 key at `address_n`.
+pub fn ed25519_sign(address_n: &[u32], message: &[u8]) -> Result<[u8; 64]> {
+ get_crypto_or_die()
+ .ed25519_sign(address_n.into(), message.into())
+ .into_app_result()
+ .c()
+}
+
+/// Verifies a MAC previously produced by [`get_address_mac`] for `address_n`,
+/// `address` and the coin type `slip44`, confirming the pairing hasn't been
+/// tampered with. Fails on a wrong MAC.
+pub fn check_address_mac(
+ address_n: &[u32],
+ mac: &[u8; 32],
+ address: &str,
+ slip44: u32,
+) -> Result<()> {
+ get_crypto_or_die()
+ .check_address_mac(address_n.into(), mac, address.into(), slip44)
+ .into_app_result()
+ .c()
+}
+
+/// Computes a MAC binding `address_n` to `address` of the coin type `slip44`
+/// (as the built-in coin apps do), so a cached `address` can later be
+/// re-authenticated via [`check_address_mac`] without a full re-derivation.
+pub fn get_address_mac(address_n: &[u32], address: &str, slip44: u32) -> Result<[u8; 32]> {
+ get_crypto_or_die()
+ .get_address_mac(address_n.into(), address.into(), slip44)
+ .into_app_result()
+ .c()
+}
+
+/// Verifies a 64-byte `r||s` ECDSA `signature` of `digest` against
+/// `public_key` (compressed or uncompressed SEC1).
+pub fn ecdsa_verify_digest(
+ curve: EcdsaCurve,
+ public_key: &[u8],
+ signature: &[u8],
+ digest: &[u8],
+) -> Result<()> {
+ get_crypto_or_die()
+ .ecdsa_verify_digest(curve, public_key.into(), signature.into(), digest.into())
+ .into_app_result()
+ .c()
+}
+
+/// Recovers the uncompressed public key from an ECDSA `signature` over
+/// `digest`, with no candidate public key to check against — see
+/// [`traits::crypto::CryptoV1::ecdsa_recover_pubkey`](crate::traits::crypto::CryptoV1::ecdsa_recover_pubkey)
+/// for `signature`'s exact byte layout.
+pub fn ecdsa_recover_pubkey(curve: EcdsaCurve, signature: &[u8], digest: &[u8]) -> Result<Vec<u8>> {
+ get_crypto_or_die()
+ .ecdsa_recover_pubkey(curve, signature.into(), digest.into())
+ .into_app_result()
+ .c()
+ .map(|b| b.as_ref().to_vec())
+}
+
+/// Verifies a 64-byte Ed25519 `signature` of `message` against the 32-byte
+/// `public_key`.
+pub fn ed25519_verify(public_key: &[u8], signature: &[u8], message: &[u8]) -> Result<()> {
+ get_crypto_or_die()
+ .ed25519_verify(public_key.into(), signature.into(), message.into())
+ .into_app_result()
+ .c()
+}
+
+/// Base58-encodes `data`.
+pub fn base58_encode(data: &[u8]) -> String {
+ String::from(get_crypto_or_die().base58_encode(data.into()).as_str())
+}
+
+/// Decodes a base58-encoded `data` string.
+pub fn base58_decode(data: &str) -> Result<Vec<u8>> {
+ get_crypto_or_die()
+ .base58_decode(data.into())
+ .into_app_result()
+ .c()
+ .map(|b| b.as_ref().to_vec())
+}
+
+/// Base58Check-encodes `data` (base58 plus a 4-byte checksum).
+pub fn base58check_encode(data: &[u8]) -> String {
+ String::from(get_crypto_or_die().base58check_encode(data.into()).as_str())
+}
+
+/// Decodes a base58Check-encoded `data` string, verifying its checksum.
+pub fn base58check_decode(data: &str) -> Result<Vec<u8>> {
+ get_crypto_or_die()
+ .base58check_decode(data.into())
+ .into_app_result()
+ .c()
+ .map(|b| b.as_ref().to_vec())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn public_node_layout() {
+ let mut raw = [0u8; XPUB_RAW_LEN];
+ raw[0] = 3;
+ raw[1..5].copy_from_slice(&0x0102_0304u32.to_be_bytes());
+ raw[5..9].copy_from_slice(&0x8000_002cu32.to_be_bytes());
+ raw[9..41].fill(0xcc);
+ raw[41] = 0x02;
+ raw[42..].fill(0xaa);
+
+ let node = PublicNode::from_raw(&raw);
+ assert_eq!(node.depth, 3);
+ assert_eq!(node.fingerprint, 0x0102_0304);
+ assert_eq!(node.child_num, 0x8000_002c);
+ assert_eq!(node.chain_code, [0xcc; 32]);
+ assert_eq!(node.public_key[0], 0x02);
+ assert_eq!(node.public_key[1..], [0xaa; 32]);
+
+ let serialized = node.serialize(0x0488_b21e);
+ assert_eq!(serialized[..4], 0x0488_b21eu32.to_be_bytes());
+ assert_eq!(serialized[4..], raw);
+ }
+}
### sdk/crates/trezor-app-sdk/src/error.rs
@@ -0,0 +1,371 @@
+#[cfg(feature = "debug")]
+use alloc::boxed::Box;
+
+use crate::traits::crypto::CryptoError;
+use crate::traits::util::{CoreServiceError, FastResult, ServiceResult};
+use crate::traits::wire::FailureKind;
+
+/// The SDK's result type.
+pub type Result<T> = core::result::Result<T, Error>;
+
+#[cfg_attr(any(feature = "debug", feature = "test"), derive(Debug))]
+/// Errors an app's code can return. Which ones reach the host, and as what,
+/// is decided by [`Error::kind`] and [`Error::message`].
+pub enum Error {
+ /// A call to a Core service failed.
+ ServiceError,
+ /// The request's data is invalid; the text says why.
+ DataError(&'static str),
+ /// The user cancelled the action.
+ Cancelled,
+ /// A message could not be decoded.
+ InvalidMessage,
+ /// A parameter can't be passed to the SDK function, e.g. a value out of range.
+ InvalidArgument,
+ /// A value is invalid; the text says why.
+ ValueError(&'static str),
+ /// Core asked the app to stop, the error must reach the app's entry point.
+ Stopped,
+ #[cfg(feature = "debug")]
+ /// Another error with the source location where it was propagated, see
+ /// [`ResultExt::c`].
+ Context {
+ /// Source file of the location.
+ file: &'static str,
+ /// Line of the location.
+ line: u32,
+ /// The wrapped error.
+ source: Box<Error>,
+ },
+}
+
+impl Error {
+ /// The failure type Core reports to the host.
+ pub fn kind(&self) -> FailureKind {
+ match self {
+ Self::ServiceError => FailureKind::ProcessError,
+ Self::DataError(_) => FailureKind::DataError,
+ Self::Cancelled => FailureKind::ActionCancelled,
+ Self::InvalidMessage => FailureKind::DataError,
+ Self::InvalidArgument => FailureKind::DataError,
+ Self::ValueError(_) => FailureKind::DataError,
+ // never reaches the host: the app exits instead
+ Self::Stopped => FailureKind::ProcessError,
+ #[cfg(feature = "debug")]
+ Self::Context { source, .. } => source.kind(),
+ }
+ }
+
+ /// The message Core reports to the host; tells apart variants sharing a
+ /// code.
+ pub fn message(&self) -> &'static str {
+ match self {
+ Self::ServiceError => "service error",
+ Self::InvalidMessage => "invalid message",
+ Self::InvalidArgument => "invalid argument",
+ Self::DataError(msg) => msg,
+ Self::ValueError(msg) => msg,
+ Self::Cancelled => "cancelled",
+ Self::Stopped => "stopped",
+ #[cfg(feature = "debug")]
+ Self::Context { source, .. } => source.message(),
+ }
+ }
+
+ /// Logs this error and reports it to the host as a failure, using
+ /// [`Error::kind`] and [`Error::message`].
+ pub fn send_to_host(&self) -> Result<()> {
+ crate::error!("{}", self);
+ crate::wire::wire_error(self.kind(), self.message())
+ }
+
+ /// Whether Core asked the app to stop.
+ pub fn is_stopped(&self) -> bool {
+ match self {
+ Self::Stopped => true,
+ #[cfg(feature = "debug")]
+ Self::Context { source, .. } => source.is_stopped(),
+ _ => false,
+ }
+ }
+
+ /// The variant's name, for logging.
+ pub fn error_type(&self) -> &'static str {
+ match self {
+ Self::ServiceError => "ServiceError",
+ Self::DataError(_) => "DataError",
+ Self::Cancelled => "Cancelled",
+ Self::InvalidMessage => "InvalidMessage",
+ Self::InvalidArgument => "InvalidArgument",
+ Self::ValueError(_) => "ValueError",
+ Self::Stopped => "Stopped",
+ #[cfg(feature = "debug")]
+ Self::Context { source, .. } => source.error_type(),
+ }
+ }
+
+ #[cfg(feature = "debug")]
+ /// Wraps the error with the source location `loc`.
+ pub fn c_at(self, loc: &'static core::panic::Location<'static>) -> Self {
+ Error::Context {
+ file: loc.file(),
+ line: loc.line(),
+ source: Box::new(self),
+ }
+ }
+
+ #[cfg(feature = "debug")]
+ /// The wrapped error, if this is a [`Error::Context`].
+ pub fn source(&self) -> Option<&Error> {
+ match self {
+ Error::Context { source, .. } => Some(&*source),
+ _ => None,
+ }
+ }
+}
+
+impl CryptoError {
+ /// Returns a static human-readable description of the error.
+ pub fn message(&self) -> &'static str {
+ match self {
+ Self::InvalidPublicKey => "invalid public key",
+ Self::InvalidSignature => "invalid signature",
+ Self::InvalidEncoding => "invalid encoding",
+ }
+ }
+}
+
+impl<E> CoreServiceError<E> {
+ /// Keeps the system errors, for services without errors of their own.
+ pub(crate) fn system<F>(self) -> CoreServiceError<F> {
+ match self {
+ Self::ServiceError(_) | Self::ServiceCallFailed => CoreServiceError::ServiceCallFailed,
+ Self::Timeout => CoreServiceError::Timeout,
+ Self::StopApplication => CoreServiceError::StopApplication,
+ }
+ }
+}
+
+/// Splits a [`ServiceResult`] into its service-specific outcome and the
+/// system errors, so the caller can match on the former and `?` the latter.
+///
+/// ```rust,ignore
+/// match crypto.ecdsa_verify_digest(...).split_service_error()? {
+/// Ok(()) => { ... }
+/// Err(CryptoError::InvalidSignature) => { ... }
+/// Err(_) => { ... }
+/// }
+/// ```
+pub trait ServiceResultExt<T, E> {
+ /// Splits into the service's own result and the system errors.
+ fn split_service_error(
+ self,
+ ) -> core::result::Result<core::result::Result<T, E>, CoreServiceError<()>>;
+}
+
+impl<T, E> ServiceResultExt<T, E> for ServiceResult<T, E> {
+ fn split_service_error(
+ self,
+ ) -> core::result::Result<core::result::Result<T, E>, CoreServiceError<()>> {
+ match self {
+ FastResult::Ok(t) => Ok(Ok(t)),
+ FastResult::Err(CoreServiceError::ServiceError(e)) => Ok(Err(e)),
+ FastResult::Err(CoreServiceError::Timeout) => Err(CoreServiceError::Timeout),
+ FastResult::Err(CoreServiceError::ServiceCallFailed) => {
+ Err(CoreServiceError::ServiceCallFailed)
+ }
+ FastResult::Err(CoreServiceError::StopApplication) => {
+ Err(CoreServiceError::StopApplication)
+ }
+ }
+ }
+}
+
+impl From<CoreServiceError<()>> for Error {
+ fn from(error: CoreServiceError<()>) -> Self {
+ match error {
+ CoreServiceError::StopApplication => Error::Stopped,
+ // details are in Core's log
+ CoreServiceError::ServiceError(())
+ | CoreServiceError::Timeout
+ | CoreServiceError::ServiceCallFailed => Error::ServiceError,
+ }
+ }
+}
+
+impl From<CryptoError> for Error {
+ fn from(error: CryptoError) -> Self {
+ Error::DataError(error.message())
+ }
+}
+
+impl From<CoreServiceError<CryptoError>> for Error {
+ fn from(error: CoreServiceError<CryptoError>) -> Self {
+ match error {
+ CoreServiceError::ServiceError(e) => e.into(),
+ e => e.system::<()>().into(),
+ }
+ }
+}
+
+/// Converts the stable-ABI [`FastResult`] a [`WireV1`](crate::traits::wire::WireV1)/
+/// [`CryptoV1`](crate::traits::crypto::CryptoV1)/[`UiV1`](crate::traits::ui::UiV1)
+/// call returns into this crate's own [`Result`].
+pub trait IntoAppResult<T> {
+ /// Converts into the SDK's [`Result`].
+ fn into_app_result(self) -> Result<T>;
+}
+
+impl<T, E> IntoAppResult<T> for FastResult<T, E>
+where
+ Error: From<E>,
+{
+ fn into_app_result(self) -> Result<T> {
+ self.into_result().map_err(Into::into)
+ }
+}
+
+#[cfg(feature = "debug")]
+impl ufmt::uDisplay for Error {
+ fn fmt<W: ?Sized>(&self, f: &mut ufmt::Formatter<'_, W>) -> core::result::Result<(), W::Error>
+ where
+ W: ufmt::uWrite,
+ {
+ match self {
+ Error::Context { file, line, .. } => {
+ ufmt::uwrite!(f, "Context Error at\nLocation: {}:{}", file, line)?;
+ }
+ _ => {
+ ufmt::uwrite!(f, "{}: {}", self.error_type(), self.message())?;
+ }
+ }
+ let mut source = self.source();
+ while let Some(err) = source {
+ match err {
+ Error::Context { file, line, .. } => {
+ ufmt::uwrite!(f, "\nLocation: {}:{}", file, line)?;
+ }
+ _ => {
+ ufmt::uwrite!(f, "\nCaused by: {}: {}", err.error_type(), err.message())?;
+ }
+ }
+ source = err.source();
+ }
+
+ Ok(())
+ }
+}
+
+#[cfg(not(feature = "debug"))]
+impl ufmt::uDisplay for Error {
+ fn fmt<W: ?Sized>(&self, f: &mut ufmt::Formatter<'_, W>) -> core::result::Result<(), W::Error>
+ where
+ W: ufmt::uWrite,
+ {
+ ufmt::uwrite!(f, "{}: {}", self.error_type(), self.message())?;
+ Ok(())
+ }
+}
+
+/// Extension trait for attaching call-site context to an [`Error`] as it
+/// propagates up through `?`.
+pub trait ResultExt<T> {
+ /// Records the caller's file and line on `Err`, if the `debug` feature
+ /// is enabled; otherwise a no-op.
+ ///
+ /// Call it right after any fallible expression you want to be locatable
+ /// in a `debug` build, typically as `foo().c()?`:
+ ///
+ /// ```rust,no_run
+ /// # use trezor_app_sdk::{Error, Result, ResultExt};
+ /// fn inner() -> Result<()> {
+ /// Err(Error::InvalidArgument)
+ /// }
+ ///
+ /// fn outer() -> Result<()> {
+ /// inner().c()?; // records this line when `debug` is enabled
+ /// Ok(())
+ /// }
+ /// ```
+ ///
+ /// # `debug` builds
+ ///
+ /// Wraps the error in [`Error::Context`], capturing the file and line of
+ /// the `.c()` call itself via `#[track_caller]`. Every further `.c()`
+ /// applied on the way back up the call stack adds one more location, so
+ /// a chain of `.c()` calls builds a manual backtrace. Printing the final
+ /// error (via its [`ufmt::uDisplay`] impl) walks that chain, e.g.:
+ ///
+ /// ```text
+ /// Context Error at
+ /// Location: outer.rs:8
+ /// Location: main.rs:3
+ /// Caused by: InvalidArgument:
+ /// ```
+ ///
+ /// # Release builds
+ ///
+ /// Without the `debug` feature, `c()` just returns `self` unchanged —
+ /// zero cost, so it's safe to sprinkle on every fallible expression
+ /// regardless of build profile.
+ ///
+ /// # Gaps in the trace
+ ///
+ /// Each `.c()` call contributes exactly one location. If some function
+ /// forwards an error without calling it (e.g. `foo()?` instead of
+ /// `foo().c()?`), that hop simply contributes nothing — callers further
+ /// up and callees further down that *do* call `.c()` still show up
+ /// unaffected. In practice this matters most near the origin: since the
+ /// error itself carries no location until something wraps it, if the
+ /// call site closest to the failure skips `.c()`, the trace won't
+ /// contain anything below the next ancestor that does call it — the
+ /// backtrace effectively starts there. Call `.c()` consistently at every
+ /// `?` in a chain to avoid these blind spots.
+ fn c(self) -> Self;
+}
+
+impl<T> ResultExt<T> for Result<T> {
+ #[cfg(feature = "debug")]
+ #[track_caller]
+ fn c(self) -> Self {
+ let loc = core::panic::Location::caller();
+ self.map_err(|e| e.c_at(loc))
+ }
+
+ #[cfg(not(feature = "debug"))]
+ fn c(self) -> Self {
+ self
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn stop_signal_survives_conversion() {
+ assert!(Error::from(CoreServiceError::<()>::StopApplication).is_stopped());
+ assert!(Error::from(CoreServiceError::<CryptoError>::StopApplication).is_stopped());
+ assert!(!Error::from(CoreServiceError::<()>::ServiceCallFailed).is_stopped());
+ assert!(!Error::DataError("stopped").is_stopped());
+ }
+
+ #[test]
+ fn service_errors_convert() {
+ let error = Error::from(CoreServiceError::ServiceError(
+ CryptoError::InvalidSignature,
+ ));
+ assert_eq!(error.kind(), FailureKind::DataError);
+ assert_eq!(error.message(), "invalid signature");
+ let error = Error::from(CoreServiceError::<CryptoError>::Timeout);
+ assert_eq!(error.kind(), FailureKind::ProcessError);
+ }
+
+ #[cfg(feature = "debug")]
+ #[test]
+ fn stop_signal_survives_context() {
+ let error = Error::from(CoreServiceError::<()>::StopApplication)
+ .c_at(core::panic::Location::caller());
+ assert!(error.is_stopped());
+ }
+}
### sdk/crates/trezor-app-sdk/src/lib.rs
@@ -0,0 +1,84 @@
+//! # Trezor App SDK
+//!
+//! A `no_std` SDK for developing Trezor applications in Rust.
+//!
+//! ## Features
+//!
+//! - `app`: Enables full app runtime (heap allocation, IPC, UI, crypto, etc.)
+//! Required for extapps / standalone app binaries. Needs a nightly
+//! toolchain (`extern_item_impls`, for the [`app`] entry point).
+//! - `debug`: Enables debug logging and richer error context
+//! - `test`: Enables std-based testing utilities
+//! - `nightly`: Enables unstable (nightly-only) language/library features
+//! used by the default panic/abort machinery. Default-enabled;
+//! disable on stable toolchains to fall back to stable-compatible
+//! implementations.
+//!
+//! Without `app`, only `structs` (shared API types) are available — suitable
+//! for the core app which only needs to work with the API structs.
+
+#![cfg_attr(not(feature = "test"), no_std)]
+#![allow(internal_features)]
+#![allow(dead_code)]
+#![cfg_attr(
+ all(feature = "debug", not(feature = "test"), feature = "nightly"),
+ feature(lang_items)
+)]
+#![cfg_attr(feature = "app", feature(extern_item_impls))]
+#![warn(missing_docs)]
+
+extern crate alloc;
+
+#[cfg(feature = "app")]
+/// The SDK's [`Error`] type and helpers to add context to results.
+pub mod error;
+// Always available: shared API structs used by both core app and extapps
+pub mod structs;
+
+#[cfg(feature = "app")]
+/// The app runtime: the entry point, access to Core's API and the heap allocator.
+pub mod app_runtime;
+
+/// The stable-ABI traits and types shared with Core.
+pub mod traits;
+
+#[cfg(feature = "app")]
+pub mod crypto;
+
+#[cfg(feature = "app")]
+pub mod ui;
+
+#[cfg(feature = "app")]
+pub mod log;
+
+#[doc(hidden)]
+#[cfg(feature = "app")]
+pub mod print;
+
+#[cfg(feature = "app")]
+/// Small helpers, such as [`util::Timeout`].
+pub mod util;
+
+#[cfg(feature = "app")]
+mod wire;
+
+#[cfg(feature = "app")]
+mod codec;
+
+#[cfg(feature = "test")]
+pub mod mock;
+
+#[cfg(feature = "app")]
+pub use app_runtime::app;
+#[cfg(feature = "app")]
+pub use codec::{WireDecode, WireEncode, WireRequest, wire_request};
+#[cfg(feature = "app")]
+pub use error::{Error, IntoAppResult, Result, ResultExt, ServiceResultExt};
+#[cfg(feature = "app")]
+pub use traits::wire::FailureKind;
+// for the log macros, see `log!`
+#[cfg(feature = "app")]
+#[doc(hidden)]
+pub use ufmt as __ufmt;
+#[cfg(feature = "app")]
+pub use wire::{wire_call, wire_error, wire_receive, wire_send};
### sdk/crates/trezor-app-sdk/src/log.rs
@@ -0,0 +1,251 @@
+//! Logging module.
+//!
+//! Provides structured logging with compile-time level filtering.
+//!
+//! ## Usage
+//!
+//! Logging a static string literal compiles fine:
+//! ```no_run
+//! use trezor_app_sdk::info;
+//! info!("Application started");
+//! ```
+//!
+//! Passing a `String` directly will **not** compile, because `String` does not
+//! implement `ufmt::uDebug`:
+//! ```rust, compile_fail
+//! # #![no_std]
+//! # extern crate alloc;
+//! # use alloc::string::String;
+//! use trezor_app_sdk::info;
+//! let s = String::from("hello");
+//! info!("value: {}", s); // error: String does not implement uDebug
+//! ```
+//!
+//! Use `.as_str()` instead — `&str` implements `uDebug`:
+//! ```no_run
+//! use trezor_app_sdk::info;
+//! let s = String::from("hello");
+//! info!("value: {}", s.as_str()); // ok: &str implements uDebug
+//! ```
+//!
+//! ## Compile-time filtering
+//!
+//! Log level is controlled at build time via Cargo features. Enable exactly one of:
+//!
+//! ```toml
+//! # Cargo.toml
+//! [features]
+//! log_level_error = []
+//! log_level_warn = []
+//! log_level_info = []
+//! log_level_debug = []
+//! ```
+//!
+//! Each level implies all levels above it (e.g. `log_level_info` enables `error`,
+//! `warn`, and `info`). If no feature is enabled, all log output is compiled out.
+//!
+//! The preferred way to set the log level is via `cargo app-tool`:
+//!
+//! ```bash
+//! cargo app-tool build --log-level info
+//! ```
+//!
+//! Alternatively, pass the feature flag directly to Cargo:
+//!
+//! ```bash
+//! cargo build --features log_level_info
+//! ```
+
+// Private helper macro — exported only so the level-specific macros can call it
+// from other crates. Do not use this macro directly.
+#[doc(hidden)]
+#[macro_export]
+macro_rules! log {
+ ($level:expr, $($args:tt)*) => {
+ #[cfg(any(
+ feature = "log_level_error",
+ feature = "log_level_warn",
+ feature = "log_level_info",
+ feature = "log_level_debug",
+ ))]
+ {
+ $crate::print::log($level, |mut writer| {
+ // `uwrite!` expands to `ufmt::` paths, resolved here so apps
+ // need no `ufmt` dependency of their own
+ use $crate::__ufmt as ufmt;
+ ufmt::uwrite!(writer, $($args)*)
+ });
+ }
+ }
+}
+
+/// Logs a message at the **ERROR** level.
+///
+/// Compiled in when any `log_level_*` feature is enabled, since `error` is the
+/// highest-severity level and is always included when logging is active.
+///
+/// # Examples
+///
+/// ```no_run
+/// use trezor_app_sdk::error;
+/// error!("Something went wrong: {}", "bad state");
+/// ```
+///
+/// Passing a `String` directly will **not** compile — use `.as_str()`:
+/// ```compile_fail
+/// # #![no_std]
+/// # extern crate alloc;
+/// # use alloc::string::String;
+/// use trezor_app_sdk::error;
+/// let s = String::from("oops");
+/// error!("msg: {}", s); // error: String does not implement uDebug
+/// ```
+/// ```no_run
+/// use trezor_app_sdk::error;
+/// let s = String::from("oops");
+/// error!("msg: {}", s.as_str()); // ok
+/// ```
+#[macro_export]
+macro_rules! error {
+ ($($arg:tt)*) => {
+ #[cfg(any(
+ feature = "log_level_error",
+ feature = "log_level_warn",
+ feature = "log_level_info",
+ feature = "log_level_debug",
+ ))]
+ {
+ $crate::log::log!(
+ $crate::traits::syslog::LogLevel::Error,
+ $($arg)*
+ );
+ }
+ };
+}
+
+/// Logs a message at the **WARN** level.
+///
+/// Compiled in when `log_level_warn` or a lower-severity feature is enabled.
+///
+/// # Examples
+///
+/// ```no_run
+/// use trezor_app_sdk::warn;
+/// warn!("Unexpected value: {}", 42u32);
+/// ```
+///
+/// Passing a `String` directly will **not** compile — use `.as_str()`:
+/// ```rust, compile_fail
+/// # #![no_std]
+/// # extern crate alloc;
+/// # use alloc::string::String;
+/// use trezor_app_sdk::warn;
+/// let s = String::from("watch out");
+/// warn!("msg: {}", s); // error: String does not implement uDebug
+/// ```
+/// ```no_run
+/// use trezor_app_sdk::warn;
+/// let s = String::from("watch out");
+/// warn!("msg: {}", s.as_str()); // ok
+/// ```
+#[macro_export]
+macro_rules! warn {
+ ($($arg:tt)*) => {
+ #[cfg(any(
+ feature = "log_level_warn",
+ feature = "log_level_info",
+ feature = "log_level_debug",
+ ))]
+ {
+ $crate::log::log!(
+ $crate::traits::syslog::LogLevel::Warn,
+ $($arg)*
+ );
+ }
+ };
+}
+
+/// Logs a message at the **INFO** level.
+///
+/// Compiled in when `log_level_info` or `log_level_debug` is enabled.
+///
+/// # Examples
+///
+/// ```no_run
+/// use trezor_app_sdk::info;
+/// info!("Application started");
+/// info!("Processed {} items", 7u32);
+/// ```
+///
+/// Passing a `String` directly will **not** compile — use `.as_str()`:
+/// ```rust, compile_fail
+/// # #![no_std]
+/// # extern crate alloc;
+/// # use alloc::string::String;
+/// use trezor_app_sdk::info;
+/// let s = String::from("hello");
+/// info!("value: {}", s); // error: String does not implement uDebug
+/// ```
+/// ```no_run
+/// use trezor_app_sdk::info;
+/// let s = String::from("hello");
+/// info!("value: {}", s.as_str()); // ok
+/// ```
+#[macro_export]
+macro_rules! info {
+ ($($arg:tt)*) => {
+ #[cfg(any(
+ feature = "log_level_info",
+ feature = "log_level_debug",
+ ))]
+ {
+ $crate::log::log!(
+ $crate::traits::syslog::LogLevel::Info,
+ $($arg)*
+ );
+ }
+ };
+}
+
+/// Logs a message at the **DEBUG** level.
+///
+/// Compiled in only when `log_level_debug` is enabled.
+///
+/// # Examples
+///
+/// ```no_run
+/// use trezor_app_sdk::debug;
+/// debug!("Entry point reached");
+/// debug!("Raw bytes: {}", 0xDEu32);
+/// ```
+///
+/// Passing a `String` directly will **not** compile — use `.as_str()`:
+/// ```rust, compile_fail
+/// # #![no_std]
+/// # extern crate alloc;
+/// # use alloc::string::String;
+/// use trezor_app_sdk::debug;
+/// let s = String::from("trace");
+/// debug!("msg: {}", s); // error: String does not implement uDebug
+/// ```
+/// ```no_run
+/// use trezor_app_sdk::debug;
+/// let s = String::from("trace");
+/// debug!("msg: {}", s.as_str()); // ok
+/// ```
+#[macro_export]
+macro_rules! debug {
+ ($($arg:tt)*) => {
+ #[cfg(
+ feature = "log_level_debug"
+ )]
+ {
+ $crate::log::log!(
+ $crate::traits::syslog::LogLevel::Debug,
+ $($arg)*
+ );
+ }
+ };
+}
+
+pub use log;
### sdk/crates/trezor-app-sdk/src/mock.rs
@@ -0,0 +1,728 @@
+//! Mock implementations for unit testing only.
+//!
+//! This module provides stub implementations of the Trezor crypto and API interfaces
+//! intended exclusively for use in unit tests. It must **not** be used in production builds.
+//!
+//! Each implementation is explicitly marked as either:
+//! - **Functional** — delegates to a real software implementation via a third-party crate.
+//! - **Stub** — always returns a fixed error value, zero, `false`, or `null`; does not perform
+//! any real computation.
+
+use std::alloc::{GlobalAlloc, System};
+
+use mock_hmac_sha256::{HMAC as HMAC256_impl, Hash as Sha256_impl};
+use mock_hmac_sha512::{HMAC as HMAC512_impl, Hash as Sha512_impl};
+use mock_sha3::digest::FixedOutput;
+use mock_sha3::{
+ Digest, Keccak256 as Keccak256_impl, Keccak512 as Keccak512_impl, Sha3_256 as Sha3_256_impl,
+ Sha3_512 as Sha3_512_impl,
+};
+use stabby::boxed::{Box, BoxedSlice};
+use stabby::slice::Slice;
+use stabby::str::Str;
+
+use crate::traits::ApiVariant;
+use crate::traits::allocator::{FfiLayout, GlobalAllocatorV1, GlobalAllocatorV1Vtable};
+use crate::traits::crypto::{
+ BoxedHasher, CanonicalSig, CryptoError, CryptoV1, CryptoV1Vtable, Curve, EcdsaCurve, Hasher,
+ HashingAlgorithm, HmacAlgorithm, XPUB_RAW_LEN,
+};
+use crate::traits::syslog::{
+ LogCallbackDyn as _, LogCallbackRef, LogLevel, LogRecord, SyslogV1, SyslogV1Vtable,
+};
+use crate::traits::trezor_v1::{TrezorApiV1, TrezorApiV1Struct, TrezorApiV1Vtable};
+use crate::traits::ui::{
+ ConfirmAction, ConfirmProperties, ConfirmSummary, ConfirmTrade, ConfirmValue,
+ ConfirmValueIntro, ConfirmWithInfo, RequestNumber, SelectMenu, ShowAddress, ShowDanger,
+ ShowInfoWithCancel, ShowMismatch, ShowProperties, ShowPublicKey, ShowSuccess, ShowWarning,
+ TrezorUiResult, UiV1, UiV1Vtable,
+};
+use crate::traits::util::{CoreServiceError, FastResult, ServiceResult};
+use crate::traits::wire::{FailureKind, WireMessage, WireV1, WireV1Vtable};
+
+// ============================================================================
+// Dummy implementation of the stable ABI, for host-based unit tests.
+//
+// `syslog`, `allocator` (indirectly, via `std`'s allocator), and `crypto`'s
+// `get_hasher`/`get_hmac` (via the `Sha256`/`Keccak256`/etc. mocks further
+// down) do real work; everything else in `crypto` and all of `ipc` are
+// unimplemented — no test talks to a (nonexistent, in this context) Core
+// over IPC.
+// ============================================================================
+
+struct DummyApi;
+
+impl TrezorApiV1 for DummyApi {
+ extern "C" fn system_exit(&self) -> ! {
+ panic!("app called system_exit")
+ }
+
+ extern "C" fn system_exit_error<'a>(
+ &self,
+ title: Str<'a>,
+ message: Str<'a>,
+ _footer: Str<'a>,
+ ) -> ! {
+ panic!(
+ "app called system_exit_error: {} / {}",
+ title.as_str(),
+ message.as_str()
+ )
+ }
+
+ extern "C" fn system_exit_fatal<'a>(&self, message: Str<'a>, file: Str<'a>, line: u32) -> ! {
+ panic!(
+ "app called system_exit_fatal: {} at {}:{}",
+ message.as_str(),
+ file.as_str(),
+ line
+ )
+ }
+
+ extern "C" fn systick_ms(&self) -> u32 {
+ 0
+ }
+
+ extern "C" fn sleep(&self, _timeout_ms: u32) {}
+}
+
+struct DummyAllocator;
+
+// SAFETY: forwards to `std::alloc::System`, a real, correct allocator.
+unsafe impl GlobalAllocatorV1 for DummyAllocator {
+ unsafe extern "C" fn alloc(&self, layout: FfiLayout) -> *mut u8 {
+ unsafe { System.alloc(layout.into()) }
+ }
+
+ unsafe extern "C" fn dealloc(&self, ptr: *mut u8, layout: FfiLayout) {
+ unsafe { System.dealloc(ptr, layout.into()) }
+ }
+
+ unsafe extern "C" fn alloc_zeroed(&self, layout: FfiLayout) -> *mut u8 {
+ unsafe { System.alloc_zeroed(layout.into()) }
+ }
+
+ unsafe extern "C" fn realloc(
+ &self,
+ ptr: *mut u8,
+ layout: FfiLayout,
+ new_size: usize,
+ ) -> *mut u8 {
+ unsafe { System.realloc(ptr, layout.into(), new_size) }
+ }
+}
+
+struct DummyCrypto;
+
+impl CryptoV1 for DummyCrypto {
+ extern "C" fn get_hasher(&self, algorithm: HashingAlgorithm) -> BoxedHasher {
+ match algorithm {
+ HashingAlgorithm::Sha256 => Box::new(Sha256::new(None)).into(),
+ HashingAlgorithm::Sha512 => Box::new(Sha512::new(None)).into(),
+ HashingAlgorithm::Sha3_256 => Box::new(Sha3_256::new(None)).into(),
+ HashingAlgorithm::Keccak256 => Box::new(Keccak256::new(None)).into(),
+ HashingAlgorithm::Sha3_512 => Box::new(Sha3_512::new(None)).into(),
+ HashingAlgorithm::Keccak512 => Box::new(Keccak512::new(None)).into(),
+ }
+ }
+
+ extern "C" fn get_hmac<'a>(&self, algorithm: HmacAlgorithm, key: Slice<'a, u8>) -> BoxedHasher {
+ match algorithm {
+ HmacAlgorithm::Sha256 => Box::new(HmacSha256::new(key.as_slice(), None)).into(),
+ HmacAlgorithm::Sha512 => Box::new(HmacSha512::new(key.as_slice(), None)).into(),
+ }
+ }
+
+ extern "C" fn get_xpub<'a>(
+ &self,
+ _curve: Curve,
+ _address_n: Slice<'a, u32>,
+ ) -> ServiceResult<[u8; XPUB_RAW_LEN], CryptoError> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn get_public_key<'a>(
+ &self,
+ _curve: Curve,
+ _address_n: Slice<'a, u32>,
+ _compressed: bool,
+ ) -> ServiceResult<stabby::boxed::BoxedSlice<u8>, CryptoError> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn ecdsa_sign_digest<'a>(
+ &self,
+ _curve: EcdsaCurve,
+ _address_n: Slice<'a, u32>,
+ _digest: &'a [u8; 32],
+ _compressed: bool,
+ _canonical: CanonicalSig,
+ ) -> ServiceResult<[u8; 65], CryptoError> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn ed25519_sign<'a>(
+ &self,
+ _address_n: Slice<'a, u32>,
+ _message: Slice<'a, u8>,
+ ) -> ServiceResult<[u8; 64], CryptoError> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn check_address_mac<'a>(
+ &self,
+ _address_n: Slice<'a, u32>,
+ _mac: &'a [u8; 32],
+ _address: Str<'a>,
+ _slip44: u32,
+ ) -> ServiceResult<(), CryptoError> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn get_address_mac<'a>(
+ &self,
+ _address_n: Slice<'a, u32>,
+ _address: Str<'a>,
+ _slip44: u32,
+ ) -> ServiceResult<[u8; 32], CryptoError> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn ecdsa_verify_digest<'a>(
+ &self,
+ _curve: EcdsaCurve,
+ _public_key: Slice<'a, u8>,
+ _signature: Slice<'a, u8>,
+ _digest: Slice<'a, u8>,
+ ) -> FastResult<(), CryptoError> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn ecdsa_recover_pubkey<'a>(
+ &self,
+ _curve: EcdsaCurve,
+ _signature: Slice<'a, u8>,
+ _digest: Slice<'a, u8>,
+ ) -> FastResult<stabby::boxed::BoxedSlice<u8>, CryptoError> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn ed25519_verify<'a>(
+ &self,
+ _public_key: Slice<'a, u8>,
+ _signature: Slice<'a, u8>,
+ _message: Slice<'a, u8>,
+ ) -> FastResult<(), CryptoError> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn base58_encode<'a>(&self, _data: Slice<'a, u8>) -> stabby::string::String {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn base58_decode<'a>(
+ &self,
+ _data: Str<'a>,
+ ) -> FastResult<stabby::boxed::BoxedSlice<u8>, CryptoError> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn base58check_encode<'a>(&self, _data: Slice<'a, u8>) -> stabby::string::String {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn base58check_decode<'a>(
+ &self,
+ _data: Str<'a>,
+ ) -> FastResult<stabby::boxed::BoxedSlice<u8>, CryptoError> {
+ unimplemented!("not exercised by the current test suite")
+ }
+}
+
+struct DummySyslog;
+
+impl LogRecord for DummySyslog {
+ extern "C" fn write<'a>(&self, string: Str<'a>) -> FastResult<(), ()> {
+ print!("{}", string.as_str());
+ Ok(()).into()
+ }
+}
+
+impl SyslogV1 for DummySyslog {
+ extern "C" fn log_simple<'a>(&self, _level: LogLevel, message: Str<'a>) {
+ println!("{}", message.as_str());
+ }
+
+ extern "C" fn log<'a>(&self, _level: LogLevel, callback: LogCallbackRef<'a>) {
+ callback.call(self.into());
+ println!();
+ }
+}
+
+struct DummyWire;
+
+impl WireV1 for DummyWire {
+ extern "C" fn wire_receive(&self, _timeout_ms: u32) -> ServiceResult<WireMessage> {
+ Err(CoreServiceError::Timeout).into()
+ }
+
+ extern "C" fn wire_send<'a>(&self, _id: u16, _data: Slice<'a, u8>) -> ServiceResult<()> {
+ Err(CoreServiceError::ServiceCallFailed).into()
+ }
+
+ extern "C" fn wire_error<'a>(
+ &self,
+ _kind: FailureKind,
+ _message: Str<'a>,
+ ) -> ServiceResult<()> {
+ Err(CoreServiceError::ServiceCallFailed).into()
+ }
+}
+
+struct DummyUi;
+
+impl UiV1 for DummyUi {
+ extern "C" fn confirm_value<'a>(
+ &self,
+ _value: ConfirmValue<'a>,
+ ) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn confirm_value_intro<'a>(
+ &self,
+ _value: ConfirmValueIntro<'a>,
+ ) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn confirm_summary<'a>(
+ &self,
+ _value: ConfirmSummary<'a>,
+ ) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn confirm_action<'a>(
+ &self,
+ _value: ConfirmAction<'a>,
+ ) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn select_menu<'a>(&self, _value: SelectMenu<'a>) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn confirm_properties<'a>(
+ &self,
+ _value: ConfirmProperties<'a>,
+ ) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn show_properties<'a>(&self, _value: ShowProperties<'a>) -> ServiceResult<()> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn show_warning<'a>(&self, _value: ShowWarning<'a>) -> ServiceResult<()> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn show_info_with_cancel<'a>(
+ &self,
+ _value: ShowInfoWithCancel<'a>,
+ ) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn show_mismatch<'a>(
+ &self,
+ _value: ShowMismatch<'a>,
+ ) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn confirm_trade<'a>(
+ &self,
+ _value: ConfirmTrade<'a>,
+ ) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn show_danger<'a>(&self, _value: ShowDanger<'a>) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn show_success<'a>(&self, _value: ShowSuccess<'a>) -> ServiceResult<()> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn request_number<'a>(
+ &self,
+ _value: RequestNumber<'a>,
+ ) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn show_public_key<'a>(
+ &self,
+ _value: ShowPublicKey<'a>,
+ ) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn confirm_with_info<'a>(
+ &self,
+ _value: ConfirmWithInfo<'a>,
+ ) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn show_address<'a>(
+ &self,
+ _value: ShowAddress<'a>,
+ ) -> ServiceResult<TrezorUiResult> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn init_progress<'a>(
+ &self,
+ _description: stabby::option::Option<stabby::slice::Slice<'a, u8>>,
+ _title: stabby::option::Option<stabby::slice::Slice<'a, u8>>,
+ _indeterminate: bool,
+ _danger: bool,
+ ) -> ServiceResult<()> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn update_progress<'a>(
+ &self,
+ _description: stabby::option::Option<stabby::slice::Slice<'a, u8>>,
+ _value: u32,
+ ) -> ServiceResult<()> {
+ unimplemented!("not exercised by the current test suite")
+ }
+
+ extern "C" fn end_progress(&self) -> ServiceResult<()> {
+ unimplemented!("not exercised by the current test suite")
+ }
+}
+
+static DUMMY_API: TrezorApiV1Struct = TrezorApiV1Struct {
+ api: stabby::dynref_static!(DummyApi as TrezorApiV1Vtable),
+ allocator: stabby::dynref_static!(DummyAllocator as GlobalAllocatorV1Vtable),
+ crypto: stabby::dynref_static!(DummyCrypto as CryptoV1Vtable),
+ syslog: stabby::dynref_static!(DummySyslog as SyslogV1Vtable),
+ wire: stabby::dynref_static!(DummyWire as WireV1Vtable),
+ ui: stabby::dynref_static!(DummyUi as UiV1Vtable),
+};
+
+extern "C" fn dummy_api_getter(version: u32) -> ApiVariant {
+ match version {
+ 1 => ApiVariant::V1(&DUMMY_API),
+ _ => panic!("unsupported API version: {version}"),
+ }
+}
+
+/// Initializes the app-side SDK with a dummy stable-ABI implementation, so
+/// `app_runtime`-backed code (logging, `Timeout`, etc.) doesn't panic with
+/// "API not initialized" in unit tests. Idempotent: call it as many times as
+/// you like, from as many tests as you like — only the first call matters.
+pub fn sdk_init() {
+ crate::app_runtime::init(dummy_api_getter);
+}
+
+// ============================================================================
+// Functional hash / HMAC implementations (via third-party crates)
+// ============================================================================
+//
+// All structs below delegate to real software implementations and produce
+// correct cryptographic output. They are safe to use in unit tests that
+// need to verify hash or HMAC correctness.
+
+// Sha functions
+
+/// **Functional** — delegates to `mock_hmac_sha256::Hash` (software SHA-256).
+pub struct Sha256 {
+ ctx: Sha256_impl,
+}
+
+impl Sha256 {
+ /// A hasher fed with `data`, if given.
+ pub fn new(data: Option<&[u8]>) -> Self {
+ let ctx = Sha256_impl::new();
+ let mut hasher = Self { ctx };
+ if let Some(data) = data {
+ hasher.ctx.update(data);
+ }
+ hasher
+ }
+
+ /// Returns the digest.
+ pub fn digest(&mut self) -> [u8; 32] {
+ self.ctx.clone().finalize()
+ }
+}
+
+impl Hasher for Sha256 {
+ extern "C" fn update<'a>(&mut self, input: Slice<'a, u8>) {
+ self.ctx.update(input.as_slice());
+ }
+
+ extern "C" fn finalize(&mut self) -> BoxedSlice<u8> {
+ BoxedSlice::from(&self.ctx.clone().finalize()[..])
+ }
+}
+
+/// **Functional** — delegates to `mock_hmac_sha512::Hash` (software SHA-512).
+pub struct Sha512 {
+ ctx: Sha512_impl,
+}
+
+impl Sha512 {
+ /// A hasher fed with `data`, if given.
+ pub fn new(data: Option<&[u8]>) -> Self {
+ let ctx = Sha512_impl::new();
+ let mut hasher = Self { ctx };
+ if let Some(data) = data {
+ hasher.ctx.update(data);
+ }
+ hasher
+ }
+
+ /// Returns the digest.
+ pub fn digest(&mut self) -> [u8; 64] {
+ self.ctx.clone().finalize()
+ }
+}
+
+impl Hasher for Sha512 {
+ extern "C" fn update<'a>(&mut self, input: Slice<'a, u8>) {
+ self.ctx.update(input.as_slice());
+ }
+
+ extern "C" fn finalize(&mut self) -> BoxedSlice<u8> {
+ BoxedSlice::from(&self.digest()[..])
+ }
+}
+// Sha3 functions
+
+/// **Functional** — delegates to `mock_sha3::Keccak256` (software Keccak-256).
+pub struct Keccak256 {
+ ctx: Keccak256_impl,
+}
+
+impl Keccak256 {
+ /// A hasher fed with `data`, if given.
+ pub fn new(data: Option<&[u8]>) -> Self {
+ let ctx = Keccak256_impl::new();
+ let mut hasher = Self { ctx };
+ if let Some(data) = data {
+ hasher.ctx.update(data);
+ }
+ hasher
+ }
+
+ /// Returns the digest.
+ pub fn digest(&mut self) -> [u8; 32] {
+ let mut out = [0u8; 32];
+ out.copy_from_slice(self.ctx.clone().finalize_fixed().as_slice());
+ out
+ }
+}
+
+impl Hasher for Keccak256 {
+ extern "C" fn update<'a>(&mut self, input: Slice<'a, u8>) {
+ self.ctx.update(input.as_slice());
+ }
+
+ extern "C" fn finalize(&mut self) -> BoxedSlice<u8> {
+ BoxedSlice::from(&self.digest()[..])
+ }
+}
+
+/// **Functional** — delegates to `mock_sha3::Sha3_256` (software SHA3-256).
+pub struct Sha3_256 {
+ ctx: Sha3_256_impl,
+}
+
+impl Sha3_256 {
+ /// A hasher fed with `data`, if given.
+ pub fn new(data: Option<&[u8]>) -> Self {
+ let ctx = Sha3_256_impl::new();
+ let mut hasher = Self { ctx };
+ if let Some(data) = data {
+ hasher.ctx.update(data);
+ }
+ hasher
+ }
+
+ /// Returns the digest.
+ pub fn digest(&mut self) -> [u8; 32] {
+ let mut out = [0u8; 32];
+ out.copy_from_slice(self.ctx.clone().finalize_fixed().as_slice());
+ out
+ }
+}
+
+impl Hasher for Sha3_256 {
+ extern "C" fn update<'a>(&mut self, input: Slice<'a, u8>) {
+ self.ctx.update(input.as_slice());
+ }
+
+ extern "C" fn finalize(&mut self) -> BoxedSlice<u8> {
+ BoxedSlice::from(&self.digest()[..])
+ }
+}
+
+/// **Functional** — delegates to `mock_sha3::Keccak512` (software Keccak-512).
+pub struct Keccak512 {
+ ctx: Keccak512_impl,
+}
+
+impl Keccak512 {
+ /// A hasher fed with `data`, if given.
+ pub fn new(data: Option<&[u8]>) -> Self {
+ let ctx = Keccak512_impl::new();
+ let mut hasher = Self { ctx };
+ if let Some(data) = data {
+ hasher.ctx.update(data);
+ }
+ hasher
+ }
+
+ /// Returns the digest.
+ pub fn digest(&mut self) -> [u8; 64] {
+ let mut out = [0u8; 64];
+ out.copy_from_slice(self.ctx.clone().finalize_fixed().as_slice());
+ out
+ }
+}
+
+impl Hasher for Keccak512 {
+ extern "C" fn update<'a>(&mut self, input: Slice<'a, u8>) {
+ self.ctx.update(input.as_slice());
+ }
+
+ extern "C" fn finalize(&mut self) -> BoxedSlice<u8> {
+ BoxedSlice::from(&self.digest()[..])
+ }
+}
+
+/// **Functional** — delegates to `mock_sha3::Sha3_512` (software SHA3-512).
+pub struct Sha3_512 {
+ ctx: Sha3_512_impl,
+}
+
+impl Sha3_512 {
+ /// A hasher fed with `data`, if given.
+ pub fn new(data: Option<&[u8]>) -> Self {
+ let ctx = Sha3_512_impl::new();
+ let mut hasher = Self { ctx };
+ if let Some(data) = data {
+ hasher.ctx.update(data);
+ }
+ hasher
+ }
+
+ /// Returns the digest.
+ pub fn digest(&mut self) -> [u8; 64] {
+ let mut out = [0u8; 64];
+ out.copy_from_slice(self.ctx.clone().finalize_fixed().as_slice());
+ out
+ }
+}
+
+impl Hasher for Sha3_512 {
+ extern "C" fn update<'a>(&mut self, input: Slice<'a, u8>) {
+ self.ctx.update(input.as_slice());
+ }
+
+ extern "C" fn finalize(&mut self) -> BoxedSlice<u8> {
+ BoxedSlice::from(&self.digest()[..])
+ }
+}
+
+// HMAC functions
+
+/// **Functional** — delegates to `mock_hmac_sha256::HMAC` (software HMAC-SHA-256).
+pub struct HmacSha256 {
+ ctx: HMAC256_impl,
+}
+
+impl HmacSha256 {
+ /// An HMAC keyed with `key`, fed with `data`, if given.
+ pub fn new(key: &[u8], data: Option<&[u8]>) -> Self {
+ let ctx = HMAC256_impl::new(key);
+ let mut hasher = Self { ctx };
+ if let Some(data) = data {
+ hasher.ctx.update(data);
+ }
+ hasher
+ }
+
+ /// Returns the digest.
+ pub fn digest(&mut self) -> [u8; 32] {
+ let mut out = [0u8; 32];
+ out.copy_from_slice(self.ctx.clone().finalize().as_slice());
+ out
+ }
+}
+
+impl Hasher for HmacSha256 {
+ extern "C" fn update<'a>(&mut self, input: Slice<'a, u8>) {
+ self.ctx.update(input.as_slice());
+ }
+
+ extern "C" fn finalize(&mut self) -> BoxedSlice<u8> {
+ BoxedSlice::from(&self.digest()[..])
+ }
+}
+
+/// **Functional** — delegates to `mock_hmac_sha512::HMAC` (software HMAC-SHA-512).
+///
+/// Unlike the other mocks here, `hmac_sha512::HMAC` isn't `Clone`, and its
+/// `finalize` consumes `self` — so this wraps it in an `Option`, taken on
+/// [`Self::digest`] (which the [`Hasher`] impl below then calls at most once,
+/// per the same "finalize just once" contract [`Hasher::finalize`] documents).
+pub struct HmacSha512 {
+ ctx: Option<HMAC512_impl>,
+}
+
+impl HmacSha512 {
+ /// An HMAC keyed with `key`, fed with `data`, if given.
+ pub fn new(key: &[u8], data: Option<&[u8]>) -> Self {
+ let mut ctx = HMAC512_impl::new(key);
+ if let Some(data) = data {
+ ctx.update(data);
+ }
+ Self { ctx: Some(ctx) }
+ }
+
+ /// Feeds more input into the HMAC.
+ pub fn update(&mut self, data: &[u8]) {
+ self.ctx
+ .as_mut()
+ .expect("HmacSha512 has been finalized")
+ .update(data);
+ }
+
+ /// Returns the digest. Call it once.
+ pub fn digest(&mut self) -> [u8; 64] {
+ self.ctx
+ .take()
+ .expect("HmacSha512 has been finalized")
+ .finalize()
+ }
+}
+
+impl Hasher for HmacSha512 {
+ extern "C" fn update<'a>(&mut self, input: Slice<'a, u8>) {
+ HmacSha512::update(self, input.as_slice());
+ }
+
+ extern "C" fn finalize(&mut self) -> BoxedSlice<u8> {
+ BoxedSlice::from(&self.digest()[..])
+ }
+}
### sdk/crates/trezor-app-sdk/src/print.rs
@@ -0,0 +1,126 @@
+use core::cell::RefCell;
+
+use stabby::str::Str;
+
+use crate::app_runtime;
+use crate::traits::syslog::{
+ LogCallback, LogCallbackRef, LogLevel, LogRecordDyn, LogRecordRef, StaticSyslogV1, SyslogV1,
+ SyslogV1Dyn as _,
+};
+use crate::traits::util::FastResult;
+
+#[cfg(not(target_os = "none"))]
+mod unix_ffi {
+ use stabby::str::Str;
+
+ use crate::traits::syslog::{
+ LogCallbackDyn as _, LogCallbackRef, LogLevel, LogRecord, SyslogV1,
+ };
+ use crate::traits::util::FastResult;
+
+ const STDOUT_FILENO: cty::c_int = 1;
+
+ unsafe extern "C" {
+ pub unsafe fn write(fd: cty::c_int, buf: *const u8, count: cty::size_t) -> cty::ssize_t;
+ }
+
+ pub fn print(to_log: &str) {
+ // SAFETY: We're passing valid pointers and sizes.
+ unsafe {
+ write(STDOUT_FILENO, to_log.as_ptr(), to_log.len() as cty::size_t);
+ }
+ }
+
+ pub struct UnixLogger;
+
+ impl SyslogV1 for UnixLogger {
+ extern "C" fn log_simple<'a>(&self, _level: LogLevel, message: Str<'a>) {
+ print(message.as_str());
+ }
+ extern "C" fn log<'a>(&self, _level: LogLevel, callback: LogCallbackRef<'a>) {
+ callback.call(self.into());
+ }
+ }
+
+ impl LogRecord for UnixLogger {
+ extern "C" fn write<'a>(&self, string: Str<'a>) -> FastResult<(), ()> {
+ print(string.as_str());
+ Ok(()).into()
+ }
+ }
+}
+
+pub struct NoOutput;
+
+impl SyslogV1 for NoOutput {
+ extern "C" fn log_simple<'a>(&self, _level: LogLevel, _message: Str<'a>) {}
+ extern "C" fn log<'a>(&self, _level: LogLevel, _callback: LogCallbackRef<'a>) {}
+}
+
+pub struct LocalWriter<'a>(LogRecordRef<'a>);
+
+impl LocalWriter<'_> {
+ fn write(&self, s: &str) -> Result<(), ()> {
+ self.0.write(s.into()).into_result()
+ }
+}
+
+impl<'a> ufmt::uWrite for LocalWriter<'a> {
+ type Error = ();
+
+ fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
+ Self::write(self, s)
+ }
+}
+
+fn syslog() -> StaticSyslogV1 {
+ app_runtime::try_get_syslog().unwrap_or_else(fallback_syslog)
+}
+
+// `unix_ffi` only exists off-target (see its `#[cfg]` above), so the choice
+// between it and `NoOutput` has to be a real `#[cfg]` on two functions rather
+// than a runtime `if cfg!(...)` — the latter still type-checks both branches.
+#[cfg(not(target_os = "none"))]
+fn fallback_syslog() -> StaticSyslogV1 {
+ (&unix_ffi::UnixLogger).into()
+}
+
+#[cfg(target_os = "none")]
+fn fallback_syslog() -> StaticSyslogV1 {
+ (&NoOutput).into()
+}
+
+pub fn log_simple(level: LogLevel, message: &str) {
+ syslog().log_simple(level, message.into());
+}
+
+struct FnOnceWrapper<F> {
+ callback: RefCell<Option<F>>,
+}
+
+impl<F> FnOnceWrapper<F> {
+ fn new(callback: F) -> Self {
+ Self {
+ callback: RefCell::new(Some(callback)),
+ }
+ }
+}
+
+impl<F> LogCallback for FnOnceWrapper<F>
+where
+ F: for<'a> FnOnce(LocalWriter<'a>) -> Result<(), ()>,
+{
+ extern "C" fn call<'a>(&self, record: LogRecordRef<'a>) -> FastResult<(), ()> {
+ self.callback
+ .borrow_mut()
+ .take()
+ .map(|callback| callback(LocalWriter(record)))
+ .unwrap_or(Err(()))
+ .into()
+ }
+}
+
+pub fn log(level: LogLevel, callback: impl FnOnce(LocalWriter) -> Result<(), ()>) {
+ let callback = FnOnceWrapper::new(callback);
+ syslog().log(level, (&callback).into());
+}
### sdk/crates/trezor-app-sdk/src/structs.rs
@@ -0,0 +1,1101 @@
+//! Low-level IPC message types for the Trezor UI, Crypto, and Progress interfaces.
+//!
+//! These types are serialized via [`rkyv`] and sent over IPC between the app
+//! and the Core firmware task.
+//!
+//! **Prefer the higher-level `ui`/`crypto`/`progress` modules and each type's
+//! `new()` constructor over building these directly.** Fields are `pub`
+//! despite that, because Core reads them straight off the archived (rkyv)
+//! form with no wrapper API of its own — that's the one legitimate reader
+//! these fields need to stay public for.
+
+use rkyv::boxed::{ArchivedBox, BoxResolver};
+use rkyv::rancor::Fallible;
+use rkyv::ser::Writer;
+use rkyv::{Archive, Deserialize, Place, Serialize, SerializeUnsized};
+use ufmt::derive::uDebug;
+
+/// A key-value pair with an optional monospace flag, used in UI detail views.
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
+pub struct Property<'a> {
+ /// Name of the property.
+ pub key: StrSlice<'a>,
+ /// Value of the property.
+ pub value: StrSlice<'a>,
+ /// Shows the value in a monospace font.
+ pub mono: bool,
+}
+
+impl<'a> Property<'a> {
+ /// A property `key`: `value`, the value in a monospace font if `mono`.
+ pub fn new(key: &'a str, value: &'a str, mono: bool) -> Self {
+ Self {
+ key: key.into(),
+ value: value.into(),
+ mono,
+ }
+ }
+
+ /// A property with its value in a monospace font.
+ pub fn mono(key: &'a str, value: &'a str) -> Self {
+ Self::new(key, value, true)
+ }
+
+ /// A property with its value in the regular font.
+ pub fn plain(key: &'a str, value: &'a str) -> Self {
+ Self::new(key, value, false)
+ }
+}
+
+/// A string with an optional monospace flag, used in UI list views.
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
+pub struct StrExt<'a> {
+ /// The text.
+ pub key: StrSlice<'a>,
+ /// Shows the text in a monospace font.
+ pub mono: bool,
+}
+
+impl<'a> StrExt<'a> {
+ /// A text, in a monospace font if `mono`.
+ pub fn new(key: &'a str, mono: bool) -> Self {
+ Self {
+ key: key.into(),
+ mono,
+ }
+ }
+
+ /// A text in a monospace font.
+ pub fn mono(key: &'a str) -> Self {
+ Self::new(key, true)
+ }
+
+ /// A text in the regular font.
+ pub fn plain(key: &'a str) -> Self {
+ Self::new(key, false)
+ }
+}
+
+/// A borrowed string slice wrapper, serialized as a relative pointer via rkyv.
+/// Used instead of `&str` because rkyv cannot serialize `&str` directly.
+#[derive(Copy, Clone, Default, PartialEq, Eq)]
+pub struct StrSlice<'a> {
+ inner: &'a str,
+}
+
+impl<'a> StrSlice<'a> {
+ /// Borrows `s`.
+ pub fn new(s: &'a str) -> Self {
+ Self { inner: s }
+ }
+
+ /// The borrowed string.
+ pub fn as_str(&self) -> &'a str {
+ self.inner
+ }
+}
+
+// Manual uDebug: ufmt deliberately doesn't implement uDebug for `str` (it
+// would need panic-prone char-escaping logic), so this just writes the raw
+// contents, matching ufmt's own `uDisplay for str` behavior.
+impl<'a> ufmt::uDebug for StrSlice<'a> {
+ fn fmt<W: ?Sized>(&self, f: &mut ufmt::Formatter<'_, W>) -> Result<(), W::Error>
+ where
+ W: ufmt::uWrite,
+ {
+ f.write_str(self.inner)
+ }
+}
+
+impl<'a> From<&'a str> for StrSlice<'a> {
+ fn from(s: &'a str) -> Self {
+ Self::new(s)
+ }
+}
+
+// The archived form of StrSlice is rkyv's own ArchivedBox<str> — a
+// #[repr(transparent)] RelPtr<str> wrapper that already carries a correct
+// CheckBytes/Verify impl, so archived StrSlice values can be read via safe,
+// validated rkyv::access instead of access_unchecked.
+impl<'a> Archive for StrSlice<'a> {
+ type Archived = ArchivedBox<str>;
+ type Resolver = BoxResolver;
+
+ fn resolve(&self, resolver: Self::Resolver, out: Place<Self::Archived>) {
+ ArchivedBox::resolve_from_ref(self.inner, resolver, out)
+ }
+}
+
+// We restrict our serializer types with Writer because we need its
+// capabilities to serialize the inner string. For other types, we might
+// need more or less restrictive bounds on the type of S.
+impl<'a, S: Fallible + Writer + ?Sized> Serialize<S> for StrSlice<'a> {
+ fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
+ ArchivedBox::serialize_from_ref(self.inner, serializer)
+ }
+}
+
+/// A borrowed slice wrapper, serialized as a relative pointer via rkyv.
+/// Used instead of `&[T]` for the same reason as [`StrSlice`].
+pub struct Slice<'a, T: Archive> {
+ inner: &'a [T],
+}
+
+// Manual Copy/Clone: `Slice` only ever copies the borrowed `&'a [T]` itself,
+// never the elements, so it shouldn't require `T: Copy`/`T: Clone` the way a
+// derive would.
+impl<'a, T: Archive> Copy for Slice<'a, T> {}
+
+impl<'a, T: Archive> Clone for Slice<'a, T> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<'a, T: Archive + ufmt::uDebug> ufmt::uDebug for Slice<'a, T> {
+ fn fmt<W: ?Sized>(&self, f: &mut ufmt::Formatter<'_, W>) -> Result<(), W::Error>
+ where
+ W: ufmt::uWrite,
+ {
+ self.inner.fmt(f)
+ }
+}
+
+impl<'a, T: Archive + PartialEq> PartialEq for Slice<'a, T> {
+ fn eq(&self, other: &Self) -> bool {
+ self.inner == other.inner
+ }
+}
+
+impl<'a, T: Archive + Eq> Eq for Slice<'a, T> {}
+
+impl<'a, T: Archive> Slice<'a, T> {
+ /// Borrows `s`.
+ pub fn new(s: &'a [T]) -> Self {
+ Self { inner: s }
+ }
+
+ /// The borrowed slice.
+ pub fn as_slice(&self) -> &'a [T] {
+ self.inner
+ }
+
+ /// Number of elements.
+ pub fn len(&self) -> usize {
+ self.inner.len()
+ }
+
+ /// Whether there are no elements.
+ pub fn is_empty(&self) -> bool {
+ self.inner.is_empty()
+ }
+
+ /// The element at `index`, if any.
+ pub fn get(&self, index: usize) -> Option<&T> {
+ self.inner.get(index)
+ }
+}
+
+impl<'a, T: Archive> From<&'a [T]> for Slice<'a, T> {
+ fn from(s: &'a [T]) -> Self {
+ Self::new(s)
+ }
+}
+
+// The archived form of Slice<T> is rkyv's own ArchivedBox<[T::Archived]> —
+// same rationale as StrSlice above: reuses rkyv's existing CheckBytes/Verify
+// impl for unsized RelPtr pointees instead of hand-rolling one.
+impl<'a, T: Archive> Archive for Slice<'a, T> {
+ type Archived = ArchivedBox<[T::Archived]>;
+ type Resolver = BoxResolver;
+
+ fn resolve(&self, resolver: Self::Resolver, out: Place<Self::Archived>) {
+ ArchivedBox::resolve_from_ref(self.inner, resolver, out)
+ }
+}
+
+impl<'a, T: Archive, S: Fallible + Writer + ?Sized> Serialize<S> for Slice<'a, T>
+where
+ [T]: SerializeUnsized<S>,
+{
+ fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
+ ArchivedBox::serialize_from_ref(self.inner, serializer)
+ }
+}
+
+/// A menu of selectable string items.
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct SelectMenu<'a> {
+ /// Entries shown on the screen.
+ pub items: Slice<'a, StrSlice<'a>>,
+ /// Label of the cancel entry, if any.
+ pub cancel: Option<StrSlice<'a>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+impl<'a> SelectMenu<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(items: &'a [StrSlice<'a>], cancel: Option<&'a str>, br_code: i32) -> SelectMenu<'a> {
+ SelectMenu {
+ items: items.into(),
+ cancel: cancel.map(|s| s.into()),
+ br_code,
+ }
+ }
+}
+
+/// A trade confirmation screen, shown via [`crate::ui::confirm_trade`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ConfirmTrade<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// Subtitle under the title.
+ pub subtitle: StrSlice<'a>,
+ /// What the user gets.
+ pub buy: StrSlice<'a>,
+ /// What the user gives.
+ pub sell: Option<StrSlice<'a>>,
+ /// The left button returns `Back` instead of cancelling.
+ pub back_button: bool,
+ /// Button request name sent to the host.
+ pub br_name: Option<StrSlice<'a>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+impl<'a> ConfirmTrade<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ subtitle: &'a str,
+ buy: &'a str,
+ sell: Option<&'a str>,
+ back_button: bool,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> ConfirmTrade<'a> {
+ ConfirmTrade {
+ title: title.into(),
+ subtitle: subtitle.into(),
+ buy: buy.into(),
+ sell: sell.map(|s| s.into()),
+ back_button,
+ br_name: br_name.map(|s| s.into()),
+ br_code,
+ }
+ }
+}
+
+/// An action confirmation screen, shown via [`crate::ui::confirm_action`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ConfirmAction<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// The action to confirm.
+ pub action: StrSlice<'a>,
+ /// Description text.
+ pub description: Option<StrSlice<'a>>,
+ /// Subtitle under the title.
+ pub subtitle: Option<StrSlice<'a>>,
+ /// The user confirms by holding the button.
+ pub hold: bool,
+ /// Shows a cancel button.
+ pub cancel: bool,
+ /// Text of the confirm button.
+ pub verb: Option<StrSlice<'a>>,
+ /// Button request name sent to the host.
+ pub br_name: Option<StrSlice<'a>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+ /// The menu button returns `Info` to the app instead of opening Core's menu.
+ pub external_menu: bool,
+}
+
+impl<'a> ConfirmAction<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ action: &'a str,
+ description: Option<&'a str>,
+ subtitle: Option<&'a str>,
+ hold: bool,
+ verb: Option<&'a str>,
+ cancel: bool,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ external_menu: bool,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ action: action.into(),
+ description: description.map(|s| s.into()),
+ subtitle: subtitle.map(|s| s.into()),
+ hold,
+ cancel,
+ verb: verb.map(|s| s.into()),
+ br_name: br_name.map(|s| s.into()),
+ br_code,
+ external_menu,
+ }
+ }
+}
+
+/// A transaction summary confirmation screen, shown via [`crate::ui::confirm_summary`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ConfirmSummary<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// The amount.
+ pub amount: Option<StrSlice<'a>>,
+ /// Label of the amount.
+ pub amount_label: Option<StrSlice<'a>>,
+ /// The fee.
+ pub fee: StrSlice<'a>,
+ /// Label of the fee.
+ pub fee_label: StrSlice<'a>,
+ /// Title of the account information.
+ pub account_title: Option<StrSlice<'a>>,
+ /// Account information as key-value pairs.
+ pub account_items: Option<Slice<'a, Property<'a>>>,
+ /// Title of the extra information.
+ pub extra_title: Option<StrSlice<'a>>,
+ /// Extra information as key-value pairs.
+ pub extra_items: Option<Slice<'a, Property<'a>>>,
+ /// The left button returns `Back` instead of cancelling.
+ pub back_button: bool,
+ /// Button request name sent to the host.
+ pub br_name: Option<StrSlice<'a>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+impl<'a> ConfirmSummary<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ amount: Option<&'a str>,
+ amount_label: Option<&'a str>,
+ fee: &'a str,
+ fee_label: &'a str,
+ account_title: Option<&'a str>,
+ account_items: Option<&'a [Property<'a>]>,
+ extra_title: Option<&'a str>,
+ extra_items: Option<&'a [Property<'a>]>,
+ back_button: bool,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ amount: amount.map(|s| s.into()),
+ amount_label: amount_label.map(|s| s.into()),
+ fee: fee.into(),
+ fee_label: fee_label.into(),
+ account_title: account_title.map(|s| s.into()),
+ account_items: account_items.map(|s| s.into()),
+ extra_title: extra_title.map(|s| s.into()),
+ extra_items: extra_items.map(|s| s.into()),
+ back_button,
+ br_name: br_name.map(|s| s.into()),
+ br_code,
+ }
+ }
+}
+
+/// A value confirmation screen, shown via [`crate::ui::confirm_value`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ConfirmValue<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// The value to confirm.
+ pub value: StrSlice<'a>,
+ /// Description text.
+ pub description: Option<StrSlice<'a>>,
+ /// The value is data, shown in a data font.
+ pub is_data: bool,
+ /// Subtitle under the title.
+ pub subtitle: Option<StrSlice<'a>>,
+ /// Text of the confirm button.
+ pub verb: Option<StrSlice<'a>>,
+ /// Shows an info button in the header.
+ pub info: bool,
+ /// The user confirms by holding the button.
+ pub hold: bool,
+ /// Shows the value in monospace chunks, for easier comparison.
+ pub chunkify: bool,
+ /// Shows a page counter.
+ pub page_counter: bool,
+ /// Shows a cancel button.
+ pub cancel: bool,
+ /// Button request name sent to the host.
+ pub br_name: Option<StrSlice<'a>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+ /// The menu button returns `Info` to the app instead of opening Core's menu.
+ pub external_menu: bool,
+ /// Footer text, and whether it is bold.
+ pub footer: Option<(StrSlice<'a>, bool)>,
+}
+
+impl<'a> ConfirmValue<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ content: &'a str,
+ description: Option<&'a str>,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ is_data: bool,
+ verb: Option<&'a str>,
+ subtitle: Option<&'a str>,
+ info: bool,
+ hold: bool,
+ chunkify: bool,
+ page_counter: bool,
+ cancel: bool,
+ external_menu: bool,
+ footer: Option<(&'a str, bool)>,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ value: content.into(),
+ description: description.map(|s| s.into()),
+ is_data,
+ subtitle: subtitle.map(|s| s.into()),
+ verb: verb.map(|s| s.into()),
+ info,
+ hold,
+ chunkify,
+ page_counter,
+ cancel,
+ br_name: br_name.map(|s| s.into()),
+ br_code,
+ external_menu,
+ footer: footer.map(|(s, b)| (s.into(), b)),
+ }
+ }
+}
+
+/// An intro screen shown before [`ConfirmValue`], via [`crate::ui::confirm_value_intro`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ConfirmValueIntro<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// The value to confirm.
+ pub value: StrSlice<'a>,
+ /// Subtitle under the title.
+ pub subtitle: Option<StrSlice<'a>>,
+ /// Text of the confirm button.
+ pub verb: Option<StrSlice<'a>>,
+ /// Text of the cancel button.
+ pub verb_cancel: Option<StrSlice<'a>>,
+ /// Text of the button that shows the whole value.
+ pub verb_view_all: Option<StrSlice<'a>>,
+ /// The user confirms by holding the button.
+ pub hold: bool,
+ /// Shows the value in monospace chunks, for easier comparison.
+ pub chunkify: bool,
+ /// Button request name sent to the host.
+ pub br_name: Option<StrSlice<'a>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+impl<'a> ConfirmValueIntro<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ value: &'a str,
+ subtitle: Option<&'a str>,
+ verb: Option<&'a str>,
+ verb_cancel: Option<&'a str>,
+ verb_view_all: Option<&'a str>,
+ hold: bool,
+ chunkify: bool,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ value: value.into(),
+ subtitle: subtitle.map(|s| s.into()),
+ verb: verb.map(|s| s.into()),
+ verb_cancel: verb_cancel.map(|s| s.into()),
+ verb_view_all: verb_view_all.map(|s| s.into()),
+ hold,
+ chunkify,
+ br_name: br_name.map(|s| s.into()),
+ br_code,
+ }
+ }
+}
+
+/// A warning screen, shown via [`crate::ui::show_warning`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ShowWarning<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// Body text.
+ pub content: StrSlice<'a>,
+ /// Text of the confirm button.
+ pub verb: StrSlice<'a>,
+ /// Button request name sent to the host.
+ pub br_name: Option<StrSlice<'a>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+ /// Lets the user cancel.
+ pub allow_cancel: bool,
+ /// Shows the screen as dangerous.
+ pub danger: bool,
+}
+
+impl<'a> ShowWarning<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ content: &'a str,
+ verb: &'a str,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ allow_cancel: bool,
+ danger: bool,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ content: content.into(),
+ verb: verb.into(),
+ br_name: br_name.map(|s| s.into()),
+ br_code,
+ allow_cancel,
+ danger,
+ }
+ }
+}
+
+/// A mismatch warning screen, shown via [`crate::ui::show_mismatch`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ShowMismatch<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+impl<'a> ShowMismatch<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(title: &'a str, br_code: i32) -> Self {
+ Self {
+ title: title.into(),
+ br_code,
+ }
+ }
+}
+
+/// A danger warning screen, shown via [`crate::ui::show_danger`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ShowDanger<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// Body text.
+ pub content: StrSlice<'a>,
+ /// Button request name sent to the host.
+ pub br_name: Option<StrSlice<'a>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+ /// Text of the cancel button.
+ pub verb_cancel: Option<StrSlice<'a>>,
+ /// Title of the menu.
+ pub menu_title: Option<StrSlice<'a>>,
+}
+
+impl<'a> ShowDanger<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ content: &'a str,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ verb_cancel: Option<&'a str>,
+ menu_title: Option<&'a str>,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ content: content.into(),
+ br_name: br_name.map(|s| s.into()),
+ br_code,
+ verb_cancel: verb_cancel.map(|s| s.into()),
+ menu_title: menu_title.map(|s| s.into()),
+ }
+ }
+}
+
+/// A success screen, shown via [`crate::ui::show_success`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ShowSuccess<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// Body text.
+ pub content: StrSlice<'a>,
+ /// Text of the button.
+ pub button: StrSlice<'a>,
+ /// Closes the screen after this many milliseconds.
+ pub duration_ms: Option<u32>,
+ /// Button request name sent to the host.
+ pub br_name: Option<StrSlice<'a>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+impl<'a> ShowSuccess<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ content: &'a str,
+ button: &'a str,
+ duration_ms: Option<u32>,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ content: content.into(),
+ button: button.into(),
+ duration_ms,
+ br_name: br_name.map(|s| s.into()),
+ br_code,
+ }
+ }
+}
+
+/// A number-entry screen, shown via [`crate::ui::request_number`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct RequestNumber<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// Body text.
+ pub content: StrSlice<'a>,
+ /// Number shown at first.
+ pub initial: u32,
+ /// Smallest allowed number.
+ pub min: u32,
+ /// Largest allowed number.
+ pub max: u32,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+impl<'a> RequestNumber<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ content: &'a str,
+ initial: u32,
+ min: u32,
+ max: u32,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ content: content.into(),
+ initial,
+ min,
+ max,
+ br_code,
+ }
+ }
+}
+
+/// A property-list confirmation screen, shown via [`crate::ui::confirm_properties`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ConfirmProperties<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// Properties shown as key-value pairs.
+ pub props: Slice<'a, Property<'a>>,
+ /// Subtitle under the title.
+ pub subtitle: Option<StrSlice<'a>>,
+ /// Text of the confirm button.
+ pub verb: Option<StrSlice<'a>>,
+ /// The user confirms by holding the button.
+ pub hold: bool,
+ /// Button request name sent to the host.
+ pub br_name: Option<StrSlice<'a>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+ /// The menu button returns `Info` to the app instead of opening Core's menu.
+ pub external_menu: bool,
+}
+
+impl<'a> ConfirmProperties<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ props: &'a [Property<'a>],
+ subtitle: Option<&'a str>,
+ verb: Option<&'a str>,
+ hold: bool,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ external_menu: bool,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ props: props.into(),
+ subtitle: subtitle.map(|s| s.into()),
+ verb: verb.map(|s| s.into()),
+ hold,
+ br_name: br_name.map(|s| s.into()),
+ br_code,
+ external_menu,
+ }
+ }
+}
+
+/// A property-list display screen (no confirmation), shown via [`crate::ui::show_properties`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ShowProperties<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// Properties shown as key-value pairs.
+ pub props: Slice<'a, Property<'a>>,
+ /// Subtitle under the title.
+ pub subtitle: Option<StrSlice<'a>>,
+ /// Button request name sent to the host.
+ pub br_name: Option<StrSlice<'a>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+impl<'a> ShowProperties<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ props: &'a [Property<'a>],
+ subtitle: Option<&'a str>,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ props: props.into(),
+ subtitle: subtitle.map(|s| s.into()),
+ br_name: br_name.map(|s| s.into()),
+ br_code,
+ }
+ }
+}
+
+/// A public key display screen, shown via [`crate::ui::show_public_key`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ShowPublicKey<'a> {
+ /// The public key.
+ pub pubkey: StrSlice<'a>,
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// Account name shown with the key.
+ pub account: Option<StrSlice<'a>>,
+ /// Derivation path shown with the key.
+ pub path: Option<StrSlice<'a>>,
+ /// Warning text.
+ pub warning: Option<StrSlice<'a>>,
+ /// Button request name sent to the host.
+ pub br_name: StrSlice<'a>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+impl<'a> ShowPublicKey<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ pubkey: &'a str,
+ title: &'a str,
+ account: Option<&'a str>,
+ path: Option<&'a str>,
+ warning: Option<&'a str>,
+ br_name: &'a str,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ pubkey: pubkey.into(),
+ title: title.into(),
+ account: account.map(|s| s.into()),
+ path: path.map(|s| s.into()),
+ warning: warning.map(|s| s.into()),
+ br_name: br_name.into(),
+ br_code,
+ }
+ }
+}
+
+/// An info screen with a cancel option, shown via [`crate::ui::show_info_with_cancel`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ShowInfoWithCancel<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// Entries shown on the screen.
+ pub items: Slice<'a, Property<'a>>,
+ /// Shows the value in monospace chunks, for easier comparison.
+ pub chunkify: bool,
+ /// Button request name sent to the host.
+ pub br_name: Option<StrSlice<'a>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+impl<'a> ShowInfoWithCancel<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ items: &'a [Property<'a>],
+ chunkify: bool,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ items: items.into(),
+ chunkify,
+ br_name: br_name.map(|s| s.into()),
+ br_code,
+ }
+ }
+}
+/// A confirmation screen with an extra info button, shown via [`crate::ui::confirm_with_info`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ConfirmWithInfo<'a> {
+ /// Screen title.
+ pub title: StrSlice<'a>,
+ /// Subtitle under the title.
+ pub subtitle: Option<StrSlice<'a>>,
+ /// Entries shown on the screen.
+ pub items: Slice<'a, StrExt<'a>>,
+ /// Text of the confirm button.
+ pub verb: StrSlice<'a>,
+ /// Text of the info button.
+ pub verb_info: Option<StrSlice<'a>>,
+ /// Button request name sent to the host.
+ pub br_name: Option<StrSlice<'a>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+impl ConfirmWithInfo<'_> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new<'a>(
+ title: &'a str,
+ subtitle: Option<&'a str>,
+ items: &'a [StrExt<'a>],
+ verb: &'a str,
+ verb_info: Option<&'a str>,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> ConfirmWithInfo<'a> {
+ ConfirmWithInfo {
+ title: title.into(),
+ subtitle: subtitle.map(|s| s.into()),
+ items: items.into(),
+ verb: verb.into(),
+ verb_info: verb_info.map(|s| s.into()),
+ br_name: br_name.map(|s| s.into()),
+ br_code,
+ }
+ }
+}
+
+/// An address display screen, shown via [`crate::ui::show_address`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub struct ShowAddress<'a> {
+ /// The address.
+ pub address: StrSlice<'a>,
+ /// The address as encoded in the QR code.
+ pub address_qr: StrSlice<'a>,
+ /// Screen title.
+ pub title: Option<StrSlice<'a>>,
+ /// Subtitle under the title.
+ pub subtitle: Option<StrSlice<'a>>,
+ /// Account name shown with the address.
+ pub account: Option<StrSlice<'a>>,
+ /// Derivation path shown with the address.
+ pub path: Option<StrSlice<'a>>,
+ /// Extended public keys of a multisig address.
+ pub xpubs: Slice<'a, Property<'a>>,
+ /// Shows the value in monospace chunks, for easier comparison.
+ pub chunkify: bool,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+ /// The address is case-sensitive.
+ pub case_sensitive: bool,
+}
+
+impl ShowAddress<'_> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new<'a>(
+ address: &'a str,
+ address_qr: &'a str,
+ title: Option<&'a str>,
+ subtitle: Option<&'a str>,
+ account: Option<&'a str>,
+ path: Option<&'a str>,
+ xpubs: &'a [Property<'a>],
+ chunkify: bool,
+ br_code: i32,
+ case_sensitive: bool,
+ ) -> ShowAddress<'a> {
+ ShowAddress {
+ address: address.into(),
+ address_qr: address_qr.into(),
+ title: title.map(|s| s.into()),
+ subtitle: subtitle.map(|s| s.into()),
+ account: account.map(|s| s.into()),
+ path: path.map(|s| s.into()),
+ xpubs: xpubs.into(),
+ chunkify,
+ br_code,
+ case_sensitive,
+ }
+ }
+}
+
+/// All UI screens that can be requested from the app via IPC.
+///
+/// Each variant corresponds to one screen type in the Trezor UI. Constructed
+/// by the higher-level `ui` module — do not construct variants directly.
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize)]
+pub enum TrezorUiEnum<'a> {
+ /// A [`SelectMenu`] screen.
+ SelectMenu(SelectMenu<'a>),
+ /// A [`ConfirmTrade`] screen.
+ ConfirmTrade(ConfirmTrade<'a>),
+ /// A [`ConfirmAction`] screen.
+ ConfirmAction(ConfirmAction<'a>),
+ /// A [`ConfirmSummary`] screen.
+ ConfirmSummary(ConfirmSummary<'a>),
+ /// A [`ConfirmValue`] screen.
+ ConfirmValue(ConfirmValue<'a>),
+ /// A [`ConfirmValueIntro`] screen.
+ ConfirmValueIntro(ConfirmValueIntro<'a>),
+ /// A [`ShowWarning`] screen.
+ ShowWarning(ShowWarning<'a>),
+ /// A [`ShowMismatch`] screen.
+ ShowMismatch(ShowMismatch<'a>),
+ /// A [`ShowDanger`] screen.
+ ShowDanger(ShowDanger<'a>),
+ /// A [`ShowSuccess`] screen.
+ ShowSuccess(ShowSuccess<'a>),
+ /// A [`RequestNumber`] screen.
+ RequestNumber(RequestNumber<'a>),
+ /// A [`ConfirmProperties`] screen.
+ ConfirmProperties(ConfirmProperties<'a>),
+ /// A [`ShowProperties`] screen.
+ ShowProperties(ShowProperties<'a>),
+ /// A [`ShowPublicKey`] screen.
+ ShowPublicKey(ShowPublicKey<'a>),
+ /// A [`ShowInfoWithCancel`] screen.
+ ShowInfoWithCancel(ShowInfoWithCancel<'a>),
+ /// A [`ConfirmWithInfo`] screen.
+ ConfirmWithInfo(ConfirmWithInfo<'a>),
+ /// A [`ShowAddress`] screen.
+ ShowAddress(ShowAddress<'a>),
+}
+
+/// Result returned by the Core task after a UI interaction.
+#[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
+pub enum TrezorUiResult {
+ /// The user confirmed.
+ Confirmed,
+ /// The user went back.
+ Back,
+ /// The user cancelled.
+ Cancelled,
+ /// The user asked for more information.
+ Info,
+ /// The number the user entered.
+ Integer(u32),
+}
+
+pub use progress::TrezorProgressEnum;
+
+// rkyv derives a resolver whose variant fields carry no docs
+#[allow(missing_docs)]
+mod progress {
+ use super::*;
+
+ /// Progress bar operations that can be requested from the app via IPC.
+ ///
+ /// Constructed by the higher-level `progress` module — do not construct variants directly.
+ #[derive(uDebug, Copy, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
+ pub enum TrezorProgressEnum<'a> {
+ /// Show a progress indicator.
+ Init {
+ /// Description text.
+ description: Option<StrSlice<'a>>,
+ /// Title.
+ title: Option<StrSlice<'a>>,
+ /// The progress has no known value; shows an animation instead.
+ indeterminate: bool,
+ /// Shows the indicator as dangerous.
+ danger: bool,
+ },
+ /// Update the progress indicator.
+ Update {
+ /// New description text.
+ description: Option<StrSlice<'a>>,
+ /// Progress, from 0 to 1000.
+ value: u32,
+ },
+ /// Close the progress indicator.
+ End,
+ }
+
+ impl<'a> TrezorProgressEnum<'a> {
+ /// The IPC message id of the request.
+ pub fn id(&self) -> u16 {
+ match self {
+ TrezorProgressEnum::Init { .. } => 0,
+ TrezorProgressEnum::Update { .. } => 1,
+ TrezorProgressEnum::End => 2,
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Ensures every variant of TrezorProgressEnum has a unique id()
+ /// and that no variant is accidentally forgotten.
+ #[test]
+ fn progress_ids_are_unique_and_exhaustive() {
+ use TrezorProgressEnum::*;
+ let variants: &[(u16, &str)] = &[
+ (
+ Init {
+ description: None,
+ title: None,
+ indeterminate: false,
+ danger: false,
+ }
+ .id(),
+ "Init",
+ ),
+ (
+ Update {
+ description: None,
+ value: 0,
+ }
+ .id(),
+ "Update",
+ ),
+ (End.id(), "End"),
+ ];
+ // all IDs must be unique
+ let mut seen = std::collections::HashSet::new();
+ for (id, name) in variants {
+ assert!(seen.insert(id), "duplicate id {} for variant {}", id, name);
+ }
+ // total count must match — add new variants here when extending the enum
+ assert_eq!(variants.len(), 3, "new variant added but test not updated");
+ }
+}
### sdk/crates/trezor-app-sdk/src/traits/allocator.rs
@@ -0,0 +1,54 @@
+use core::alloc::Layout;
+
+/// A stable-ABI [`Layout`]: size and alignment of an allocation.
+#[stabby::stabby]
+#[repr(C)]
+pub struct FfiLayout {
+ size: usize,
+ align: usize,
+}
+
+impl From<Layout> for FfiLayout {
+ fn from(layout: Layout) -> Self {
+ Self {
+ size: layout.size(),
+ align: layout.align(),
+ }
+ }
+}
+
+impl From<FfiLayout> for Layout {
+ fn from(layout: FfiLayout) -> Self {
+ unsafe { Layout::from_size_align_unchecked(layout.size, layout.align) }
+ }
+}
+
+#[stabby::stabby(checked)]
+/// Heap allocation for an app, served by Core from the app's heap region.
+///
+/// # Safety
+///
+/// Implementations must uphold the [`GlobalAlloc`](core::alloc::GlobalAlloc) contract.
+pub unsafe trait GlobalAllocatorV1: Send + Sync {
+ /// Allocates memory for `layout`; null on failure.
+ unsafe extern "C" fn alloc(&self, layout: FfiLayout) -> *mut u8;
+
+ /// Frees memory previously allocated with `layout`.
+ unsafe extern "C" fn dealloc(&self, ptr: *mut u8, layout: FfiLayout);
+
+ /// Like [`Self::alloc`], with the memory zeroed.
+ unsafe extern "C" fn alloc_zeroed(&self, layout: FfiLayout) -> *mut u8;
+
+ /// Resizes an allocation to `new_size` bytes; null on failure.
+ unsafe extern "C" fn realloc(
+ &self,
+ ptr: *mut u8,
+ layout: FfiLayout,
+ new_size: usize,
+ ) -> *mut u8;
+}
+
+/// The stabby vtable of [`GlobalAllocatorV1`].
+pub type GlobalAllocatorV1Vtable = stabby::vtable!(GlobalAllocatorV1 + Send + Sync);
+/// A borrowed `dyn GlobalAllocatorV1`.
+pub type GlobalAllocatorV1Ref<'a> = stabby::DynRef<'a, GlobalAllocatorV1Vtable>;
### sdk/crates/trezor-app-sdk/src/traits/crypto.rs
@@ -0,0 +1,232 @@
+use stabby::alloc::string::String;
+use stabby::boxed::{Box, BoxedSlice};
+use stabby::slice::Slice;
+use stabby::str::Str;
+
+use super::util::{FastResult, ServiceResult};
+
+/// Length of [`CryptoV1::get_xpub`]'s result: a serialized xpub without its
+/// 4-byte version.
+pub const XPUB_RAW_LEN: usize = 74;
+
+/// Errors of the cryptographic functions.
+#[stabby::stabby]
+#[repr(u8)]
+pub enum CryptoError {
+ /// The public key is invalid or in an unsupported form.
+ InvalidPublicKey,
+ /// The signature does not verify.
+ InvalidSignature,
+ /// The input is not valid in the expected encoding.
+ InvalidEncoding,
+}
+
+#[stabby::stabby(checked)]
+/// A streaming hash or HMAC computation, see [`CryptoV1::get_hasher`].
+pub trait Hasher {
+ /// Feeds more input into the hash state.
+ extern "C" fn update<'a>(&mut self, input: Slice<'a, u8>);
+
+ /// Returns the digest. Call it once; Core panics on any later use.
+ extern "C" fn finalize(&mut self) -> BoxedSlice<u8>;
+}
+
+/// An owned `dyn Hasher`.
+pub type BoxedHasher = stabby::dynptr!(Box<dyn Hasher>);
+
+/// Hash functions for [`CryptoV1::get_hasher`].
+#[stabby::stabby]
+#[repr(u8)]
+pub enum HashingAlgorithm {
+ /// SHA-256.
+ Sha256,
+ /// SHA3-256.
+ Sha3_256,
+ /// SHA-512.
+ Sha512,
+ /// Keccak-256, as used by Ethereum.
+ Keccak256,
+ /// SHA3-512.
+ Sha3_512,
+ /// Keccak-512.
+ Keccak512,
+}
+
+/// Algorithms accepted by [`CryptoV1::get_hmac`]. A separate (smaller) enum
+/// from [`HashingAlgorithm`] since HMAC is only defined here over the SHA-2
+/// family, not SHA-3/Keccak.
+#[stabby::stabby]
+#[repr(u8)]
+pub enum HmacAlgorithm {
+ /// HMAC-SHA256.
+ Sha256,
+ /// HMAC-SHA512.
+ Sha512,
+}
+
+/// ECDSA curves. Their values match [`Curve`]'s.
+#[stabby::stabby]
+#[repr(u8)]
+pub enum EcdsaCurve {
+ /// secp256k1.
+ Secp256k1 = 0,
+ /// NIST P-256.
+ Nist256p1 = 1,
+}
+
+/// Curves to derive keys on. Core only allows the ones in the app's manifest.
+#[stabby::stabby]
+#[repr(u8)]
+pub enum Curve {
+ /// secp256k1.
+ Secp256k1 = 0,
+ /// NIST P-256.
+ Nist256p1 = 1,
+ /// Ed25519.
+ Ed25519 = 2,
+ /// Curve25519.
+ Curve25519 = 3,
+}
+
+/// Extra constraint on a secp256k1 signature, matching trezor-crypto's
+/// `is_canonical` callbacks. Core keeps re-signing until the signature
+/// satisfies it.
+#[stabby::stabby]
+#[repr(u8)]
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum CanonicalSig {
+ /// Any valid signature.
+ Any = 0,
+ /// Ethereum's: the recovery id fits in one bit, and `s` is low.
+ Ethereum = 1,
+}
+
+#[stabby::stabby(checked)]
+/// Cryptography: key derivation and signing through Core, and local hashing,
+/// verification and encodings.
+pub trait CryptoV1: Send + Sync {
+ /// Starts a hash computation with `algorithm`.
+ extern "C" fn get_hasher(&self, algorithm: HashingAlgorithm) -> BoxedHasher;
+
+ /// Starts an HMAC computation (over `algorithm`, one of the SHA-2
+ /// family) under `key`. `key` is only read during this call (copied into
+ /// the HMAC context's internal state); Core never retains it afterward.
+ extern "C" fn get_hmac<'a>(&self, algorithm: HmacAlgorithm, key: Slice<'a, u8>) -> BoxedHasher;
+
+ /// Derives the public node for `address_n` on `curve`, as a serialized
+ /// xpub without its version: depth (1), parent fingerprint (4), child
+ /// number (4), chain code (32) and compressed public key (33).
+ extern "C" fn get_xpub<'a>(
+ &self,
+ curve: Curve,
+ address_n: Slice<'a, u32>,
+ ) -> ServiceResult<[u8; XPUB_RAW_LEN], CryptoError>;
+
+ /// Derives the public key for `address_n` on `curve`.
+ extern "C" fn get_public_key<'a>(
+ &self,
+ curve: Curve,
+ address_n: Slice<'a, u32>,
+ compressed: bool,
+ ) -> ServiceResult<BoxedSlice<u8>, CryptoError>;
+
+ /// Signs a raw 32-byte digest with the ECDSA key at `address_n`; Ed25519
+ /// has no digest signing, see [`Self::ed25519_sign`].
+ ///
+ /// `canonical` is only supported on secp256k1; any other curve rejects
+ /// anything but [`CanonicalSig::Any`].
+ extern "C" fn ecdsa_sign_digest<'a>(
+ &self,
+ curve: EcdsaCurve,
+ address_n: Slice<'a, u32>,
+ digest: &'a [u8; 32],
+ compressed: bool,
+ canonical: CanonicalSig,
+ ) -> ServiceResult<[u8; 65], CryptoError>;
+
+ /// Signs `message` with the Ed25519 key at `address_n`.
+ extern "C" fn ed25519_sign<'a>(
+ &self,
+ address_n: Slice<'a, u32>,
+ message: Slice<'a, u8>,
+ ) -> ServiceResult<[u8; 64], CryptoError>;
+
+ /// Verifies a MAC previously produced by [`Self::get_address_mac`] for
+ /// `address_n`, `address` and the coin type `slip44`, confirming the
+ /// pairing hasn't been tampered with. Fails on a wrong MAC.
+ extern "C" fn check_address_mac<'a>(
+ &self,
+ address_n: Slice<'a, u32>,
+ mac: &'a [u8; 32],
+ address: Str<'a>,
+ slip44: u32,
+ ) -> ServiceResult<(), CryptoError>;
+
+ /// Computes a MAC binding `address_n` to `address` of the coin type
+ /// `slip44`, so a cached `address` can later be re-authenticated via
+ /// [`Self::check_address_mac`] without a full re-derivation.
+ extern "C" fn get_address_mac<'a>(
+ &self,
+ address_n: Slice<'a, u32>,
+ address: Str<'a>,
+ slip44: u32,
+ ) -> ServiceResult<[u8; 32], CryptoError>;
+
+ /// Verifies a 64-byte `r||s` ECDSA `signature` of `digest` against
+ /// `public_key`, given in compressed or uncompressed SEC1 form.
+ extern "C" fn ecdsa_verify_digest<'a>(
+ &self,
+ curve: EcdsaCurve,
+ public_key: Slice<'a, u8>,
+ signature: Slice<'a, u8>,
+ digest: Slice<'a, u8>,
+ ) -> FastResult<(), CryptoError>;
+
+ /// Recovers the uncompressed public key from an ECDSA `signature` over
+ /// `digest`, with no candidate public key to check against (unlike
+ /// [`Self::ecdsa_verify_digest`], which confirms `signature` matches a
+ /// given key — this instead always returns whichever key the signature's
+ /// own recovery id points to). `signature` is 65 bytes: a 1-byte recovery
+ /// id (`0..=3`) followed by the 64-byte `r||s` signature (Trezor's
+ /// `[v, r, s]` convention).
+ extern "C" fn ecdsa_recover_pubkey<'a>(
+ &self,
+ curve: EcdsaCurve,
+ signature: Slice<'a, u8>,
+ digest: Slice<'a, u8>,
+ ) -> FastResult<BoxedSlice<u8>, CryptoError>;
+
+ /// Verifies a 64-byte Ed25519 `signature` of `message` against the
+ /// 32-byte `public_key`.
+ extern "C" fn ed25519_verify<'a>(
+ &self,
+ public_key: Slice<'a, u8>,
+ signature: Slice<'a, u8>,
+ message: Slice<'a, u8>,
+ ) -> FastResult<(), CryptoError>;
+
+ /// Base58-encodes `data`.
+ extern "C" fn base58_encode<'a>(&self, data: Slice<'a, u8>) -> String;
+
+ /// Decodes a base58 string.
+ extern "C" fn base58_decode<'a>(
+ &self,
+ data: Str<'a>,
+ ) -> FastResult<BoxedSlice<u8>, CryptoError>;
+
+ /// Base58Check-encodes `data` (base58 plus a 4-byte checksum).
+ extern "C" fn base58check_encode<'a>(&self, data: Slice<'a, u8>) -> String;
+
+ /// Decodes a base58Check string, verifying its checksum.
+ extern "C" fn base58check_decode<'a>(
+ &self,
+ data: Str<'a>,
+ ) -> FastResult<BoxedSlice<u8>, CryptoError>;
+}
+
+/// The stabby vtable of [`CryptoV1`].
+pub type CryptoV1Vtable = stabby::vtable!(CryptoV1 + Send + Sync);
+/// A borrowed `dyn CryptoV1`.
+pub type CryptoV1Ref<'a> = stabby::DynRef<'a, CryptoV1Vtable>;
+/// A `dyn CryptoV1` that lives as long as the app.
+pub type StaticCryptoV1 = CryptoV1Ref<'static>;
### sdk/crates/trezor-app-sdk/src/traits/mod.rs
@@ -0,0 +1,26 @@
+/// Heap allocation provided by Core.
+pub mod allocator;
+/// Cryptography: key derivation, signing, hashing and encodings.
+pub mod crypto;
+/// Logging to Core's system log.
+pub mod syslog;
+/// The root interface that bundles all the others.
+pub mod trezor_v1;
+pub mod ui;
+/// Result types shared by the other interfaces.
+pub mod util;
+/// Messaging with the host.
+pub mod wire;
+
+pub use trezor_v1::{TrezorApiV1, TrezorApiV1Struct};
+
+/// The API Core hands to an app, by version.
+#[stabby::stabby]
+#[repr(C, u8)]
+pub enum ApiVariant {
+ /// Version 1 of the API.
+ V1(&'static TrezorApiV1Struct) = 1,
+}
+
+/// Function Core passes to `applet_main` to get the API of a given version.
+pub type ApiGetter = extern "C" fn(version: u32) -> ApiVariant;
### sdk/crates/trezor-app-sdk/src/traits/syslog.rs
@@ -0,0 +1,54 @@
+use stabby::str::Str;
+
+use super::util::FastResult;
+
+/// Severity of a log message.
+#[stabby::stabby]
+#[repr(u8)]
+pub enum LogLevel {
+ /// An error.
+ Error = 1,
+ /// A warning.
+ Warn = 2,
+ /// Information.
+ Info = 3,
+ /// Debugging output.
+ Debug = 4,
+}
+
+#[stabby::stabby(checked)]
+/// A log line being written, piece by piece.
+pub trait LogRecord {
+ /// Appends `string` to the log line.
+ extern "C" fn write<'a>(&self, string: Str<'a>) -> FastResult<(), ()>;
+}
+
+#[stabby::stabby(checked)]
+/// Writes a log message into the [`LogRecord`] it is given.
+pub trait LogCallback {
+ /// Writes the message into `record`.
+ extern "C" fn call<'a>(&self, record: LogRecordRef<'a>) -> FastResult<(), ()>;
+}
+
+/// A borrowed `dyn LogRecord`.
+pub type LogRecordRef<'a> = stabby::dynptr!(&'a dyn LogRecord);
+/// A borrowed `dyn LogCallback`.
+pub type LogCallbackRef<'a> = stabby::dynptr!(&'a dyn LogCallback);
+
+#[stabby::stabby(checked)]
+/// Logging to Core's system log.
+pub trait SyslogV1: Send + Sync {
+ /// Logs `message` at `level`.
+ extern "C" fn log_simple<'a>(&self, level: LogLevel, message: Str<'a>);
+
+ /// Logs at `level` a message that `callback` writes; skipped without calling
+ /// `callback` if the level is filtered out.
+ extern "C" fn log<'a>(&self, level: LogLevel, callback: LogCallbackRef<'a>);
+}
+
+/// The stabby vtable of [`SyslogV1`].
+pub type SyslogV1Vtable = stabby::vtable!(SyslogV1 + Send + Sync);
+/// A borrowed `dyn SyslogV1`.
+pub type SyslogV1Ref<'a> = stabby::DynRef<'a, SyslogV1Vtable>;
+/// A `dyn SyslogV1` that lives as long as the app.
+pub type StaticSyslogV1 = SyslogV1Ref<'static>;
### sdk/crates/trezor-app-sdk/src/traits/trezor_v1.rs
@@ -0,0 +1,53 @@
+use stabby::str::Str;
+
+use super::allocator::GlobalAllocatorV1Ref;
+use super::crypto::CryptoV1Ref;
+use super::syslog::SyslogV1Ref;
+use super::ui::UiV1Ref;
+use super::wire::WireV1Ref;
+
+#[stabby::stabby(checked)]
+/// System functions of the API: exiting and timing.
+pub trait TrezorApiV1: Send + Sync {
+ /// Ends the app normally.
+ extern "C" fn system_exit(&self) -> !;
+
+ /// Ends the app with an error, reported to the host as an app failure.
+ extern "C" fn system_exit_error<'a>(
+ &self,
+ title: Str<'a>,
+ message: Str<'a>,
+ footer: Str<'a>,
+ ) -> !;
+
+ /// Ends the app on a fatal error at `file`:`line`, e.g. a panic.
+ extern "C" fn system_exit_fatal<'a>(&self, message: Str<'a>, file: Str<'a>, line: u32) -> !;
+
+ /// Milliseconds since the device started.
+ extern "C" fn systick_ms(&self) -> u32;
+
+ /// Sleeps for `timeout_ms` milliseconds.
+ extern "C" fn sleep(&self, timeout_ms: u32);
+}
+
+/// The stabby vtable of [`TrezorApiV1`].
+pub type TrezorApiV1Vtable = stabby::vtable!(TrezorApiV1 + Send + Sync);
+/// A borrowed `dyn TrezorApiV1`.
+pub type TrezorApiV1Ref<'a> = stabby::DynRef<'a, TrezorApiV1Vtable>;
+
+/// Version 1 of the API Core hands to an app: one interface per area.
+#[stabby::stabby]
+pub struct TrezorApiV1Struct {
+ /// System functions.
+ pub api: TrezorApiV1Ref<'static>,
+ /// Heap allocation.
+ pub allocator: GlobalAllocatorV1Ref<'static>,
+ /// Cryptography.
+ pub crypto: CryptoV1Ref<'static>,
+ /// Logging.
+ pub syslog: SyslogV1Ref<'static>,
+ /// Messaging with the host.
+ pub wire: WireV1Ref<'static>,
+ /// User interface.
+ pub ui: UiV1Ref<'static>,
+}
### sdk/crates/trezor-app-sdk/src/traits/ui.rs
@@ -0,0 +1,551 @@
+//! Stable-ABI mirror of `structs.rs`'s UI/progress argument structs.
+//!
+//! `structs.rs` is the wire IDL shared byte-for-byte with Core's Rust+Python
+//! side and isn't itself ABI-stable (`rkyv`-only, not `#[stabby::stabby]`).
+//! These mirror types exist purely so the `UiV1` trait can cross the stable
+//! ABI boundary; `core/embed/api`'s implementation converts a mirror value
+//! into the matching `structs.rs` enum internally before sending it over the
+//! wire.
+//!
+//! Optional string fields are `StabbyOption<Slice<u8>>` (raw bytes), not
+//! `StabbyOption<Str>` — `Str` doesn't propagate niche/determinant info
+//! through its own `Slice<u8>` wrapper, so `stabby::option::Option<Str<'_>>`
+//! fails to satisfy `#[stabby::stabby]`'s `IDeterminantProvider` bound where
+//! `Option<Slice<u8>>` (the type `Str` itself wraps) does not have this
+//! issue. `opt_bytes`/[`as_opt_str`] convert at the edges.
+
+use stabby::option::Option as StabbyOption;
+use stabby::slice::Slice;
+use stabby::str::Str;
+
+use super::util::ServiceResult;
+
+// the app-side constructors are in `crate::ui`
+
+/// Recovers the `&str` an `opt_bytes`-produced field holds, if any.
+///
+/// # Safety
+///
+/// `bytes`, if present, must have come from `opt_bytes` applied to a
+/// genuine `&str` (true for every field on every type in this module).
+pub fn as_opt_str(bytes: StabbyOption<Slice<'_, u8>>) -> Option<&str> {
+ core::option::Option::from(bytes).map(|b: Slice<'_, u8>| {
+ // SAFETY: see function doc.
+ unsafe { core::str::from_utf8_unchecked(b.as_slice()) }
+ })
+}
+
+/// A key-value pair with an optional monospace flag, used in UI detail views.
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct Property<'a> {
+ /// Name of the property.
+ pub key: Str<'a>,
+ /// Value of the property.
+ pub value: Str<'a>,
+ /// Shown in a monospace font.
+ pub mono: bool,
+}
+
+/// A string with an optional monospace flag, used in UI list views.
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct StrExt<'a> {
+ /// The text.
+ pub key: Str<'a>,
+ /// Shown in a monospace font.
+ pub mono: bool,
+}
+
+/// Result returned by Core after a UI interaction.
+#[stabby::stabby]
+#[repr(C, u8)]
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum TrezorUiResult {
+ /// The user confirmed.
+ Confirmed,
+ /// The user went back.
+ Back,
+ /// The user cancelled.
+ Cancelled,
+ /// The user asked for more information.
+ Info,
+ /// The number the user entered.
+ Integer(u32),
+}
+
+/// A menu of selectable string items.
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct SelectMenu<'a> {
+ /// Entries shown on the screen.
+ pub items: Slice<'a, Str<'a>>,
+ /// Label of the cancel entry, if any.
+ pub cancel: StabbyOption<Slice<'a, u8>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+/// Stable-ABI form of [`crate::structs::ConfirmTrade`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ConfirmTrade<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// Subtitle under the title.
+ pub subtitle: Str<'a>,
+ /// What the user gets.
+ pub buy: Str<'a>,
+ /// What the user gives.
+ pub sell: StabbyOption<Slice<'a, u8>>,
+ /// The left button returns `Back` instead of cancelling.
+ pub back_button: bool,
+ /// Button request name sent to the host.
+ pub br_name: StabbyOption<Slice<'a, u8>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+/// Stable-ABI form of [`crate::structs::ConfirmAction`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ConfirmAction<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// The action to confirm.
+ pub action: Str<'a>,
+ /// Description text.
+ pub description: StabbyOption<Slice<'a, u8>>,
+ /// Subtitle under the title.
+ pub subtitle: StabbyOption<Slice<'a, u8>>,
+ /// The user confirms by holding the button.
+ pub hold: bool,
+ /// Shows a cancel button.
+ pub cancel: bool,
+ /// Text of the confirm button.
+ pub verb: StabbyOption<Slice<'a, u8>>,
+ /// Button request name sent to the host.
+ pub br_name: StabbyOption<Slice<'a, u8>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+ /// The menu button returns `Info` to the app instead of opening Core's menu.
+ pub external_menu: bool,
+}
+
+/// Stable-ABI form of [`crate::structs::ConfirmSummary`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ConfirmSummary<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// The amount.
+ pub amount: StabbyOption<Slice<'a, u8>>,
+ /// Label of the amount.
+ pub amount_label: StabbyOption<Slice<'a, u8>>,
+ /// The fee.
+ pub fee: Str<'a>,
+ /// Label of the fee.
+ pub fee_label: Str<'a>,
+ /// Title of the account information.
+ pub account_title: StabbyOption<Slice<'a, u8>>,
+ /// Account information as key-value pairs.
+ pub account_items: StabbyOption<Slice<'a, Property<'a>>>,
+ /// Title of the extra information.
+ pub extra_title: StabbyOption<Slice<'a, u8>>,
+ /// Extra information as key-value pairs.
+ pub extra_items: StabbyOption<Slice<'a, Property<'a>>>,
+ /// The left button returns `Back` instead of cancelling.
+ pub back_button: bool,
+ /// Button request name sent to the host.
+ pub br_name: StabbyOption<Slice<'a, u8>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+/// Fields mirror [`crate::structs::ConfirmValue`] except `footer`, which is
+/// flattened into `footer_text`/`footer_bold` since stabby has no tuples;
+/// [`Self::new`] still takes the same `Option<(&str, bool)>` shape as the
+/// wire-format constructor, since a plain (non-ABI-crossing) parameter can
+/// be a tuple.
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ConfirmValue<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// The value to confirm.
+ pub value: Str<'a>,
+ /// Description text.
+ pub description: StabbyOption<Slice<'a, u8>>,
+ /// The value is data, shown in a data font.
+ pub is_data: bool,
+ /// Subtitle under the title.
+ pub subtitle: StabbyOption<Slice<'a, u8>>,
+ /// Text of the confirm button.
+ pub verb: StabbyOption<Slice<'a, u8>>,
+ /// Shows an info button in the header.
+ pub info: bool,
+ /// The user confirms by holding the button.
+ pub hold: bool,
+ /// Shows the value in monospace chunks, for easier comparison.
+ pub chunkify: bool,
+ /// Shows a page counter.
+ pub page_counter: bool,
+ /// Shows a cancel button.
+ pub cancel: bool,
+ /// Button request name sent to the host.
+ pub br_name: StabbyOption<Slice<'a, u8>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+ /// The menu button returns `Info` to the app instead of opening Core's menu.
+ pub external_menu: bool,
+ /// Footer text.
+ pub footer_text: StabbyOption<Slice<'a, u8>>,
+ /// Shows the footer text in bold.
+ pub footer_bold: bool,
+}
+
+/// Stable-ABI form of [`crate::structs::ConfirmValueIntro`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ConfirmValueIntro<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// The value to confirm.
+ pub value: Str<'a>,
+ /// Subtitle under the title.
+ pub subtitle: StabbyOption<Slice<'a, u8>>,
+ /// Text of the confirm button.
+ pub verb: StabbyOption<Slice<'a, u8>>,
+ /// Text of the cancel button.
+ pub verb_cancel: StabbyOption<Slice<'a, u8>>,
+ /// Text of the button that shows the whole value.
+ pub verb_view_all: StabbyOption<Slice<'a, u8>>,
+ /// The user confirms by holding the button.
+ pub hold: bool,
+ /// Shows the value in monospace chunks, for easier comparison.
+ pub chunkify: bool,
+ /// Button request name sent to the host.
+ pub br_name: StabbyOption<Slice<'a, u8>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+/// Stable-ABI form of [`crate::structs::ShowWarning`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ShowWarning<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// Body text.
+ pub content: Str<'a>,
+ /// Text of the confirm button.
+ pub verb: Str<'a>,
+ /// Button request name sent to the host.
+ pub br_name: StabbyOption<Slice<'a, u8>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+ /// Lets the user cancel.
+ pub allow_cancel: bool,
+ /// Shows the screen as dangerous.
+ pub danger: bool,
+}
+
+/// Stable-ABI form of [`crate::structs::ShowMismatch`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ShowMismatch<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+/// Stable-ABI form of [`crate::structs::ShowDanger`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ShowDanger<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// Body text.
+ pub content: Str<'a>,
+ /// Button request name sent to the host.
+ pub br_name: StabbyOption<Slice<'a, u8>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+ /// Text of the cancel button.
+ pub verb_cancel: StabbyOption<Slice<'a, u8>>,
+ /// Title of the menu.
+ pub menu_title: StabbyOption<Slice<'a, u8>>,
+}
+
+/// Stable-ABI form of [`crate::structs::ShowSuccess`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ShowSuccess<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// Body text.
+ pub content: Str<'a>,
+ /// Text of the button.
+ pub button: Str<'a>,
+ /// Closes the screen after this many milliseconds.
+ pub duration_ms: StabbyOption<u32>,
+ /// Button request name sent to the host.
+ pub br_name: StabbyOption<Slice<'a, u8>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+/// Stable-ABI form of [`crate::structs::RequestNumber`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct RequestNumber<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// Body text.
+ pub content: Str<'a>,
+ /// Number shown at first.
+ pub initial: u32,
+ /// Smallest allowed number.
+ pub min: u32,
+ /// Largest allowed number.
+ pub max: u32,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+/// Stable-ABI form of [`crate::structs::ConfirmProperties`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ConfirmProperties<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// Properties shown as key-value pairs.
+ pub props: Slice<'a, Property<'a>>,
+ /// Subtitle under the title.
+ pub subtitle: StabbyOption<Slice<'a, u8>>,
+ /// Text of the confirm button.
+ pub verb: StabbyOption<Slice<'a, u8>>,
+ /// The user confirms by holding the button.
+ pub hold: bool,
+ /// Button request name sent to the host.
+ pub br_name: StabbyOption<Slice<'a, u8>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+ /// The menu button returns `Info` to the app instead of opening Core's menu.
+ pub external_menu: bool,
+}
+
+/// Stable-ABI form of [`crate::structs::ShowProperties`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ShowProperties<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// Properties shown as key-value pairs.
+ pub props: Slice<'a, Property<'a>>,
+ /// Subtitle under the title.
+ pub subtitle: StabbyOption<Slice<'a, u8>>,
+ /// Button request name sent to the host.
+ pub br_name: StabbyOption<Slice<'a, u8>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+/// Stable-ABI form of [`crate::structs::ShowPublicKey`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ShowPublicKey<'a> {
+ /// The public key.
+ pub pubkey: Str<'a>,
+ /// Screen title.
+ pub title: Str<'a>,
+ /// Account name shown with the key.
+ pub account: StabbyOption<Slice<'a, u8>>,
+ /// Derivation path shown with the key.
+ pub path: StabbyOption<Slice<'a, u8>>,
+ /// Warning text.
+ pub warning: StabbyOption<Slice<'a, u8>>,
+ /// Button request name sent to the host.
+ pub br_name: Str<'a>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+/// Stable-ABI form of [`crate::structs::ShowInfoWithCancel`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ShowInfoWithCancel<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// Entries shown on the screen.
+ pub items: Slice<'a, Property<'a>>,
+ /// Shows the value in monospace chunks, for easier comparison.
+ pub chunkify: bool,
+ /// Button request name sent to the host.
+ pub br_name: StabbyOption<Slice<'a, u8>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+/// Stable-ABI form of [`crate::structs::ConfirmWithInfo`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ConfirmWithInfo<'a> {
+ /// Screen title.
+ pub title: Str<'a>,
+ /// Subtitle under the title.
+ pub subtitle: StabbyOption<Slice<'a, u8>>,
+ /// Entries shown on the screen.
+ pub items: Slice<'a, StrExt<'a>>,
+ /// Text of the confirm button.
+ pub verb: Str<'a>,
+ /// Text of the info button.
+ pub verb_info: StabbyOption<Slice<'a, u8>>,
+ /// Button request name sent to the host.
+ pub br_name: StabbyOption<Slice<'a, u8>>,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+}
+
+/// Stable-ABI form of [`crate::structs::ShowAddress`].
+#[stabby::stabby]
+#[derive(Clone)]
+pub struct ShowAddress<'a> {
+ /// The address.
+ pub address: Str<'a>,
+ /// The address as encoded in the QR code.
+ pub address_qr: Str<'a>,
+ /// Screen title.
+ pub title: StabbyOption<Slice<'a, u8>>,
+ /// Subtitle under the title.
+ pub subtitle: StabbyOption<Slice<'a, u8>>,
+ /// Account name shown with the address.
+ pub account: StabbyOption<Slice<'a, u8>>,
+ /// Derivation path shown with the address.
+ pub path: StabbyOption<Slice<'a, u8>>,
+ /// Extended public keys of a multisig address.
+ pub xpubs: Slice<'a, Property<'a>>,
+ /// Shows the value in monospace chunks, for easier comparison.
+ pub chunkify: bool,
+ /// Button request code sent to the host.
+ pub br_code: i32,
+ /// The address is case-sensitive.
+ pub case_sensitive: bool,
+}
+
+/// Talks to Core's UI/progress screens. Each method sends one screen request
+/// over the wire and returns Core's response — implemented in `core/embed/api`
+/// against [`super::wire::WireV1`].
+#[stabby::stabby(checked)]
+pub trait UiV1: Send + Sync {
+ /// Shows a [`ConfirmValue`] screen.
+ extern "C" fn confirm_value<'a>(
+ &self,
+ value: ConfirmValue<'a>,
+ ) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a [`ConfirmValueIntro`] screen.
+ extern "C" fn confirm_value_intro<'a>(
+ &self,
+ value: ConfirmValueIntro<'a>,
+ ) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a [`ConfirmSummary`] screen.
+ extern "C" fn confirm_summary<'a>(
+ &self,
+ value: ConfirmSummary<'a>,
+ ) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a [`ConfirmAction`] screen.
+ extern "C" fn confirm_action<'a>(
+ &self,
+ value: ConfirmAction<'a>,
+ ) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a [`SelectMenu`] screen.
+ extern "C" fn select_menu<'a>(&self, value: SelectMenu<'a>) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a [`ConfirmProperties`] screen.
+ extern "C" fn confirm_properties<'a>(
+ &self,
+ value: ConfirmProperties<'a>,
+ ) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a [`ShowProperties`] screen.
+ extern "C" fn show_properties<'a>(&self, value: ShowProperties<'a>) -> ServiceResult<()>;
+
+ /// Shows a [`ShowWarning`] screen.
+ extern "C" fn show_warning<'a>(&self, value: ShowWarning<'a>) -> ServiceResult<()>;
+
+ /// Shows a [`ShowInfoWithCancel`] screen.
+ extern "C" fn show_info_with_cancel<'a>(
+ &self,
+ value: ShowInfoWithCancel<'a>,
+ ) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a [`ShowMismatch`] screen.
+ extern "C" fn show_mismatch<'a>(
+ &self,
+ value: ShowMismatch<'a>,
+ ) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a [`ConfirmTrade`] screen.
+ extern "C" fn confirm_trade<'a>(
+ &self,
+ value: ConfirmTrade<'a>,
+ ) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a [`ShowDanger`] screen.
+ extern "C" fn show_danger<'a>(&self, value: ShowDanger<'a>) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a [`ShowSuccess`] screen.
+ extern "C" fn show_success<'a>(&self, value: ShowSuccess<'a>) -> ServiceResult<()>;
+
+ /// Shows a [`RequestNumber`] screen.
+ extern "C" fn request_number<'a>(
+ &self,
+ value: RequestNumber<'a>,
+ ) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a [`ShowPublicKey`] screen.
+ extern "C" fn show_public_key<'a>(
+ &self,
+ value: ShowPublicKey<'a>,
+ ) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a [`ConfirmWithInfo`] screen.
+ extern "C" fn confirm_with_info<'a>(
+ &self,
+ value: ConfirmWithInfo<'a>,
+ ) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a [`ShowAddress`] screen.
+ extern "C" fn show_address<'a>(&self, value: ShowAddress<'a>) -> ServiceResult<TrezorUiResult>;
+
+ /// Shows a progress indicator with an optional `description` and `title`.
+ extern "C" fn init_progress<'a>(
+ &self,
+ description: StabbyOption<Slice<'a, u8>>,
+ title: StabbyOption<Slice<'a, u8>>,
+ indeterminate: bool,
+ danger: bool,
+ ) -> ServiceResult<()>;
+
+ /// Updates the progress indicator's `description` and `value` (0 to 1000).
+ extern "C" fn update_progress<'a>(
+ &self,
+ description: StabbyOption<Slice<'a, u8>>,
+ value: u32,
+ ) -> ServiceResult<()>;
+
+ /// Closes the progress indicator.
+ extern "C" fn end_progress(&self) -> ServiceResult<()>;
+}
+
+/// The stabby vtable of [`UiV1`].
+pub type UiV1Vtable = stabby::vtable!(UiV1 + Send + Sync);
+/// A borrowed `dyn UiV1`.
+pub type UiV1Ref<'a> = stabby::DynRef<'a, UiV1Vtable>;
+/// A `dyn UiV1` that lives as long as the app.
+pub type StaticUiV1 = UiV1Ref<'static>;
### sdk/crates/trezor-app-sdk/src/traits/util.rs
@@ -0,0 +1,69 @@
+/// A stable-ABI `Result`, for calls that need no service error wrapper.
+///
+/// A plain `#[repr(C, u8)]` enum, used instead of `stabby::result::Result` to
+/// avoid stabby's niche optimization, which makes compilation excessively slow
+/// when both `T` and `E` are non-trivial.
+#[stabby::stabby]
+#[repr(C, u8)]
+pub enum FastResult<T, E> {
+ /// Success.
+ Ok(T) = 0,
+ /// Failure.
+ Err(E) = 1,
+}
+
+impl<T, E> FastResult<T, E> {
+ /// Converts into a standard [`Result`].
+ pub fn into_result(self) -> Result<T, E> {
+ match self {
+ FastResult::Ok(t) => Result::Ok(t),
+ FastResult::Err(e) => Result::Err(e),
+ }
+ }
+
+ /// Borrows the value as a standard [`Result`] of references.
+ pub fn as_result_ref<'a>(&'a self) -> Result<&'a T, &'a E> {
+ match self {
+ FastResult::Ok(t) => Result::Ok(t),
+ FastResult::Err(e) => Result::Err(e),
+ }
+ }
+}
+
+impl<T, E> From<Result<T, E>> for FastResult<T, E> {
+ fn from(result: Result<T, E>) -> Self {
+ match result {
+ Result::Ok(t) => FastResult::Ok(t),
+ Result::Err(e) => FastResult::Err(e),
+ }
+ }
+}
+
+/// Errors that can occur while talking to a Core-provided service.
+///
+/// Primary error type for fallible API calls.
+#[stabby::stabby]
+#[repr(C, u8)]
+pub enum CoreServiceError<E> {
+ /// Service-specific error.
+ ServiceError(E),
+ /// The operation timed out while waiting for a response.
+ Timeout,
+ /// Failed to perform the operation.
+ ///
+ /// Could be an IPC failure, invalid arguments or undecodable response.
+ /// Core-side logging provides details, those are not passed over the API
+ /// boundary.
+ ServiceCallFailed,
+ /// Core requested the application to stop.
+ ///
+ /// This error MUST be propagated to the top-level handler and end the
+ /// application event loop.
+ StopApplication,
+}
+
+/// Result of an API call that goes through a Core service.
+pub type ServiceResult<T, E = ()> = FastResult<T, CoreServiceError<E>>;
+
+/// Longest timeout, in milliseconds, an API call accepts.
+pub const TIMEOUT_MAX: u32 = u32::MAX / 2 - 1;
### sdk/crates/trezor-app-sdk/src/traits/wire.rs
@@ -0,0 +1,52 @@
+use stabby::boxed::BoxedSlice;
+use stabby::slice::Slice;
+use stabby::str::Str;
+
+use super::util::ServiceResult;
+
+/// An owned wire message: a numeric id paired with its body bytes.
+#[stabby::stabby]
+pub struct WireMessage {
+ /// Message id, from the app's own message numbering.
+ pub id: u16,
+ /// Message body.
+ pub data: BoxedSlice<u8>,
+}
+
+/// Failure types an app may report; Core maps them to `FailureType` by
+/// position, keep the order in sync with `_APP_FAILURE_CODES`.
+#[stabby::stabby]
+#[repr(u8)]
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(test, derive(Debug))]
+pub enum FailureKind {
+ /// The request's data is invalid.
+ DataError,
+ /// The user cancelled the action.
+ ActionCancelled,
+ /// Processing failed for another reason.
+ ProcessError,
+}
+
+/// Talks to the host through Core.
+///
+/// Apps never see raw IPC primitives — this trait *is* the transport, hiding
+/// how bytes actually move between the app and Core.
+#[stabby::stabby(checked)]
+pub trait WireV1: Send + Sync {
+ /// Waits for the next message from the host.
+ extern "C" fn wire_receive(&self, timeout_ms: u32) -> ServiceResult<WireMessage>;
+
+ /// Sends `data` tagged `id` to the host.
+ extern "C" fn wire_send<'a>(&self, id: u16, data: Slice<'a, u8>) -> ServiceResult<()>;
+
+ /// Sends an error to the host, ending the app's run.
+ extern "C" fn wire_error<'a>(&self, kind: FailureKind, message: Str<'a>) -> ServiceResult<()>;
+}
+
+/// The stabby vtable of [`WireV1`].
+pub type WireV1Vtable = stabby::vtable!(WireV1 + Send + Sync);
+/// A borrowed `dyn WireV1`.
+pub type WireV1Ref<'a> = stabby::DynRef<'a, WireV1Vtable>;
+/// A `dyn WireV1` that lives as long as the app.
+pub type StaticWireV1 = WireV1Ref<'static>;
### sdk/crates/trezor-app-sdk/src/ui.rs
@@ -0,0 +1,424 @@
+//! High-level UI API for interacting with the Trezor display.
+//!
+//! Every function here sends one screen request over the stable-ABI
+//! [`UiV1`](crate::traits::ui::UiV1) vtable handed to this app, and returns
+//! Core's response.
+
+use crate::app_runtime::get_ui_or_die;
+
+// constructors of the `traits::ui` structs
+mod constructors;
+
+use constructors::opt_bytes;
+
+use crate::traits::ui::UiV1Dyn as _;
+pub use crate::traits::ui::{
+ ConfirmAction, ConfirmProperties, ConfirmSummary, ConfirmTrade, ConfirmValue,
+ ConfirmValueIntro, ConfirmWithInfo, Property, RequestNumber, SelectMenu, ShowAddress,
+ ShowDanger, ShowInfoWithCancel, ShowMismatch, ShowProperties, ShowPublicKey, ShowSuccess,
+ ShowWarning, StrExt, TrezorUiResult,
+};
+use crate::{Error, IntoAppResult, Result};
+
+/// The user's answer to a screen, or an error.
+pub type UiResult = Result<TrezorUiResult>;
+
+/// Converts a [`TrezorUiResult`] into `Ok(())` if confirmed, or [`Error::Cancelled`] otherwise.
+///
+/// Useful as the outermost check after a UI flow.
+pub fn error_if_not_confirmed(result: TrezorUiResult) -> Result<()> {
+ if matches!(result, TrezorUiResult::Confirmed) {
+ Ok(())
+ } else {
+ Err(Error::Cancelled)
+ }
+}
+
+/// Runs a sequence of confirmation screens as one linear flow: `Confirmed`
+/// advances to the next factory, `Back` steps back to the previous one (if
+/// any), `Cancelled` ends the whole flow as cancelled.
+pub fn confirm_linear_flow(confirm_factories: &[&dyn Fn() -> UiResult]) -> UiResult {
+ let mut i = 0usize;
+
+ while i < confirm_factories.len() {
+ let res = (confirm_factories[i])()?;
+
+ match res {
+ TrezorUiResult::Confirmed => {
+ i += 1;
+ }
+ TrezorUiResult::Back if i > 0 => {
+ i -= 1;
+ }
+ TrezorUiResult::Cancelled => {
+ return Ok(TrezorUiResult::Cancelled);
+ }
+ _ => {
+ // TODO: proper error type
+ return Err(Error::Cancelled);
+ }
+ }
+ }
+
+ Ok(TrezorUiResult::Confirmed)
+}
+
+/// Runs a main UI layout in a loop, opening a [`Menu`] when the user requests more info.
+pub fn interact_with_menu_flow<'a>(
+ main_layout: impl for<'b> Fn(Option<&'b str>) -> UiResult,
+ menu: &Menu<'a>,
+ br_name: Option<&str>,
+) -> UiResult {
+ let mut first_br = br_name;
+
+ loop {
+ let result = main_layout(first_br)?;
+ first_br = None; // ButtonRequest should be sent once (for the main layout)
+
+ if matches!(result, TrezorUiResult::Info) {
+ let menu_res = menu.interact()?;
+ if matches!(menu_res, TrezorUiResult::Cancelled) {
+ return Ok(TrezorUiResult::Cancelled);
+ }
+ continue;
+ }
+
+ return Ok(result);
+ }
+}
+
+/// Runs a main layout paired with an optional info layout, looping until confirmed or cancelled.
+pub fn interact_with_info_flow(
+ main_layout: impl for<'a> Fn(Option<&'a str>) -> UiResult,
+ info_layout: impl for<'a> Fn(Option<&'a str>) -> UiResult,
+ br_name: &str,
+ repeat_button_request: Option<bool>,
+ info_layout_can_confirm: Option<bool>,
+) -> UiResult {
+ let repeat_button_request = repeat_button_request.unwrap_or(false);
+ let info_layout_can_confirm = info_layout_can_confirm.unwrap_or(false);
+
+ let mut first_br = Some(br_name);
+ let next_br = if repeat_button_request {
+ Some(br_name)
+ } else {
+ None
+ };
+
+ loop {
+ let main_res = main_layout(first_br)?;
+
+ first_br = next_br;
+ match main_res {
+ TrezorUiResult::Confirmed => {
+ return Ok(TrezorUiResult::Confirmed);
+ }
+ TrezorUiResult::Info => {
+ let info_res = info_layout(next_br)?;
+
+ if info_layout_can_confirm && matches!(info_res, TrezorUiResult::Confirmed) {
+ return Ok(TrezorUiResult::Confirmed);
+ } else {
+ // Return to the same main step after info flow.
+ continue;
+ }
+ }
+ TrezorUiResult::Cancelled => {
+ return Ok(TrezorUiResult::Cancelled);
+ }
+ _ => {
+ // TODO: proper error type
+ return Err(Error::Cancelled);
+ }
+ }
+ }
+}
+
+/// Shows a paginated text screen and returns whether the user wants to see more.
+pub fn should_show_more<'a>(
+ title: &'a str,
+ para: &'a [StrExt<'a>],
+ button_text: &'a str,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ verb: &'a str,
+) -> Result<bool> {
+ match confirm_with_info(ConfirmWithInfo::new(
+ title,
+ None,
+ para,
+ verb,
+ Some(button_text),
+ br_name,
+ br_code,
+ )) {
+ Ok(TrezorUiResult::Confirmed) => Ok(false),
+ Ok(TrezorUiResult::Info) => Ok(true),
+ _ => Err(Error::Cancelled),
+ }
+}
+
+/// One entry in a [`Menu`], rendered as a [`ShowProperties`] screen when selected.
+#[derive(Copy, Clone)]
+pub struct Details<'a> {
+ name: &'a str,
+ props: &'a [Property<'a>],
+ title: Option<&'a str>,
+ subtitle: Option<&'a str>,
+ br_code: i32,
+}
+
+impl<'a> Details<'a> {
+ /// An entry named `name` that shows `props`, with an optional `title` and
+ /// `subtitle`.
+ pub fn new(
+ name: &'a str,
+ props: &'a [Property<'a>],
+ title: Option<&'a str>,
+ subtitle: Option<&'a str>,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ name,
+ title,
+ props,
+ subtitle,
+ br_code,
+ }
+ }
+
+ fn interact(&self) -> Result<()> {
+ show_properties(ShowProperties::new(
+ self.title.unwrap_or(self.name),
+ self.props,
+ self.subtitle,
+ None,
+ self.br_code,
+ ))
+ }
+}
+
+/// The cancel entry of a [`Menu`]; selecting it cancels the flow.
+#[derive(Copy, Clone)]
+pub struct Cancel<'a> {
+ title: &'a str,
+}
+
+impl<'a> Cancel<'a> {
+ /// A cancel entry labelled `title`.
+ pub fn new(title: &'a str) -> Self {
+ Self { title }
+ }
+}
+
+/// A menu of [`Details`] entries plus an optional [`Cancel`] entry, driven by
+/// [`Menu::interact`].
+#[derive(Copy, Clone)]
+pub struct Menu<'a> {
+ children: &'a [Details<'a>],
+ cancel: Option<Cancel<'a>>,
+}
+
+impl<'a> Menu<'a> {
+ const MAX_MENU_ITEMS: usize = 5;
+
+ /// A menu of `children`, with an optional `cancel` entry.
+ pub fn new(children: &'a [Details<'a>], cancel: Option<Cancel<'a>>) -> Self {
+ Self { children, cancel }
+ }
+
+ /// Shows the menu until the user cancels, opening the selected entries.
+ pub fn interact(&self) -> UiResult {
+ if self.children.is_empty() && self.cancel.is_none() {
+ // TODO: maybe raise error instead
+ return Ok(TrezorUiResult::Confirmed);
+ }
+
+ if self.children.len() > Self::MAX_MENU_ITEMS {
+ // TODO: proper error type
+ return Err(Error::Cancelled);
+ }
+
+ let mut items = ["".into(); Self::MAX_MENU_ITEMS];
+ let mut i = 0usize;
+ while i < self.children.len() {
+ items[i] = self.children[i].name.into();
+ i += 1;
+ }
+
+ loop {
+ let choice = select_menu(
+ SelectMenu::new(
+ &items[..self.children.len()],
+ self.cancel.as_ref().map(|c| c.title),
+ 1,
+ ),
+ self.children.len(),
+ )?;
+
+ match choice {
+ TrezorUiResult::Integer(idx) if (idx as usize) < self.children.len() => {
+ // Same behavior as Python: open details, ignore its result, return to menu.
+ self.children[idx as usize].interact()?;
+ continue;
+ }
+ TrezorUiResult::Confirmed => {
+ return Ok(TrezorUiResult::Confirmed);
+ }
+ // Same behavior as Python's `cancel_leaf`: cancel without confirmation.
+ TrezorUiResult::Cancelled if self.cancel.is_some() => {
+ return Ok(TrezorUiResult::Cancelled);
+ }
+ TrezorUiResult::Cancelled => continue,
+ // TODO: proper error type
+ _ => return Err(Error::Cancelled),
+ }
+ }
+ }
+}
+
+/// Shows a [`ConfirmValue`] screen and returns the user's answer.
+pub fn confirm_value<'a>(confirm_value: ConfirmValue<'a>) -> UiResult {
+ get_ui_or_die()
+ .confirm_value(confirm_value)
+ .into_app_result()
+}
+
+/// Shows a [`ConfirmValueIntro`] screen and returns the user's answer.
+pub fn confirm_value_intro<'a>(confirm_value_intro: ConfirmValueIntro<'a>) -> UiResult {
+ get_ui_or_die()
+ .confirm_value_intro(confirm_value_intro)
+ .into_app_result()
+}
+
+/// Shows a [`ConfirmSummary`] screen and returns the user's answer.
+pub fn confirm_summary<'a>(confirm_summary: ConfirmSummary<'a>) -> UiResult {
+ get_ui_or_die()
+ .confirm_summary(confirm_summary)
+ .into_app_result()
+}
+
+/// Shows a [`ConfirmAction`] screen and returns the user's answer.
+pub fn confirm_action<'a>(confirm_action: ConfirmAction<'a>) -> UiResult {
+ get_ui_or_die()
+ .confirm_action(confirm_action)
+ .into_app_result()
+}
+
+fn select_menu<'a>(select_menu: SelectMenu<'a>, len: usize) -> UiResult {
+ match get_ui_or_die().select_menu(select_menu).into_app_result() {
+ Ok(TrezorUiResult::Integer(idx)) if (idx as usize) < len => {
+ Ok(TrezorUiResult::Integer(idx))
+ }
+ Ok(TrezorUiResult::Confirmed) => Ok(TrezorUiResult::Confirmed),
+ Ok(_) => Ok(TrezorUiResult::Cancelled),
+ Err(e) => Err(e),
+ }
+}
+
+/// Shows a [`ConfirmProperties`] screen and returns the user's answer.
+pub fn confirm_properties<'a>(confirm_properties: ConfirmProperties<'a>) -> UiResult {
+ get_ui_or_die()
+ .confirm_properties(confirm_properties)
+ .into_app_result()
+}
+
+/// Shows a [`ShowProperties`] screen.
+pub fn show_properties<'a>(show_properties: ShowProperties<'a>) -> Result<()> {
+ get_ui_or_die()
+ .show_properties(show_properties)
+ .into_app_result()
+}
+
+/// Shows a [`ShowWarning`] screen.
+pub fn show_warning<'a>(show_warning: ShowWarning<'a>) -> Result<()> {
+ get_ui_or_die().show_warning(show_warning).into_app_result()
+}
+
+/// Shows a [`ShowInfoWithCancel`] screen and returns the user's answer.
+pub fn show_info_with_cancel<'a>(show_info_with_cancel: ShowInfoWithCancel<'a>) -> UiResult {
+ get_ui_or_die()
+ .show_info_with_cancel(show_info_with_cancel)
+ .into_app_result()
+}
+
+/// Shows a [`ShowMismatch`] screen and returns the user's answer.
+pub fn show_mismatch<'a>(show_mismatch: ShowMismatch<'a>) -> UiResult {
+ get_ui_or_die()
+ .show_mismatch(show_mismatch)
+ .into_app_result()
+}
+
+/// Shows a [`ConfirmTrade`] screen and returns the user's answer.
+pub fn confirm_trade<'a>(confirm_trade: ConfirmTrade<'a>) -> UiResult {
+ get_ui_or_die()
+ .confirm_trade(confirm_trade)
+ .into_app_result()
+}
+
+/// Shows a [`ShowDanger`] screen and returns the user's answer.
+pub fn show_danger<'a>(show_danger: ShowDanger<'a>) -> UiResult {
+ get_ui_or_die().show_danger(show_danger).into_app_result()
+}
+
+/// Shows a [`ShowSuccess`] screen.
+pub fn show_success<'a>(show_success: ShowSuccess<'a>) -> Result<()> {
+ get_ui_or_die().show_success(show_success).into_app_result()
+}
+
+/// Shows a [`RequestNumber`] screen and returns the user's answer.
+pub fn request_number<'a>(request_number: RequestNumber<'a>) -> UiResult {
+ get_ui_or_die()
+ .request_number(request_number)
+ .into_app_result()
+}
+
+/// Shows a [`ShowPublicKey`] screen and returns the user's answer.
+pub fn show_public_key<'a>(show_public_key: ShowPublicKey<'a>) -> UiResult {
+ get_ui_or_die()
+ .show_public_key(show_public_key)
+ .into_app_result()
+}
+
+/// Shows a [`ConfirmWithInfo`] screen and returns the user's answer.
+pub fn confirm_with_info<'a>(confirm_with_info: ConfirmWithInfo<'a>) -> UiResult {
+ get_ui_or_die()
+ .confirm_with_info(confirm_with_info)
+ .into_app_result()
+}
+
+/// Shows a [`ShowAddress`] screen and returns the user's answer.
+pub fn show_address<'a>(show_address: ShowAddress<'a>) -> UiResult {
+ get_ui_or_die().show_address(show_address).into_app_result()
+}
+
+/// Starts a progress indicator, with an optional `description`/`title` and
+/// whether it's `indeterminate` (no known end point) or `danger`ous (drawn
+/// in a warning style).
+pub fn init_progress<'a>(
+ description: Option<&'a str>,
+ title: Option<&'a str>,
+ indeterminate: bool,
+ danger: bool,
+) -> Result<()> {
+ get_ui_or_die()
+ .init_progress(
+ opt_bytes(description),
+ opt_bytes(title),
+ indeterminate,
+ danger,
+ )
+ .into_app_result()
+}
+
+/// Updates the current progress indicator's `description` and `value` (0-1000).
+pub fn update_progress<'a>(description: Option<&'a str>, value: u32) -> Result<()> {
+ get_ui_or_die()
+ .update_progress(opt_bytes(description), value)
+ .into_app_result()
+}
+
+/// Ends the current progress indicator.
+pub fn end_progress() -> Result<()> {
+ get_ui_or_die().end_progress().into_app_result()
+}
### sdk/crates/trezor-app-sdk/src/ui/constructors.rs
@@ -0,0 +1,468 @@
+//! Constructors of the [`crate::traits::ui`] structs, taking plain Rust types.
+
+use stabby::option::Option as StabbyOption;
+use stabby::slice::Slice;
+use stabby::str::Str;
+
+use crate::traits::ui::{
+ ConfirmAction, ConfirmProperties, ConfirmSummary, ConfirmTrade, ConfirmValue,
+ ConfirmValueIntro, ConfirmWithInfo, Property, RequestNumber, SelectMenu, ShowAddress,
+ ShowDanger, ShowInfoWithCancel, ShowMismatch, ShowProperties, ShowPublicKey, ShowSuccess,
+ ShowWarning, StrExt,
+};
+
+/// Converts an optional `&str` constructor argument into the
+/// niche-friendly `StabbyOption<Slice<u8>>` field representation.
+pub(crate) fn opt_bytes(s: Option<&str>) -> StabbyOption<Slice<'_, u8>> {
+ s.map(|s| Slice::from(s.as_bytes())).into()
+}
+
+impl<'a> Property<'a> {
+ /// A property `key`: `value`, the value in a monospace font if `mono`.
+ pub fn new(key: &'a str, value: &'a str, mono: bool) -> Self {
+ Self {
+ key: key.into(),
+ value: value.into(),
+ mono,
+ }
+ }
+
+ /// A property with its value in a monospace font.
+ pub fn mono(key: &'a str, value: &'a str) -> Self {
+ Self::new(key, value, true)
+ }
+
+ /// A property with its value in the regular font.
+ pub fn plain(key: &'a str, value: &'a str) -> Self {
+ Self::new(key, value, false)
+ }
+}
+
+impl<'a> StrExt<'a> {
+ /// A text, in a monospace font if `mono`.
+ pub fn new(key: &'a str, mono: bool) -> Self {
+ Self {
+ key: key.into(),
+ mono,
+ }
+ }
+
+ /// A text in a monospace font.
+ pub fn mono(key: &'a str) -> Self {
+ Self::new(key, true)
+ }
+
+ /// A text in the regular font.
+ pub fn plain(key: &'a str) -> Self {
+ Self::new(key, false)
+ }
+}
+
+impl<'a> SelectMenu<'a> {
+ /// A menu of `items`, with an optional `cancel` entry; `br_code` is the
+ /// button request code sent to the host.
+ pub fn new(items: &'a [Str<'a>], cancel: Option<&'a str>, br_code: i32) -> Self {
+ Self {
+ items: items.into(),
+ cancel: opt_bytes(cancel),
+ br_code,
+ }
+ }
+}
+
+impl<'a> ConfirmTrade<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ subtitle: &'a str,
+ buy: &'a str,
+ sell: Option<&'a str>,
+ back_button: bool,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ subtitle: subtitle.into(),
+ buy: buy.into(),
+ sell: opt_bytes(sell),
+ back_button,
+ br_name: opt_bytes(br_name),
+ br_code,
+ }
+ }
+}
+
+impl<'a> ConfirmAction<'a> {
+ #[allow(clippy::too_many_arguments)]
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ action: &'a str,
+ description: Option<&'a str>,
+ subtitle: Option<&'a str>,
+ hold: bool,
+ verb: Option<&'a str>,
+ cancel: bool,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ external_menu: bool,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ action: action.into(),
+ description: opt_bytes(description),
+ subtitle: opt_bytes(subtitle),
+ hold,
+ cancel,
+ verb: opt_bytes(verb),
+ br_name: opt_bytes(br_name),
+ br_code,
+ external_menu,
+ }
+ }
+}
+
+impl<'a> ConfirmSummary<'a> {
+ #[allow(clippy::too_many_arguments)]
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ amount: Option<&'a str>,
+ amount_label: Option<&'a str>,
+ fee: &'a str,
+ fee_label: &'a str,
+ account_title: Option<&'a str>,
+ account_items: Option<&'a [Property<'a>]>,
+ extra_title: Option<&'a str>,
+ extra_items: Option<&'a [Property<'a>]>,
+ back_button: bool,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ amount: opt_bytes(amount),
+ amount_label: opt_bytes(amount_label),
+ fee: fee.into(),
+ fee_label: fee_label.into(),
+ account_title: opt_bytes(account_title),
+ account_items: account_items.map(Into::into).into(),
+ extra_title: opt_bytes(extra_title),
+ extra_items: extra_items.map(Into::into).into(),
+ back_button,
+ br_name: opt_bytes(br_name),
+ br_code,
+ }
+ }
+}
+
+impl<'a> ConfirmValue<'a> {
+ #[allow(clippy::too_many_arguments)]
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ content: &'a str,
+ description: Option<&'a str>,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ is_data: bool,
+ verb: Option<&'a str>,
+ subtitle: Option<&'a str>,
+ info: bool,
+ hold: bool,
+ chunkify: bool,
+ page_counter: bool,
+ cancel: bool,
+ external_menu: bool,
+ footer: Option<(&'a str, bool)>,
+ ) -> Self {
+ let (footer_text, footer_bold) = match footer {
+ Some((text, bold)) => (opt_bytes(Some(text)), bold),
+ None => (opt_bytes(None), false),
+ };
+ Self {
+ title: title.into(),
+ value: content.into(),
+ description: opt_bytes(description),
+ is_data,
+ subtitle: opt_bytes(subtitle),
+ verb: opt_bytes(verb),
+ info,
+ hold,
+ chunkify,
+ page_counter,
+ cancel,
+ br_name: opt_bytes(br_name),
+ br_code,
+ external_menu,
+ footer_text,
+ footer_bold,
+ }
+ }
+}
+
+impl<'a> ConfirmValueIntro<'a> {
+ #[allow(clippy::too_many_arguments)]
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ value: &'a str,
+ subtitle: Option<&'a str>,
+ verb: Option<&'a str>,
+ verb_cancel: Option<&'a str>,
+ verb_view_all: Option<&'a str>,
+ hold: bool,
+ chunkify: bool,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ value: value.into(),
+ subtitle: opt_bytes(subtitle),
+ verb: opt_bytes(verb),
+ verb_cancel: opt_bytes(verb_cancel),
+ verb_view_all: opt_bytes(verb_view_all),
+ hold,
+ chunkify,
+ br_name: opt_bytes(br_name),
+ br_code,
+ }
+ }
+}
+
+impl<'a> ShowWarning<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ content: &'a str,
+ verb: &'a str,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ allow_cancel: bool,
+ danger: bool,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ content: content.into(),
+ verb: verb.into(),
+ br_name: opt_bytes(br_name),
+ br_code,
+ allow_cancel,
+ danger,
+ }
+ }
+}
+
+impl<'a> ShowMismatch<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(title: &'a str, br_code: i32) -> Self {
+ Self {
+ title: title.into(),
+ br_code,
+ }
+ }
+}
+
+impl<'a> ShowDanger<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ content: &'a str,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ verb_cancel: Option<&'a str>,
+ menu_title: Option<&'a str>,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ content: content.into(),
+ br_name: opt_bytes(br_name),
+ br_code,
+ verb_cancel: opt_bytes(verb_cancel),
+ menu_title: opt_bytes(menu_title),
+ }
+ }
+}
+
+impl<'a> ShowSuccess<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ content: &'a str,
+ button: &'a str,
+ duration_ms: Option<u32>,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ content: content.into(),
+ button: button.into(),
+ duration_ms: duration_ms.into(),
+ br_name: opt_bytes(br_name),
+ br_code,
+ }
+ }
+}
+
+impl<'a> RequestNumber<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ content: &'a str,
+ initial: u32,
+ min: u32,
+ max: u32,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ content: content.into(),
+ initial,
+ min,
+ max,
+ br_code,
+ }
+ }
+}
+
+impl<'a> ConfirmProperties<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ props: &'a [Property<'a>],
+ subtitle: Option<&'a str>,
+ verb: Option<&'a str>,
+ hold: bool,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ external_menu: bool,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ props: props.into(),
+ subtitle: opt_bytes(subtitle),
+ verb: opt_bytes(verb),
+ hold,
+ br_name: opt_bytes(br_name),
+ br_code,
+ external_menu,
+ }
+ }
+}
+
+impl<'a> ShowProperties<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ props: &'a [Property<'a>],
+ subtitle: Option<&'a str>,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ props: props.into(),
+ subtitle: opt_bytes(subtitle),
+ br_name: opt_bytes(br_name),
+ br_code,
+ }
+ }
+}
+
+impl<'a> ShowPublicKey<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ pubkey: &'a str,
+ title: &'a str,
+ account: Option<&'a str>,
+ path: Option<&'a str>,
+ warning: Option<&'a str>,
+ br_name: &'a str,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ pubkey: pubkey.into(),
+ title: title.into(),
+ account: opt_bytes(account),
+ path: opt_bytes(path),
+ warning: opt_bytes(warning),
+ br_name: br_name.into(),
+ br_code,
+ }
+ }
+}
+
+impl<'a> ShowInfoWithCancel<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ items: &'a [Property<'a>],
+ chunkify: bool,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ items: items.into(),
+ chunkify,
+ br_name: opt_bytes(br_name),
+ br_code,
+ }
+ }
+}
+
+impl<'a> ConfirmWithInfo<'a> {
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ title: &'a str,
+ subtitle: Option<&'a str>,
+ items: &'a [StrExt<'a>],
+ verb: &'a str,
+ verb_info: Option<&'a str>,
+ br_name: Option<&'a str>,
+ br_code: i32,
+ ) -> Self {
+ Self {
+ title: title.into(),
+ subtitle: opt_bytes(subtitle),
+ items: items.into(),
+ verb: verb.into(),
+ verb_info: opt_bytes(verb_info),
+ br_name: opt_bytes(br_name),
+ br_code,
+ }
+ }
+}
+
+impl<'a> ShowAddress<'a> {
+ #[allow(clippy::too_many_arguments)]
+ /// Creates the request; each argument sets the field of the same name.
+ pub fn new(
+ address: &'a str,
+ address_qr: &'a str,
+ title: Option<&'a str>,
+ subtitle: Option<&'a str>,
+ account: Option<&'a str>,
+ path: Option<&'a str>,
+ xpubs: &'a [Property<'a>],
+ chunkify: bool,
+ br_code: i32,
+ case_sensitive: bool,
+ ) -> Self {
+ Self {
+ address: address.into(),
+ address_qr: address_qr.into(),
+ title: opt_bytes(title),
+ subtitle: opt_bytes(subtitle),
+ account: opt_bytes(account),
+ path: opt_bytes(path),
+ xpubs: xpubs.into(),
+ chunkify,
+ br_code,
+ case_sensitive,
+ }
+ }
+}
### sdk/crates/trezor-app-sdk/src/util.rs
@@ -0,0 +1,144 @@
+use stabby::boxed::BoxedSlice;
+use ufmt::derive::uDebug;
+
+use crate::app_runtime;
+use crate::traits::util::TIMEOUT_MAX;
+
+/// Milliseconds since the device started.
+///
+/// Wraps around after about 49.7 days, so compare ticks by their difference,
+/// e.g. `systick_ms().wrapping_sub(start) >= timeout_ms`, and build deadlines
+/// with `systick_ms().wrapping_add(ms)`.
+pub fn systick_ms() -> u32 {
+ app_runtime::systick_ms()
+}
+
+/// Represents a timeout duration in milliseconds.
+///
+/// Use [`Timeout::max`] for the longest supported timeout, or construct
+/// via [`Timeout::ms`], [`Timeout::seconds`], or [`Timeout::minutes`].
+#[derive(uDebug, Copy, Clone, PartialEq, Eq)]
+pub struct Timeout(pub(crate) u32);
+
+impl Timeout {
+ /// Creates a timeout of `ms` milliseconds.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `ms` exceeds [`TIMEOUT_MAX`].
+ pub fn ms(ms: u32) -> Self {
+ assert!(ms <= TIMEOUT_MAX, "Timeout too long");
+ Self(ms)
+ }
+
+ /// Creates a timeout of `seconds` seconds.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the resulting timeout exceeds [`TIMEOUT_MAX`] ms.
+ pub fn seconds(seconds: u32) -> Self {
+ // saturate, so an overflow fails the TIMEOUT_MAX check instead of wrapping
+ Self::ms(seconds.saturating_mul(1000))
+ }
+
+ /// Creates a timeout of `minutes` minutes.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the resulting timeout exceeds [`TIMEOUT_MAX`] ms.
+ pub fn minutes(minutes: u32) -> Self {
+ Self::seconds(minutes.saturating_mul(60))
+ }
+
+ /// Returns the maximum supported timeout value.
+ pub fn max() -> Self {
+ Self::ms(TIMEOUT_MAX)
+ }
+
+ /// Returns the timeout in milliseconds.
+ pub fn as_ms(&self) -> u32 {
+ self.0
+ }
+
+ /// Blocks until this timeout elapses.
+ pub fn sleep(&self) {
+ app_runtime::sleep(self.0);
+ }
+}
+
+/// A fixed-capacity writer over a mutable byte slice, implementing [`ufmt::uWrite`].
+///
+/// Useful for formatting into stack-allocated buffers without heap allocation.
+pub struct SliceWriter<'a> {
+ slice: &'a mut [u8],
+ pos: usize,
+}
+
+impl<'a> SliceWriter<'a> {
+ /// Creates a new `SliceWriter` backed by `slice`.
+ pub fn new(slice: &'a mut [u8]) -> Self {
+ Self { slice, pos: 0 }
+ }
+}
+
+impl<'a> ufmt::uWrite for SliceWriter<'a> {
+ type Error = ();
+
+ fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
+ if self.pos + s.len() > self.slice.len() {
+ return Err(());
+ }
+ self.slice[self.pos..self.pos + s.len()].copy_from_slice(s.as_bytes());
+ self.pos += s.len();
+ Ok(())
+ }
+}
+
+impl<'a> AsRef<str> for SliceWriter<'a> {
+ fn as_ref(&self) -> &str {
+ // SAFETY: The only way to write is by invoking the ufmt::uWrite impl,
+ // which appends valid Rust &strs.
+ unsafe { core::str::from_utf8_unchecked(&self.slice[..self.pos]) }
+ }
+}
+
+/// Bytes handed over by Core, exposed as `impl AsRef<[u8]>` without copying
+/// them out of the [`BoxedSlice`].
+pub(crate) struct Bytes(pub(crate) BoxedSlice<u8>);
+
+impl AsRef<[u8]> for Bytes {
+ fn as_ref(&self) -> &[u8] {
+ &self.0
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn systick_ms_reads_core() {
+ // the mock API's systick is 0
+ crate::mock::sdk_init();
+ assert_eq!(systick_ms(), 0);
+ }
+
+ #[test]
+ fn timeout_units() {
+ assert_eq!(Timeout::seconds(2).as_ms(), 2000);
+ assert_eq!(Timeout::minutes(2).as_ms(), 120_000);
+ }
+
+ // 4_294_968 s wraps to 704 ms without the overflow guard
+ #[test]
+ #[should_panic(expected = "Timeout too long")]
+ fn timeout_seconds_overflow_panics() {
+ Timeout::seconds(4_294_968);
+ }
+
+ #[test]
+ #[should_panic(expected = "Timeout too long")]
+ fn timeout_minutes_overflow_panics() {
+ Timeout::minutes(71_583_000);
+ }
+}
### sdk/crates/trezor-app-sdk/src/wire.rs
@@ -0,0 +1,54 @@
+//! Talking to the host through Core: receive, send, call and error. The
+//! message encoding on top lives in [`crate::codec`].
+
+use crate::app_runtime::get_wire_or_die;
+use crate::traits::wire::{FailureKind, WireV1Dyn as _};
+use crate::util::{Bytes, Timeout};
+use crate::{IntoAppResult, Result, ResultExt, debug};
+
+/// Waits for the next message from the host and returns its id and raw bytes.
+pub fn wire_receive() -> Result<(u16, impl AsRef<[u8]>)> {
+ debug!("Waiting for wire message");
+ let message = get_wire_or_die()
+ .wire_receive(Timeout::max().as_ms())
+ .into_app_result()
+ .c()?;
+ debug!("Received wire message: id={}", message.id);
+
+ Ok((message.id, Bytes(message.data)))
+}
+
+/// Sends a message to the host. On its own this is how a flow ends; mid-flow
+/// use [`wire_call`].
+pub fn wire_send(id: u16, bytes: &[u8]) -> Result<()> {
+ get_wire_or_die()
+ .wire_send(id, bytes.into())
+ .into_app_result()
+ .c()
+}
+
+/// Sends a failure of `kind` with `message` to the host; for an SDK
+/// [`Error`](crate::Error) use [`Error::send_to_host`](crate::Error::send_to_host).
+pub fn wire_error(kind: FailureKind, message: &str) -> Result<()> {
+ get_wire_or_die()
+ .wire_error(kind, message.into())
+ .into_app_result()
+ .c()
+}
+
+/// Sends a request to the host and returns the response's message id and raw
+/// bytes.
+///
+/// Encoding/decoding of `req`/the response is left to the caller, so this
+/// primitive has no serializer dependency. Returning the id alongside the
+/// bytes (rather than assuming a single fixed response type) lets a request
+/// with more than one possible response dispatch on it — see e.g. Tron's
+/// `request_contract`, which can get back any one of several contract
+/// message types. Prefer [`wire_request`](crate::wire_request) for the common single-response
+/// case; use this directly only when you need that dispatch, or need to
+/// bypass [`WireRequest`](crate::WireRequest)/[`WireEncode`](crate::WireEncode)/
+/// [`WireDecode`](crate::WireDecode) entirely.
+pub fn wire_call(id: u16, req_bytes: &[u8]) -> Result<(u16, impl AsRef<[u8]> + use<>)> {
+ wire_send(id, req_bytes)?;
+ wire_receive()
+}
### sdk/crates/trezor-app-sdk/supply-chain/audits.toml
@@ -0,0 +1,4 @@
+
+# cargo-vet audits file
+
+[audits]
### sdk/crates/trezor-app-sdk/supply-chain/config.toml
@@ -0,0 +1,211 @@
+
+# cargo-vet config file
+
+[cargo-vet]
+version = "0.10"
+
+[imports.bytecodealliance]
+url = "https://raw.githubusercontent.com/bytecodealliance/wasmtime/main/supply-chain/audits.toml"
+
+[imports.google]
+url = "https://raw.githubusercontent.com/google/rust-crate-audits/main/audits.toml"
+
+[imports.isrg]
+url = "https://raw.githubusercontent.com/divviup/libprio-rs/main/supply-chain/audits.toml"
+
+[imports.mozilla]
+url = "https://raw.githubusercontent.com/mozilla/supply-chain/main/audits.toml"
+
+[imports.trezor]
+url = "https://raw.githubusercontent.com/trezor/trezor-firmware/main/supply-chain/audits.toml"
+
+[imports.zcash]
+url = "https://raw.githubusercontent.com/zcash/rust-ecosystem/main/supply-chain/audits.toml"
+
+[[exemptions.block-buffer]]
+version = "0.12.1"
+criteria = "safe-to-deploy"
+
+[[exemptions.bytecheck]]
+version = "0.8.3"
+criteria = "safe-to-deploy"
+
+[[exemptions.bytecheck_derive]]
+version = "0.8.3"
+criteria = "safe-to-deploy"
+
+[[exemptions.cfg-if]]
+version = "1.0.5"
+criteria = "safe-to-deploy"
+
+[[exemptions.const-oid]]
+version = "0.10.3"
+criteria = "safe-to-deploy"
+
+[[exemptions.crypto-common]]
+version = "0.2.2"
+criteria = "safe-to-deploy"
+
+[[exemptions.digest]]
+version = "0.11.3"
+criteria = "safe-to-deploy"
+
+[[exemptions.equivalent]]
+version = "1.0.3"
+criteria = "safe-to-deploy"
+
+[[exemptions.hashbrown]]
+version = "0.17.2"
+criteria = "safe-to-deploy"
+
+[[exemptions.hmac-sha256]]
+version = "1.1.15"
+criteria = "safe-to-deploy"
+
+[[exemptions.hmac-sha512]]
+version = "1.1.13"
+criteria = "safe-to-deploy"
+
+[[exemptions.hybrid-array]]
+version = "0.4.15"
+criteria = "safe-to-deploy"
+
+[[exemptions.indexmap]]
+version = "2.14.2"
+criteria = "safe-to-deploy"
+
+[[exemptions.keccak]]
+version = "0.2.2"
+criteria = "safe-to-deploy"
+
+[[exemptions.libc]]
+version = "0.2.191"
+criteria = "safe-to-deploy"
+
+[[exemptions.lock_api]]
+version = "0.4.14"
+criteria = "safe-to-deploy"
+
+[[exemptions.memchr]]
+version = "2.8.3"
+criteria = "safe-to-deploy"
+
+[[exemptions.munge]]
+version = "0.4.7"
+criteria = "safe-to-deploy"
+
+[[exemptions.munge_macro]]
+version = "0.4.7"
+criteria = "safe-to-deploy"
+
+[[exemptions.num_enum]]
+version = "0.7.6"
+criteria = "safe-to-deploy"
+
+[[exemptions.num_enum_derive]]
+version = "0.7.6"
+criteria = "safe-to-deploy"
+
+[[exemptions.proc-macro-crate]]
+version = "3.5.0"
+criteria = "safe-to-deploy"
+
+[[exemptions.proc-macro2]]
+version = "1.0.107"
+criteria = "safe-to-deploy"
+
+[[exemptions.ptr_meta]]
+version = "0.3.2"
+criteria = "safe-to-deploy"
+
+[[exemptions.ptr_meta_derive]]
+version = "0.3.2"
+criteria = "safe-to-deploy"
+
+[[exemptions.rancor]]
+version = "0.1.3"
+criteria = "safe-to-deploy"
+
+[[exemptions.rend]]
+version = "0.5.4"
+criteria = "safe-to-deploy"
+
+[[exemptions.rkyv]]
+version = "0.8.18"
+criteria = "safe-to-deploy"
+
+[[exemptions.rkyv_derive]]
+version = "0.8.18"
+criteria = "safe-to-deploy"
+
+[[exemptions.rustversion]]
+version = "1.0.23"
+criteria = "safe-to-deploy"
+
+[[exemptions.scopeguard]]
+version = "1.2.0"
+criteria = "safe-to-deploy"
+
+[[exemptions.serde_core]]
+version = "1.0.229"
+criteria = "safe-to-deploy"
+
+[[exemptions.serde_derive]]
+version = "1.0.229"
+criteria = "safe-to-deploy"
+
+[[exemptions.sha2-const-stable]]
+version = "0.1.0"
+criteria = "safe-to-deploy"
+
+[[exemptions.sha3]]
+version = "0.11.0"
+criteria = "safe-to-deploy"
+
+[[exemptions.spin]]
+version = "0.10.1"
+criteria = "safe-to-deploy"
+
+[[exemptions.syn]]
+version = "1.0.109"
+criteria = "safe-to-deploy"
+
+[[exemptions.syn]]
+version = "2.0.119"
+criteria = "safe-to-deploy"
+
+[[exemptions.syn]]
+version = "3.0.10"
+criteria = "safe-to-deploy"
+
+[[exemptions.toml_datetime]]
+version = "1.1.3+spec-1.1.0"
+criteria = "safe-to-deploy"
+
+[[exemptions.toml_edit]]
+version = "0.25.20+spec-1.1.0"
+criteria = "safe-to-deploy"
+
+[[exemptions.toml_parser]]
+version = "1.1.6+spec-1.1.0"
+criteria = "safe-to-deploy"
+
+[[exemptions.typenum]]
+version = "1.20.1"
+criteria = "safe-to-deploy"
+
+[[exemptions.ufmt]]
+version = "0.2.0"
+criteria = "safe-to-deploy"
+
+[[exemptions.ufmt-macros]]
+version = "0.3.0"
+criteria = "safe-to-deploy"
+
+[[exemptions.unicode-ident]]
+version = "1.0.27"
+criteria = "safe-to-deploy"
+
+[[exemptions.winnow]]
+version = "1.0.5"
+criteria = "safe-to-deploy"
### sdk/crates/trezor-app-sdk/supply-chain/imports.lock
@@ -0,0 +1,182 @@
+
+# cargo-vet imports lock
+
+[[audits.bytecodealliance.audits.rustc_version]]
+who = "Alex Crichton <alex@alexcrichton.com>"
+criteria = "safe-to-deploy"
+delta = "0.4.0 -> 0.4.1"
+notes = "Minor changes, nothing worrisome"
+
+[[audits.bytecodealliance.audits.semver]]
+who = "Pat Hickey <phickey@fastly.com>"
+criteria = "safe-to-deploy"
+version = "1.0.17"
+notes = "plenty of unsafe pointer and vec tricks, but in well-structured and commented code that appears to be correct"
+
+[[audits.bytecodealliance.audits.tinyvec]]
+who = "Alex Crichton <alex@alexcrichton.com>"
+criteria = "safe-to-deploy"
+version = "1.6.0"
+notes = """
+This crate, while it implements collections, does so without `std::*` APIs and
+without `unsafe`. Skimming the crate everything looks reasonable and what one
+would expect from idiomatic safe collections in Rust.
+"""
+
+[[audits.google.audits.quote]]
+who = "Lukasz Anforowicz <lukasza@chromium.org>"
+criteria = "safe-to-deploy"
+version = "1.0.35"
+notes = """
+Grepped for "unsafe", "crypt", "cipher", "fs", "net" - there were no hits
+(except for benign "net" hit in tests and "fs" hit in README.md)
+"""
+aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT"
+
+[[audits.google.audits.quote]]
+who = "Adrian Taylor <adetaylor@chromium.org>"
+criteria = "safe-to-deploy"
+delta = "1.0.35 -> 1.0.36"
+aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT"
+
+[[audits.google.audits.quote]]
+who = "Lukasz Anforowicz <lukasza@chromium.org>"
+criteria = "safe-to-deploy"
+delta = "1.0.36 -> 1.0.37"
+notes = """
+The delta just 1) inlines/expands `impl ToTokens` that used to be handled via
+`primitive!` macro and 2) adds `impl ToTokens` for `CStr` and `CString`.
+"""
+aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT"
+
+[[audits.google.audits.quote]]
+who = "Dustin J. Mitchell <djmitche@chromium.org>"
+criteria = "safe-to-deploy"
+delta = "1.0.37 -> 1.0.38"
+notes = "Still no unsafe"
+aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT"
+
+[[audits.google.audits.quote]]
+who = "Daniel Cheng <dcheng@chromium.org>"
+criteria = "safe-to-deploy"
+delta = "1.0.38 -> 1.0.39"
+notes = "Only minor changes for clippy lints and documentation."
+aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT"
+
+[[audits.google.audits.quote]]
+who = "Lukasz Anforowicz <lukasza@chromium.org>"
+criteria = "safe-to-deploy"
+delta = "1.0.39 -> 1.0.40"
+notes = """
+The delta is just a simplification of how `tokens.extend(...)` call is made.
+Still no `unsafe` anywhere.
+"""
+aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT"
+
+[[audits.google.audits.tinyvec]]
+who = "Adrian Taylor <adetaylor@chromium.org>"
+criteria = "safe-to-deploy"
+delta = "1.6.0 -> 1.6.1"
+aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT"
+
+[[audits.google.audits.tinyvec]]
+who = "Adrian Taylor <adetaylor@chromium.org>"
+criteria = "safe-to-deploy"
+delta = "1.6.1 -> 1.7.0"
+aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT"
+
+[[audits.google.audits.tinyvec]]
+who = "Dustin J. Mitchell <djmitche@chromium.org>"
+criteria = "safe-to-deploy"
+delta = "1.7.0 -> 1.8.0"
+aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT"
+
+[[audits.google.audits.tinyvec]]
+who = "Adrian Taylor <adetaylor@chromium.org>"
+criteria = "safe-to-deploy"
+delta = "1.8.0 -> 1.8.1"
+aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT"
+
+[[audits.google.audits.tinyvec]]
+who = "Daniel Cheng <dcheng@chromium.org>"
+criteria = "safe-to-deploy"
+delta = "1.8.1 -> 1.9.0"
+notes = """
+Larger delta, but no unsafe code introduced. Deltas for:
+- borsh (Binary Object Representation Serializer for Hashing) serialization/deserialization support behind the `borsh` feature.
+- trait implementations to interoperate with the generic-array crate
+- miscellaneous helper functions and support code, e.g. `into_vec()`.
+"""
+aggregated-from = "https://chromium.googlesource.com/chromium/src/+/main/third_party/rust/chromium_crates_io/supply-chain/audits.toml?format=TEXT"
+
+[audits.isrg.audits]
+
+[[audits.mozilla.audits.cpufeatures]]
+who = "Alex Franchuk <afranchuk@mozilla.com>"
+criteria = "safe-to-deploy"
+version = "0.3.1"
+notes = """
+No dependencies aside from libc, and no use of std. Unsafe code is minimal and necessary.
+"""
+aggregated-from = "https://raw.githubusercontent.com/mozilla/cargo-vet/main/supply-chain/audits.toml"
+
+[[audits.mozilla.audits.quote]]
+who = "Jan-Erik Rediger <jrediger@mozilla.com>"
+criteria = "safe-to-deploy"
+delta = "1.0.40 -> 1.0.45"
+aggregated-from = "https://raw.githubusercontent.com/mozilla/glean/main/supply-chain/audits.toml"
+
+[[audits.mozilla.audits.quote]]
+who = "Jan-Erik Rediger <jrediger@mozilla.com>"
+criteria = "safe-to-deploy"
+delta = "1.0.45 -> 1.0.47"
+aggregated-from = "https://raw.githubusercontent.com/mozilla/glean/main/supply-chain/audits.toml"
+
+[[audits.mozilla.audits.rustc_version]]
+who = "Nika Layzell <nika@thelayzells.com>"
+criteria = "safe-to-deploy"
+version = "0.4.0"
+notes = """
+Use of powerful capabilities is limited to invoking `rustc -vV` to get version
+information for parsing version information.
+"""
+aggregated-from = "https://raw.githubusercontent.com/mozilla/cargo-vet/main/supply-chain/audits.toml"
+
+[[audits.mozilla.audits.semver]]
+who = "Ben Dean-Kawamura <bdk@mozilla.com>"
+criteria = "safe-to-deploy"
+delta = "1.0.16 -> 1.0.28"
+notes = "Very few changes, mostly removes support for older Rust versions. Some unsafe code refactored, but it seemed to be functionally equivalent to me."
+aggregated-from = "https://raw.githubusercontent.com/mozilla-firefox/firefox/main/supply-chain/audits.toml"
+
+[[audits.mozilla.audits.semver]]
+who = "Bobby Holley <bobbyholley@gmail.com>"
+criteria = "safe-to-deploy"
+delta = "1.0.17 -> 1.0.16"
+aggregated-from = "https://raw.githubusercontent.com/mozilla-firefox/firefox/main/supply-chain/audits.toml"
+
+[[audits.mozilla.audits.simdutf8]]
+who = "Henri Sivonen <hsivonen@hsivonen.fi>"
+criteria = "safe-to-deploy"
+version = "0.1.5"
+notes = "Confidence in correctness of the algorithm is based on fuzzing the SSE 4.2 and AVX2 implementations rather than working through the logic of the code. Audit of aarch64 and Wasm is by comparing the code with the SSE 4.2 case."
+aggregated-from = "https://raw.githubusercontent.com/mozilla-firefox/firefox/main/supply-chain/audits.toml"
+
+[[audits.mozilla.audits.tinyvec]]
+who = "Alex Franchuk <afranchuk@mozilla.com>"
+criteria = "safe-to-deploy"
+delta = "1.9.0 -> 1.13.3"
+notes = "Unsafe code is forbidden, so there's no new unsafe code. There are 3 new optional dependencies, all reasonable (adding trait impls)."
+aggregated-from = "https://raw.githubusercontent.com/mozilla/cargo-vet/main/supply-chain/audits.toml"
+
+[[audits.trezor.audits.cty]]
+who = "matejcik <ja@matejcik.cz>"
+criteria = "safe-to-deploy"
+version = "0.2.2"
+
+[[audits.trezor.audits.ufmt-write]]
+who = "matejcik <ja@matejcik.cz>"
+criteria = "safe-to-deploy"
+version = "0.1.0"
+
+[audits.zcash.audits]Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.