diff --git a/.github/workflows/test-all-builds.yml b/.github/workflows/test-all-builds.yml index 7cebc377..6e79ea38 100644 --- a/.github/workflows/test-all-builds.yml +++ b/.github/workflows/test-all-builds.yml @@ -23,6 +23,11 @@ jobs: uses: actions/checkout@v4 with: submodules: 'recursive' + - name: Install Rust + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y \ + --profile minimal --default-toolchain stable --target riscv32imafc-unknown-none-elf + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" - name: Build (${{ matrix.board }}) run: | git config --global --add safe.directory "$GITHUB_WORKSPACE" diff --git a/.github/workflows/test-each-commit.yml b/.github/workflows/test-each-commit.yml index a0a13ba7..05ba86f8 100644 --- a/.github/workflows/test-each-commit.yml +++ b/.github/workflows/test-each-commit.yml @@ -77,6 +77,12 @@ jobs: - name: Install check dependencies run: apt-get update && apt-get install -y zlib1g-dev libmbedtls-dev + - name: Install Rust + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y \ + --profile minimal --default-toolchain stable --target riscv32imafc-unknown-none-elf + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + # Into the IDF Python env, which export.sh puts on PATH for the checks. - name: Install clang-format 21 run: . $IDF_PATH/export.sh && pip install 'clang-format==21.1.*' diff --git a/.gitignore b/.gitignore index 13a6d661..9b810b8d 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ sdkconfig sdkconfig.old managed_components/ compile_commands.json +**/target/ # Release release/ @@ -60,6 +61,9 @@ main/core/test/test_bip138_keys main/core/test/test_bip138_backup main/core/test/combined.o main/core/test/libwally.a +main/pages/bip_flow/test/test_bip_flow_register +main/pages/bip_flow/test/test_bip_flow_header +main/pages/bip_flow/test/test_bip388 # IDE / tools .vscode/ diff --git a/.gitmodules b/.gitmodules index 14d21d6c..b8c45e58 100644 --- a/.gitmodules +++ b/.gitmodules @@ -10,3 +10,6 @@ [submodule "components/bip138"] path = components/bip138 url = https://github.com/odudex/bip138.git +[submodule "components/bipqr/upstream"] + path = components/bipqr/upstream + url = https://github.com/pythcoiner/bipqr.git diff --git a/.justfile b/.justfile index 2699d5b9..1f7b7ffb 100644 --- a/.justfile +++ b/.justfile @@ -63,6 +63,14 @@ scan-prof board="wave_4b": (_check_board board) command -v idf.py >/dev/null || . $IDF_PATH/export.sh idf.py -B build_scanprof_{{board}} -D SDKCONFIG=build_scanprof_{{board}}/sdkconfig -D "SDKCONFIG_DEFAULTS=$(just _defaults {{board}});sdkconfig.scanprof" flash monitor +debug-log port="/dev/ttyACM0" board="wave_35": (_check_board board) + #!/usr/bin/env sh + set -e + command -v idf.py >/dev/null || . $IDF_PATH/export.sh + out="build_{{board}}/debug_storage.bin" + python -m esptool --chip esp32p4 -p {{port}} read-flash 0xc20000 0x8000 "$out" + strings "$out" | sed -n '/boot\|bip_flow\|descriptor_loader\|debug log trimmed/p' + format: ./scripts/format.sh @@ -81,6 +89,9 @@ fuzz iterations="20000": make -C main/core/test SANITIZE=1 FUZZ_ITERATIONS={{iterations}} fuzz make -C main/core/test clean +rust-setup: + rustup target add riscv32imafc-unknown-none-elf + clean: rm -fRd build build_wave_4b build_wave_35 build_wave_5 build_wave_43 build_crowpanel build_wave_7b build_p4_pico rm -fRd build_*_v3 @@ -95,6 +106,7 @@ clean: make -C components/secure_memory/test clean make -C components/bip138 clean make -C main/qr/test clean + make -C main/pages/bip_flow/test clean rm -rf components/k_quirc/test/build make -C main/core/test clean diff --git a/components/bbqr/src/bbqr.c b/components/bbqr/src/bbqr.c index 526996da..ac0ecaef 100644 --- a/components/bbqr/src/bbqr.c +++ b/components/bbqr/src/bbqr.c @@ -7,6 +7,7 @@ // Base36 alphabet (0-9, A-Z) static const char BASE36_ALPHABET[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; +static const char HEX_ALPHABET[] = "0123456789ABCDEF"; // BBQr spec: raw deflate with a 1KB window (wbits = -10) #define BBQR_COMPRESS_WBITS 10 @@ -66,7 +67,65 @@ bool bbqr_is_valid_encoding(char c) { bool bbqr_is_valid_file_type(char c) { return c == BBQR_TYPE_PSBT || c == BBQR_TYPE_TRANSACTION || - c == BBQR_TYPE_JSON || c == BBQR_TYPE_UNICODE; + c == BBQR_TYPE_JSON || c == BBQR_TYPE_UNICODE || c == BBQR_TYPE_BINARY; +} + +static BBQrParts *allocate_parts(size_t encoded_len, size_t payload_per_part, + int num_parts, char encoding, char file_type) { + BBQrParts *parts = (BBQrParts *)calloc(1, sizeof(BBQrParts)); + if (!parts) { + return NULL; + } + + parts->parts = (char **)calloc(num_parts, sizeof(char *)); + if (!parts->parts) { + free(parts); + return NULL; + } + + parts->count = num_parts; + parts->encoding = encoding; + parts->file_type = file_type; + + if (encoded_len > SIZE_MAX - (size_t)num_parts * (BBQR_HEADER_LEN + 1)) { + free(parts->parts); + free(parts); + return NULL; + } + size_t storage_len = encoded_len + (size_t)num_parts * (BBQR_HEADER_LEN + 1); + parts->storage = (char *)malloc(storage_len); + if (!parts->storage) { + free(parts->parts); + free(parts); + return NULL; + } + + size_t storage_offset = 0; + char total_c1, total_c2; + bbqr_base36_encode(num_parts, &total_c1, &total_c2); + for (int i = 0; i < num_parts; i++) { + size_t this_payload_len = + part_payload_len(encoded_len, payload_per_part, i); + + char index_c1, index_c2; + bbqr_base36_encode(i, &index_c1, &index_c2); + + char *part = parts->storage + storage_offset; + parts->parts[i] = part; + part[0] = 'B'; + part[1] = '$'; + part[2] = encoding; + part[3] = file_type; + part[4] = total_c1; + part[5] = total_c2; + part[6] = index_c1; + part[7] = index_c2; + part[BBQR_HEADER_LEN + this_payload_len] = '\0'; + + storage_offset += BBQR_HEADER_LEN + this_payload_len + 1; + } + + return parts; } int bbqr_base36_decode(char c1, char c2) { @@ -109,8 +168,9 @@ bool bbqr_parse_part(const char *data, size_t data_len, BBQrPart *part) { return false; } - // Check magic "B$" - if (data[0] != 'B' || data[1] != '$') { + // Check magic "B$" case-insensitively; other alphanumeric header fields are + // normalized below as well. + if (toupper((unsigned char)data[0]) != 'B' || data[1] != '$') { return false; } @@ -315,78 +375,82 @@ BBQrParts *bbqr_encode(const uint8_t *data, size_t data_len, char file_type, payload_per_part = ((payload_per_part + 7) / 8) * 8; // Round up to multiple of 8 - // Allocate parts structure - BBQrParts *parts = (BBQrParts *)calloc(1, sizeof(BBQrParts)); + BBQrParts *parts = allocate_parts(encoded_len, (size_t)payload_per_part, + num_parts, encoding, file_type); if (!parts) { free(compressed); return NULL; } - parts->parts = (char **)calloc(num_parts, sizeof(char *)); - if (!parts->parts) { - free(parts); - free(compressed); + bbqr_parts_writer_t writer = { + .parts = parts, + .part_index = 0, + .payload_offset = 0, + .payload_per_part = (size_t)payload_per_part, + .encoded_len = encoded_len, + .total_written = 0, + }; + bool encoded = + base32_encode_write(to_encode, to_encode_len, write_to_parts, &writer); + free(compressed); + if (!encoded || writer.total_written != encoded_len) { + bbqr_parts_free(parts); return NULL; } - parts->count = num_parts; - parts->encoding = encoding; - parts->file_type = file_type; + return parts; +} - if (encoded_len > SIZE_MAX - (size_t)num_parts * (BBQR_HEADER_LEN + 1)) { - free(parts->parts); - free(parts); - free(compressed); +BBQrParts *bbqr_encode_hex(const uint8_t *data, size_t data_len, char file_type, + int max_chars_per_qr) { + if (!data || data_len == 0 || !bbqr_is_valid_file_type(file_type)) { return NULL; } - size_t storage_len = encoded_len + (size_t)num_parts * (BBQR_HEADER_LEN + 1); - parts->storage = (char *)malloc(storage_len); - if (!parts->storage) { - free(parts->parts); - free(parts); - free(compressed); + + if (max_chars_per_qr < BBQR_HEADER_LEN + 2) { return NULL; } - // Generate headers and lay out all part strings in one allocation. - size_t storage_offset = 0; - char total_c1, total_c2; - bbqr_base36_encode(num_parts, &total_c1, &total_c2); - for (int i = 0; i < num_parts; i++) { - size_t this_payload_len = - part_payload_len(encoded_len, (size_t)payload_per_part, i); + if (data_len > SIZE_MAX / 2) { + return NULL; + } + size_t encoded_len = data_len * 2; - // Build header: B$ + encoding + file_type + total(2) + index(2) - char index_c1, index_c2; - bbqr_base36_encode(i, &index_c1, &index_c2); + int max_payload_per_part = max_chars_per_qr - BBQR_HEADER_LEN; + size_t payload_per_part = (size_t)(max_payload_per_part & ~1); + if (payload_per_part == 0) { + return NULL; + } - char *part = parts->storage + storage_offset; - parts->parts[i] = part; - part[0] = 'B'; - part[1] = '$'; - part[2] = encoding; - part[3] = file_type; - part[4] = total_c1; - part[5] = total_c2; - part[6] = index_c1; - part[7] = index_c2; - part[BBQR_HEADER_LEN + this_payload_len] = '\0'; + size_t parts_needed = + encoded_len / payload_per_part + (encoded_len % payload_per_part != 0); + if (parts_needed == 0 || parts_needed > 1295) { + return NULL; + } + int num_parts = (int)parts_needed; - storage_offset += BBQR_HEADER_LEN + this_payload_len + 1; + payload_per_part = (encoded_len + (size_t)num_parts - 1) / (size_t)num_parts; + payload_per_part = (payload_per_part + 1) & ~(size_t)1; + + BBQrParts *parts = allocate_parts(encoded_len, payload_per_part, num_parts, + BBQR_ENCODING_HEX, file_type); + if (!parts) { + return NULL; } - bbqr_parts_writer_t writer = { - .parts = parts, - .part_index = 0, - .payload_offset = 0, - .payload_per_part = (size_t)payload_per_part, - .encoded_len = encoded_len, - .total_written = 0, - }; - bool encoded = - base32_encode_write(to_encode, to_encode_len, write_to_parts, &writer); - free(compressed); - if (!encoded || writer.total_written != encoded_len) { + size_t byte_offset = 0; + for (int i = 0; i < parts->count; i++) { + char *payload = parts->parts[i] + BBQR_HEADER_LEN; + size_t payload_len = part_payload_len(encoded_len, payload_per_part, i); + size_t bytes_this_part = payload_len / 2; + for (size_t j = 0; j < bytes_this_part; j++) { + uint8_t byte = data[byte_offset++]; + payload[j * 2] = HEX_ALPHABET[byte >> 4]; + payload[j * 2 + 1] = HEX_ALPHABET[byte & 0x0f]; + } + } + + if (byte_offset != data_len) { bbqr_parts_free(parts); return NULL; } diff --git a/components/bbqr/src/bbqr.h b/components/bbqr/src/bbqr.h index 9c3a7bb8..0b38dd09 100644 --- a/components/bbqr/src/bbqr.h +++ b/components/bbqr/src/bbqr.h @@ -19,6 +19,7 @@ #define BBQR_TYPE_TRANSACTION 'T' // Raw Bitcoin transaction #define BBQR_TYPE_JSON 'J' // JSON data #define BBQR_TYPE_UNICODE 'U' // Unicode text +#define BBQR_TYPE_BINARY 'B' // Generic binary data /** * @brief Header length for BBQr format @@ -113,6 +114,22 @@ uint8_t *bbqr_decode_payload(char encoding, const char *data, size_t data_len, BBQrParts *bbqr_encode(const uint8_t *data, size_t data_len, char file_type, int max_chars_per_qr); +/** + * @brief Encode binary data as hex BBQr parts. + * + * Encodes the input data using BBQr hexadecimal encoding, without compression. + * This is the transport used by bipqr response messages (B$HB). + * + * @param data Binary data to encode + * @param data_len Length of data + * @param file_type File type character ('P', 'T', 'J', 'U', 'B') + * @param max_chars_per_qr Maximum characters per QR code (including header) + * @return Pointer to BBQrParts structure, or NULL on failure. + * Caller must free using bbqr_parts_free(). + */ +BBQrParts *bbqr_encode_hex(const uint8_t *data, size_t data_len, char file_type, + int max_chars_per_qr); + /** * @brief Free BBQrParts structure * diff --git a/components/bbqr/test/test_bbqr.c b/components/bbqr/test/test_bbqr.c index a0c431d9..4b715e90 100644 --- a/components/bbqr/test/test_bbqr.c +++ b/components/bbqr/test/test_bbqr.c @@ -181,6 +181,83 @@ void test_bbqr_parse_header(void) { PASS(); } +void test_bbqr_binary_file_type(void) { + TEST("bbqr accepts binary file type"); + + const char *qr = "B$HB0100BEEF"; + BBQrPart part; + if (!bbqr_parse_part(qr, strlen(qr), &part)) { + FAIL("Parse failed"); + return; + } + + if (part.encoding != BBQR_ENCODING_HEX || + part.file_type != BBQR_TYPE_BINARY || part.total != 1 || + part.index != 0 || part.payload_len != 4 || + strncmp(part.payload, "BEEF", 4) != 0) { + FAIL("Wrong parsed fields"); + return; + } + + PASS(); +} + +void test_bbqr_hex_binary_encode(void) { + TEST("bbqr hex binary encode"); + + const uint8_t original[] = {0x42, 0x49, 0x50, 0x58, 0x58, 0x58, + 0x01, 0x04, 0xde, 0xad, 0xbe, 0xef}; + BBQrParts *parts = + bbqr_encode_hex(original, sizeof(original), BBQR_TYPE_BINARY, 18); + if (!parts) { + FAIL("Encode failed"); + return; + } + + bool valid = parts->count > 1 && parts->encoding == BBQR_ENCODING_HEX && + parts->file_type == BBQR_TYPE_BINARY && parts->storage != NULL; + size_t payload_len = 0; + for (int i = 0; valid && i < parts->count; i++) { + BBQrPart part; + valid = bbqr_parse_part(parts->parts[i], strlen(parts->parts[i]), &part) && + part.encoding == BBQR_ENCODING_HEX && + part.file_type == BBQR_TYPE_BINARY && part.total == parts->count && + part.index == i && strlen(parts->parts[i]) <= 18; + payload_len += valid ? part.payload_len : 0; + } + + char *payload = valid ? (char *)malloc(payload_len) : NULL; + if (!payload) { + bbqr_parts_free(parts); + FAIL("Invalid parts or allocation failed"); + return; + } + + size_t offset = 0; + for (int i = 0; i < parts->count; i++) { + BBQrPart part; + bbqr_parse_part(parts->parts[i], strlen(parts->parts[i]), &part); + memcpy(payload + offset, part.payload, part.payload_len); + offset += part.payload_len; + } + + size_t decoded_len = 0; + uint8_t *decoded = bbqr_decode_payload(BBQR_ENCODING_HEX, payload, + payload_len, &decoded_len); + free(payload); + if (!decoded || decoded_len != sizeof(original) || + memcmp(decoded, original, sizeof(original)) != 0) { + free(decoded); + bbqr_parts_free(parts); + FAIL("Decoded data mismatch"); + return; + } + + free(decoded); + bbqr_parts_free(parts); + PASS(); +} + /* Test BBQr encode/decode round-trip */ void test_bbqr_roundtrip(void) { TEST("bbqr encode/decode round-trip"); @@ -648,6 +725,8 @@ int main(void) { test_base32_roundtrip(); test_base36(); test_bbqr_parse_header(); + test_bbqr_binary_file_type(); + test_bbqr_hex_binary_encode(); test_bbqr_roundtrip(); test_bbqr_unpadded_base32(); test_bbqr_compression_quality(); diff --git a/components/bipqr/CMakeLists.txt b/components/bipqr/CMakeLists.txt new file mode 100644 index 00000000..5fe12459 --- /dev/null +++ b/components/bipqr/CMakeLists.txt @@ -0,0 +1,30 @@ +set(RUST_TARGET riscv32imafc-unknown-none-elf) +set(RUST_TARGET_DIR ${CMAKE_CURRENT_BINARY_DIR}/target) +set(RUST_LIB ${RUST_TARGET_DIR}/${RUST_TARGET}/release/libkern_bipqr.a) + +idf_component_register( + SRCS "dummy.c" + INCLUDE_DIRS + "upstream/bipqr-ll/include" +) + +find_program(CARGO_EXECUTABLE cargo REQUIRED) + +# Always runs: cargo tracks the bipqr sources and only relinks on a change +add_custom_target(bipqr_rust + COMMAND ${CMAKE_COMMAND} -E env CARGO_TARGET_DIR=${RUST_TARGET_DIR} + ${CARGO_EXECUTABLE} build --manifest-path ${CMAKE_CURRENT_LIST_DIR}/Cargo.toml + --release --target ${RUST_TARGET} + # The prebuilt compiler_builtins C objects are soft-float; libgcc's are not + COMMAND ${CMAKE_COMMAND} -DAR=${CMAKE_AR} -DLIB=${RUST_LIB} + -P ${CMAKE_CURRENT_LIST_DIR}/strip_c_builtins.cmake + BYPRODUCTS ${RUST_LIB} + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} + COMMENT "Building bipqr Rust staticlib" + VERBATIM +) +add_library(bipqr_static STATIC IMPORTED GLOBAL) +set_target_properties(bipqr_static PROPERTIES IMPORTED_LOCATION ${RUST_LIB}) +add_dependencies(bipqr_static bipqr_rust) +add_dependencies(${COMPONENT_LIB} bipqr_static) +target_link_libraries(${COMPONENT_LIB} INTERFACE bipqr_static) diff --git a/components/bipqr/Cargo.lock b/components/bipqr/Cargo.lock new file mode 100644 index 00000000..0380491b --- /dev/null +++ b/components/bipqr/Cargo.lock @@ -0,0 +1,14 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bipqr-ll" +version = "0.0.1" + +[[package]] +name = "kern-bipqr" +version = "0.1.0" +dependencies = [ + "bipqr-ll", +] diff --git a/components/bipqr/Cargo.toml b/components/bipqr/Cargo.toml new file mode 100644 index 00000000..547c6577 --- /dev/null +++ b/components/bipqr/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "kern-bipqr" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["staticlib"] + +[dependencies] +bipqr-ll = { path = "upstream/bipqr-ll", features = ["ffi"] } + +[profile.dev] +panic = "abort" + +[profile.release] +panic = "abort" diff --git a/components/bipqr/dummy.c b/components/bipqr/dummy.c new file mode 100644 index 00000000..4f990009 --- /dev/null +++ b/components/bipqr/dummy.c @@ -0,0 +1 @@ +/* ESP-IDF requires a component source file; the symbols come from Rust. */ diff --git a/components/bipqr/src/lib.rs b/components/bipqr/src/lib.rs new file mode 100644 index 00000000..4ce508f8 --- /dev/null +++ b/components/bipqr/src/lib.rs @@ -0,0 +1,43 @@ +#![cfg_attr(target_os = "none", no_std)] + +#[cfg(target_os = "none")] +use core::alloc::{GlobalAlloc, Layout}; +#[cfg(target_os = "none")] +use core::ffi::c_void; +#[cfg(target_os = "none")] +use core::panic::PanicInfo; + +pub use bipqr_ll::ffi::{ + bipqr_buf_free, bipqr_request_decode, bipqr_request_free, bipqr_response_encode, +}; + +#[cfg(target_os = "none")] +struct CAllocator; + +#[cfg(target_os = "none")] +extern "C" { + fn malloc(size: usize) -> *mut c_void; + fn free(ptr: *mut c_void); + fn abort() -> !; +} + +#[cfg(target_os = "none")] +unsafe impl GlobalAlloc for CAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + malloc(layout.size().max(1)).cast() + } + + unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { + free(ptr.cast()); + } +} + +#[cfg(target_os = "none")] +#[global_allocator] +static ALLOCATOR: CAllocator = CAllocator; + +#[cfg(target_os = "none")] +#[panic_handler] +fn panic(_info: &PanicInfo<'_>) -> ! { + unsafe { abort() } +} diff --git a/components/bipqr/strip_c_builtins.cmake b/components/bipqr/strip_c_builtins.cmake new file mode 100644 index 00000000..6b5395b2 --- /dev/null +++ b/components/bipqr/strip_c_builtins.cmake @@ -0,0 +1,13 @@ +# Drops every non-Rust object (compiler_builtins' C intrinsics) from ${LIB}. +execute_process(COMMAND ${AR} t ${LIB} OUTPUT_VARIABLE members + COMMAND_ERROR_IS_FATAL ANY) +string(REPLACE "\n" ";" members "${members}") +set(c_objects) +foreach(member IN LISTS members) + if(member MATCHES "\\.o$" AND NOT member MATCHES "\\.rcgu\\.o$") + list(APPEND c_objects ${member}) + endif() +endforeach() +if(c_objects) + execute_process(COMMAND ${AR} d ${LIB} ${c_objects} COMMAND_ERROR_IS_FATAL ANY) +endif() diff --git a/components/bipqr/upstream b/components/bipqr/upstream new file mode 160000 index 00000000..d7363e0e --- /dev/null +++ b/components/bipqr/upstream @@ -0,0 +1 @@ +Subproject commit d7363e0ea67af01b0407deff5f33c499a627f897 diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 8f0266c2..5e382ff9 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -4,8 +4,7 @@ if(CMAKE_SCRIPT_MODE_FILE) else() file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "*.c") endif() -list(FILTER SOURCES EXCLUDE REGEX ".*/core/test/.*") -list(FILTER SOURCES EXCLUDE REGEX ".*/qr/test/.*") +list(FILTER SOURCES EXCLUDE REGEX ".*/test/.*") # Select touch driver based on board if(CONFIG_KERN_BOARD_WAVE_4B) @@ -43,7 +42,7 @@ idf_component_register( INCLUDE_DIRS . PRIV_REQUIRES lvgl ${TOUCH_DRIVER} k_quirc esp_timer wave_4b wave_35 wave_5 wave_43 crowpanel wave_7b p4_pico libwally-core cUR sd_card bbqr deflate_codec video spiffs - nvs_flash efuse esp_hw_support esp_app_format mbedtls bip138 + nvs_flash efuse esp_hw_support esp_app_format mbedtls bip138 bipqr esp_driver_ppa app_update bootloader_support secure_memory bsp_common bus_timeout ) diff --git a/main/Kconfig.projbuild b/main/Kconfig.projbuild index 9b799440..809165ab 100644 --- a/main/Kconfig.projbuild +++ b/main/Kconfig.projbuild @@ -28,6 +28,16 @@ menu "Kern Configuration" bool "Waveshare ESP32-P4-Pico + 5-DSI-TOUCH-A (720x1280 MIPI DSI)" endchoice + config KERN_BOARD_NAME + string + default "wave_4b" if KERN_BOARD_WAVE_4B + default "wave_35" if KERN_BOARD_WAVE_35 + default "wave_5" if KERN_BOARD_WAVE_5 + default "wave_43" if KERN_BOARD_WAVE_43 + default "crowpanel" if KERN_BOARD_CROWPANEL + default "wave_7b" if KERN_BOARD_WAVE_7B + default "p4_pico" if KERN_BOARD_P4_PICO + config KERN_PBKDF2_HW_SHA bool "Drive PBKDF2-HMAC-SHA256 and -SHA512 on the P4 SHA accelerator" default y diff --git a/main/core/bip138_backup.c b/main/core/bip138_backup.c index 30bd0f44..208fbeea 100644 --- a/main/core/bip138_backup.c +++ b/main/core/bip138_backup.c @@ -13,10 +13,15 @@ #include /* Approval mark: a vendor item whose data is HMAC-SHA256 over the descriptor - * bytes under a key derived from this seed. Recipients of the backup hold only - * public keys, so they can read it but not forge it. */ + * bytes, then a 0x00 and the alias when the backup has one, under a key + * derived from this seed. Recipients of the backup hold only public keys, so + * they can read it but not forge it. */ static const uint8_t approval_tag[] = "kern-approval"; #define APPROVAL_TAG_LEN (sizeof(approval_tag) - 1) +/* The alias a registration is stored under, kept whole whatever the filename */ +static const uint8_t alias_tag[] = "kern-alias"; +#define ALIAS_TAG_LEN (sizeof(alias_tag) - 1) +static const uint8_t alias_separator[] = {0x00}; #define APPROVAL_KEY_TAG "KERN_BIP138_APPROVAL" static const uint32_t approval_path[] = {0x4B45524Eu | BIP32_PATH_HARDENED, 138u | BIP32_PATH_HARDENED}; @@ -60,19 +65,40 @@ static bool approval_key(uint8_t out[32]) { return true; } -static bool approval_mac(const uint8_t *descriptor, size_t len, - uint8_t out[HMAC_SHA256_LEN]) { +/* The mark over the concatenation of `n` parts */ +static bool approval_mac(const uint8_t *const *parts, const size_t *lens, + size_t n, uint8_t out[HMAC_SHA256_LEN]) { + size_t len = 0; + for (size_t i = 0; i < n; i++) + len += lens[i]; + uint8_t *data = malloc(len ? len : 1); uint8_t mac_key[32]; - if (!approval_key(mac_key)) - return false; - bool ok = wally_hmac_sha256(mac_key, sizeof(mac_key), descriptor, len, out, - HMAC_SHA256_LEN) == WALLY_OK; + bool ok = data && approval_key(mac_key); + if (ok) { + size_t off = 0; + for (size_t i = 0; i < n; i++) { + memcpy(data + off, parts[i], lens[i]); + off += lens[i]; + } + ok = wally_hmac_sha256(mac_key, sizeof(mac_key), data, len, out, + HMAC_SHA256_LEN) == WALLY_OK; + } secure_memzero(mac_key, sizeof(mac_key)); + free(data); return ok; } -bool bip138_backup_encrypt(const char *descriptor, uint8_t **blob_out, - size_t *blob_len) { +/* The mark of a backup: over the descriptor, and its alias when present */ +static bool backup_mac(const uint8_t *descriptor, size_t len, + const uint8_t *alias, size_t alias_len, + uint8_t out[HMAC_SHA256_LEN]) { + const uint8_t *parts[] = {descriptor, alias_separator, alias}; + size_t lens[] = {len, sizeof(alias_separator), alias_len}; + return approval_mac(parts, lens, alias ? 3 : 1, out); +} + +bool bip138_backup_encrypt(const char *descriptor, const char *alias, + uint8_t **blob_out, size_t *blob_len) { uint8_t keys[BIP138_KEYS_MAX * BIP138_KEY_LEN]; bip138_key_origin origins[BIP138_BACKUP_MAX_PATHS]; bip138_path paths[BIP138_BACKUP_MAX_PATHS]; @@ -96,17 +122,22 @@ bool bip138_backup_encrypt(const char *descriptor, uint8_t **blob_out, paths[i].depth = origins[i].depth; } size_t descriptor_len = strlen(descriptor); - if (!approval_mac((const uint8_t *)descriptor, descriptor_len, mac)) + if (!backup_mac((const uint8_t *)descriptor, descriptor_len, + (const uint8_t *)alias, alias ? strlen(alias) : 0, mac)) return false; - bip138_item items[2] = { + bip138_item items[3] = { {{BIP138_CONTENT_BIP, BIP138_BIP_DESCRIPTOR, NULL, 0}, (const uint8_t *)descriptor, descriptor_len}, {{BIP138_CONTENT_PROPRIETARY, 0, approval_tag, APPROVAL_TAG_LEN}, mac, - sizeof(mac)}}; - size_t pt_len = bip138_plaintext_size(items, 2, 0); + sizeof(mac)}, + {{BIP138_CONTENT_PROPRIETARY, 0, alias_tag, ALIAS_TAG_LEN}, + (const uint8_t *)alias, + alias ? strlen(alias) : 0}}; + size_t n_items = alias ? 3 : 2; + size_t pt_len = bip138_plaintext_size(items, n_items, 0); size_t cap = bip138_encrypt_size(bip138_secret_bucket(count), paths, n_paths, pt_len); if (pt_len == 0 || cap == 0) @@ -115,12 +146,12 @@ bool bip138_backup_encrypt(const char *descriptor, uint8_t **blob_out, uint8_t *blob = malloc(cap); /* Every origin is kept, common ones included, so recovery under any of the * descriptor's keys is a single derivation instead of a common-path walk. */ - bool ok = - pt && blob && - bip138_plaintext_encode(items, 2, 0, pt, pt_len, &pt_len) == BIP138_OK && - bip138_encrypt_flags(kern_bip138_crypto(), keys, count, paths, n_paths, - BIP138_FLAG_KEEP_COMMON_PATHS, pt, pt_len, blob, cap, - blob_len) == BIP138_OK; + bool ok = pt && blob && + bip138_plaintext_encode(items, n_items, 0, pt, pt_len, &pt_len) == + BIP138_OK && + bip138_encrypt_flags(kern_bip138_crypto(), keys, count, paths, + n_paths, BIP138_FLAG_KEEP_COMMON_PATHS, pt, + pt_len, blob, cap, blob_len) == BIP138_OK; SECURE_FREE_BUFFER(pt, pt_len); if (!ok) { free(blob); @@ -222,33 +253,58 @@ static size_t collect_hints(const bip138_container *cont, hint_path_t *hints) { return n; } +static bool is_proprietary(const bip138_item *item, const uint8_t *tag, + size_t tag_len) { + return item->content.type == BIP138_CONTENT_PROPRIETARY && + item->content.tag_len == tag_len && + memcmp(item->content.tag, tag, tag_len) == 0; +} + +/* The descriptor, approval mark and alias items, in that order in `slots` */ static bool find_items(const uint8_t *pt, size_t pt_len, bip138_item *slots, - bool *have_mark) { + bool *have_mark, bool *have_alias) { bip138_item_iter it; bip138_item item; bool have_descriptor = false; *have_mark = false; + *have_alias = false; bip138_item_iter_init(&it, pt, pt_len); while (bip138_item_next(&it, &item) == 1) { if (!have_descriptor && item.content.type == BIP138_CONTENT_BIP && item.content.bip == BIP138_BIP_DESCRIPTOR) { slots[0] = item; have_descriptor = true; - } else if (!*have_mark && item.content.type == BIP138_CONTENT_PROPRIETARY && - item.content.tag_len == APPROVAL_TAG_LEN && - memcmp(item.content.tag, approval_tag, APPROVAL_TAG_LEN) == 0 && + } else if (!*have_mark && + is_proprietary(&item, approval_tag, APPROVAL_TAG_LEN) && item.data_len == HMAC_SHA256_LEN) { slots[1] = item; *have_mark = true; + } else if (!*have_alias && + is_proprietary(&item, alias_tag, ALIAS_TAG_LEN)) { + slots[2] = item; + *have_alias = true; } } return have_descriptor; } +static char *item_string_alloc(const bip138_item *item) { + char *out = malloc(item->data_len + 1); + if (out) { + memcpy(out, item->data, item->data_len); + out[item->data_len] = '\0'; + } + return out; +} + +/* `alias_item` is NULL for a backup without alias */ static bool mark_is_valid(const bip138_item *descriptor_item, - const bip138_item *mark_item) { + const bip138_item *mark_item, + const bip138_item *alias_item) { uint8_t expected[HMAC_SHA256_LEN]; - if (!approval_mac(descriptor_item->data, descriptor_item->data_len, expected)) + if (!backup_mac(descriptor_item->data, descriptor_item->data_len, + alias_item ? alias_item->data : NULL, + alias_item ? alias_item->data_len : 0, expected)) return false; uint8_t diff = 0; for (size_t i = 0; i < HMAC_SHA256_LEN; i++) @@ -257,8 +313,8 @@ static bool mark_is_valid(const bip138_item *descriptor_item, } static bool decrypt_impl(const uint8_t *blob, size_t blob_len, - char **descriptor_out, bool *approved_out, - bool walk_common) { + char **descriptor_out, char **alias_out, + bool *approved_out, bool walk_common) { bip138_container cont; hint_path_t hints[BIP138_BACKUP_MAX_PATHS]; uint8_t xonly[BIP138_KEY_LEN]; @@ -267,6 +323,8 @@ static bool decrypt_impl(const uint8_t *blob, size_t blob_len, if (approved_out) *approved_out = false; + if (alias_out) + *alias_out = NULL; if (!blob || !descriptor_out || blob_len > BIP138_BACKUP_MAX_LEN || bip138_parse(blob, blob_len, &cont) != BIP138_OK) return false; @@ -291,17 +349,24 @@ static bool decrypt_impl(const uint8_t *blob, size_t blob_len, } bool ok = false; - bip138_item slots[2]; + bip138_item slots[3]; bool have_mark = false; - if (found && find_items(pt, pt_len, slots, &have_mark)) { - char *descriptor = malloc(slots[0].data_len + 1); - if (descriptor) { - memcpy(descriptor, slots[0].data, slots[0].data_len); - descriptor[slots[0].data_len] = '\0'; + bool have_alias = false; + if (found && find_items(pt, pt_len, slots, &have_mark, &have_alias)) { + char *descriptor = item_string_alloc(&slots[0]); + char *alias = alias_out && have_alias ? item_string_alloc(&slots[2]) : NULL; + if (descriptor && (!alias_out || !have_alias || alias)) { *descriptor_out = descriptor; + if (alias_out) + *alias_out = alias; if (approved_out) - *approved_out = have_mark && mark_is_valid(&slots[0], &slots[1]); + *approved_out = + have_mark && + mark_is_valid(&slots[0], &slots[1], have_alias ? &slots[2] : NULL); ok = true; + } else { + free(descriptor); + free(alias); } } SECURE_FREE_BUFFER(pt, pt_cap); @@ -309,8 +374,10 @@ static bool decrypt_impl(const uint8_t *blob, size_t blob_len, } bool bip138_backup_decrypt(const uint8_t *blob, size_t blob_len, - char **descriptor_out, bool *approved_out) { - return decrypt_impl(blob, blob_len, descriptor_out, approved_out, true); + char **descriptor_out, char **alias_out, + bool *approved_out) { + return decrypt_impl(blob, blob_len, descriptor_out, alias_out, approved_out, + true); } bool bip138_backup_detect(const uint8_t *data, size_t len) { @@ -320,33 +387,39 @@ bool bip138_backup_detect(const uint8_t *data, size_t len) { } static bool decrypt_any_impl(const uint8_t *data, size_t len, - char **descriptor_out, bool *approved_out, - bool walk_common) { + char **descriptor_out, char **alias_out, + bool *approved_out, bool walk_common) { if (approved_out) *approved_out = false; + if (alias_out) + *alias_out = NULL; if (!data || len == 0 || len > BIP138_BACKUP_MAX_LEN * 2) return false; if (bip138_is_container(data, len)) - return decrypt_impl(data, len, descriptor_out, approved_out, walk_common); + return decrypt_impl(data, len, descriptor_out, alias_out, approved_out, + walk_common); size_t cap = BIP138_BASE64_DECODED_MAX(len); uint8_t *blob = malloc(cap); size_t blob_len = 0; - bool ok = - blob && - bip138_base64_decode((const char *)data, len, blob, cap, &blob_len) == - BIP138_OK && - decrypt_impl(blob, blob_len, descriptor_out, approved_out, walk_common); + bool ok = blob && + bip138_base64_decode((const char *)data, len, blob, cap, + &blob_len) == BIP138_OK && + decrypt_impl(blob, blob_len, descriptor_out, alias_out, + approved_out, walk_common); free(blob); return ok; } bool bip138_backup_decrypt_any(const uint8_t *data, size_t len, - char **descriptor_out, bool *approved_out) { - return decrypt_any_impl(data, len, descriptor_out, approved_out, true); + char **descriptor_out, char **alias_out, + bool *approved_out) { + return decrypt_any_impl(data, len, descriptor_out, alias_out, approved_out, + true); } bool bip138_backup_decrypt_any_hinted(const uint8_t *data, size_t len, - char **descriptor_out, + char **descriptor_out, char **alias_out, bool *approved_out) { - return decrypt_any_impl(data, len, descriptor_out, approved_out, false); + return decrypt_any_impl(data, len, descriptor_out, alias_out, approved_out, + false); } diff --git a/main/core/bip138_backup.h b/main/core/bip138_backup.h index 93fd2c1b..4deed0ca 100644 --- a/main/core/bip138_backup.h +++ b/main/core/bip138_backup.h @@ -15,10 +15,13 @@ /* BIP138 container holding the descriptor, addressed to the descriptor's own * root keys, with every key's origin path stored as a recovery hint and this - * device's approval mark (an HMAC under a key only this seed can derive). - * Refuses descriptors carrying private keys. *blob_out is malloc'd; the caller - * frees it. */ + * device's approval mark (an HMAC under a key only this seed can derive), + * which covers the alias too. + * Refuses descriptors carrying private keys. `alias` (optional) is the name + * the descriptor is registered under. *blob_out is malloc'd; the caller frees + * it. */ KERN_WARN_UNUSED_RESULT bool bip138_backup_encrypt(const char *descriptor, + const char *alias, uint8_t **blob_out, size_t *blob_len); @@ -28,16 +31,19 @@ KERN_WARN_UNUSED_RESULT bool bip138_backup_encrypt(const char *descriptor, * wrote it after the user confirmed the descriptor; a backup from another * wallet, or one forged from a public xpub, decrypts with approved false. * *descriptor_out is malloc'd and NUL-terminated; free it with - * SECURE_FREE_STRING. */ + * SECURE_FREE_STRING. *alias_out (optional) receives the registration alias, + * malloc'd, or NULL when the backup has none. */ KERN_WARN_UNUSED_RESULT bool bip138_backup_decrypt(const uint8_t *blob, size_t blob_len, char **descriptor_out, + char **alias_out, bool *approved_out); /* Accepts either the binary container or its base64 text. */ KERN_WARN_UNUSED_RESULT bool bip138_backup_decrypt_any(const uint8_t *data, size_t len, char **descriptor_out, + char **alias_out, bool *approved_out); /* Same, trying only the paths the container itself stores, never the common @@ -48,7 +54,8 @@ KERN_WARN_UNUSED_RESULT bool bip138_backup_decrypt_any(const uint8_t *data, * common paths. */ KERN_WARN_UNUSED_RESULT bool bip138_backup_decrypt_any_hinted(const uint8_t *data, size_t len, - char **descriptor_out, bool *approved_out); + char **descriptor_out, char **alias_out, + bool *approved_out); /* True for a binary container or its base64 text form. */ bool bip138_backup_detect(const uint8_t *data, size_t len); diff --git a/main/core/debug_log.c b/main/core/debug_log.c new file mode 100644 index 00000000..e1d858e0 --- /dev/null +++ b/main/core/debug_log.c @@ -0,0 +1,97 @@ +#include "debug_log.h" + +#include "storage.h" + +#include +#include +#include +#include +#include +#include +#include + +static const char *TAG = "debug_log"; +static const size_t DEBUG_LOG_MAX_BYTES = 8192; + +static esp_err_t trim_if_needed(void) { + struct stat st; + if (stat(DEBUG_LOG_FLASH_PATH, &st) != 0 || st.st_size < 0 || + (size_t)st.st_size <= DEBUG_LOG_MAX_BYTES) + return ESP_OK; + + FILE *f = fopen(DEBUG_LOG_FLASH_PATH, "rb"); + if (!f) + return ESP_FAIL; + + size_t keep = DEBUG_LOG_MAX_BYTES / 2; + if (fseek(f, st.st_size - (long)keep, SEEK_SET) != 0) { + fclose(f); + return ESP_FAIL; + } + + char buf[4096]; + size_t nread = fread(buf, 1, sizeof(buf), f); + fclose(f); + + f = fopen(DEBUG_LOG_FLASH_PATH, "wb"); + if (!f) + return ESP_FAIL; + + const char *prefix = "--- debug log trimmed ---\n"; + size_t expected = strlen(prefix) + nread; + size_t written = fwrite(prefix, 1, strlen(prefix), f); + written += fwrite(buf, 1, nread, f); + fclose(f); + return written == expected ? ESP_OK : ESP_FAIL; +} + +esp_err_t debug_log_init(void) { return storage_init(); } + +esp_err_t debug_log_clear(void) { + esp_err_t ret = storage_init(); + if (ret != ESP_OK) + return ret; + unlink(DEBUG_LOG_FLASH_PATH); + return ESP_OK; +} + +void debug_logf(const char *fmt, ...) { + if (!fmt || storage_init() != ESP_OK) + return; + + if (trim_if_needed() != ESP_OK) + ESP_LOGW(TAG, "failed to trim debug log"); + + FILE *f = fopen(DEBUG_LOG_FLASH_PATH, "ab"); + if (!f) + return; + + fprintf(f, "%lld ", (long long)esp_timer_get_time()); + + va_list ap; + va_start(ap, fmt); + vfprintf(f, fmt, ap); + va_end(ap); + fputc('\n', f); + fclose(f); +} + +void debug_log_event(const char *event) { debug_logf("%s", event); } + +void debug_log_hex_preview(const char *label, const uint8_t *data, size_t len, + size_t preview_len) { + if (!label) + return; + + char hex[65]; + size_t n = len < preview_len ? len : preview_len; + if (n > sizeof(hex) / 2) + n = sizeof(hex) / 2; + + for (size_t i = 0; i < n; i++) + snprintf(hex + i * 2, sizeof(hex) - i * 2, "%02X", data ? data[i] : 0); + hex[n * 2] = '\0'; + + debug_logf("%s len=%u preview=%s%s", label, (unsigned)len, hex, + len > n ? "..." : ""); +} diff --git a/main/core/debug_log.h b/main/core/debug_log.h new file mode 100644 index 00000000..236e7ec8 --- /dev/null +++ b/main/core/debug_log.h @@ -0,0 +1,18 @@ +#ifndef DEBUG_LOG_H +#define DEBUG_LOG_H + +#include "esp_err.h" + +#include +#include + +#define DEBUG_LOG_FLASH_PATH "/spiffs/debug.log" + +esp_err_t debug_log_init(void); +esp_err_t debug_log_clear(void); +void debug_log_event(const char *event); +void debug_logf(const char *fmt, ...); +void debug_log_hex_preview(const char *label, const uint8_t *data, size_t len, + size_t preview_len); + +#endif /* DEBUG_LOG_H */ diff --git a/main/core/descriptor_validator.c b/main/core/descriptor_validator.c index 8547960c..ce919977 100644 --- a/main/core/descriptor_validator.c +++ b/main/core/descriptor_validator.c @@ -1,4 +1,5 @@ #include "descriptor_validator.h" +#include "debug_log.h" #include "key.h" #include "wallet.h" #include @@ -41,7 +42,8 @@ typedef struct { struct wally_descriptor *descriptor; int key_index; char descriptor_checksum[9]; - bool watch_only; /* keyless: skip key/xpub stages */ + bool watch_only; /* keyless: skip key/xpub stages */ + bool force_persistent; wallet_network_t watch_network; /* network for the watch-only registry add */ bool psb_warn; /* purpose/script-binding warning pending after the gates */ char psb_msg[160]; /* stashed PSB warning text (descriptor freed early) */ @@ -206,7 +208,8 @@ descriptor_scripts_are_generatable(const struct wally_descriptor *desc) { written <= sizeof(work); } -// Parse multisig threshold from descriptor string (e.g., "multi(2,..." -> 2) +// Parse multisig threshold from descriptor string ("multi(2,..." or +// "sortedmulti(2,..." -> 2) static uint32_t parse_multisig_threshold(const char *descriptor_str) { const char *multi = strstr(descriptor_str, "multi("); if (!multi) { @@ -361,10 +364,9 @@ static const char *descriptor_script_type(struct wally_descriptor *descriptor) { return name; } -static bool extract_descriptor_info(struct wally_descriptor *descriptor, - const char *descriptor_str, - int our_key_index, - descriptor_info_t *info) { +bool descriptor_info_extract(struct wally_descriptor *descriptor, + const char *descriptor_str, int our_key_index, + descriptor_info_t *info) { memset(info, 0, sizeof(descriptor_info_t)); /* static_checks rejects more keys than letter IDs; this guards keys[]. */ @@ -386,6 +388,7 @@ static bool extract_descriptor_info(struct wally_descriptor *descriptor, if (info->is_multisig) { info->threshold = parse_multisig_threshold(descriptor_str); + info->is_sorted = strstr(descriptor_str, "sortedmulti(") != NULL; } /* Each distinct key is listed by its first expression. */ @@ -436,9 +439,26 @@ static bool extract_descriptor_info(struct wally_descriptor *descriptor, return true; } +void descriptor_info_policy_name(const descriptor_info_t *info, char *out, + size_t out_len) { + if (info->is_miniscript) + snprintf(out, out_len, "Miniscript (%u key%s)", info->num_keys, + info->num_keys == 1 ? "" : "s"); + else if (info->is_multisig) + snprintf(out, out_len, "%s %u of %u", + info->is_sorted ? "sortedmulti" : "multi", info->threshold, + info->num_keys); + else if (info->script_type) + snprintf(out, out_len, "Single-sig (%s)", info->script_type); + else + snprintf(out, out_len, "Single-sig"); +} + static void id_loc_proceed(const char *id, storage_location_t loc, void *user_data) { (void)user_data; + debug_logf("descriptor_validator id_loc_proceed id=%s loc=%d", id ? id : "", + loc); if (!ctx_callback_is_live()) return; pending_generation = 0; @@ -446,8 +466,8 @@ static void id_loc_proceed(const char *id, storage_location_t loc, complete_validation(VALIDATION_USER_DECLINED); return; } - bool added = registry_add_parsed(id, current_ctx->descriptor, - (size_t)current_ctx->key_index, loc, true); + bool added = registry_persist_or_add_parsed( + id, current_ctx->descriptor, (size_t)current_ctx->key_index, loc); current_ctx->descriptor = NULL; if (!added) { ESP_LOGE(TAG, "Failed to register descriptor '%s'", id); @@ -477,25 +497,6 @@ static bool build_session_descriptor_id(char out[REGISTRY_ID_MAX_LEN]) { return false; } -static void build_session_descriptor_label(char out[REGISTRY_LABEL_MAX_LEN]) { - if (!out) - return; - - if (current_ctx->info.is_miniscript) { - snprintf(out, REGISTRY_LABEL_MAX_LEN, "Miniscript (%u key%s)", - current_ctx->info.num_keys, - current_ctx->info.num_keys == 1 ? "" : "s"); - } else if (current_ctx->info.is_multisig) { - snprintf(out, REGISTRY_LABEL_MAX_LEN, "Multisig (%u of %u)", - current_ctx->info.threshold, current_ctx->info.num_keys); - } else if (current_ctx->info.script_type) { - snprintf(out, REGISTRY_LABEL_MAX_LEN, "Single-sig (%s)", - current_ctx->info.script_type); - } else { - snprintf(out, REGISTRY_LABEL_MAX_LEN, "Single-sig"); - } -} - static void session_register_current_descriptor(void) { char id[REGISTRY_ID_MAX_LEN]; if (!build_session_descriptor_id(id)) { @@ -521,7 +522,7 @@ static void session_register_current_descriptor(void) { } char label[REGISTRY_LABEL_MAX_LEN]; - build_session_descriptor_label(label); + descriptor_info_policy_name(¤t_ctx->info, label, sizeof(label)); // The descriptor is loaded either way; without a label it lists under its id. if (!registry_set_label(id, label)) ESP_LOGW(TAG, "Failed to label session descriptor '%s'", id); @@ -534,6 +535,7 @@ static void session_register_current_descriptor(void) { // Callback after user confirms/declines descriptor info static void info_confirm_proceed(bool confirmed, void *user_data) { (void)user_data; + debug_logf("descriptor_validator info_confirm confirmed=%d", confirmed); if (!ctx_callback_is_live()) return; pending_generation = 0; @@ -546,9 +548,11 @@ static void info_confirm_proceed(bool confirmed, void *user_data) { /* Descriptor registration is disabled: load into the in-memory session * registry only. Keep id_loc_cb wired for the future registration flow, but * skip it until encrypted descriptor backups are ready. */ - if (DESCRIPTOR_PERSISTENT_REGISTRATION_ENABLED && current_ctx->id_loc_cb) { + if ((DESCRIPTOR_PERSISTENT_REGISTRATION_ENABLED || + current_ctx->force_persistent) && + current_ctx->id_loc_cb) { pending_generation = current_ctx->generation; - current_ctx->id_loc_cb(id_loc_proceed, NULL); + current_ctx->id_loc_cb(id_loc_proceed, current_ctx->user_data); } else { session_register_current_descriptor(); } @@ -558,7 +562,8 @@ static void info_confirm_proceed(bool confirmed, void *user_data) { static void show_info_or_auto_confirm(void) { pending_generation = current_ctx->generation; if (current_ctx->info_confirm_cb) - current_ctx->info_confirm_cb(¤t_ctx->info, info_confirm_proceed); + current_ctx->info_confirm_cb(¤t_ctx->info, info_confirm_proceed, + current_ctx->user_data); else info_confirm_proceed(true, NULL); } @@ -723,7 +728,7 @@ static void show_keyed_info(struct wally_descriptor *descriptor, purpose, script_name); } - bool have_info = extract_descriptor_info( + bool have_info = descriptor_info_extract( descriptor, current_ctx->descriptor_str, key_index, ¤t_ctx->info); current_ctx->descriptor = descriptor; current_ctx->key_index = key_index; @@ -920,10 +925,50 @@ void descriptor_validate_and_load(const char *descriptor_str, show_keyed_info(descriptor, key_index); } +void descriptor_validate_and_load_persistent( + const char *descriptor_str, validation_complete_cb callback, + validation_confirm_cb confirm_cb, + validation_info_confirm_cb info_confirm_cb, validation_id_loc_cb id_loc_cb, + void *user_data) { + if (descriptor_str && callback && + (!key_is_loaded() || !wallet_is_initialized())) { + cleanup_context(); + callback(VALIDATION_INTERNAL_ERROR, user_data); + return; + } + + struct wally_descriptor *descriptor = NULL; + if (validation_begin(descriptor_str, callback, info_confirm_cb, user_data, + &descriptor) != VALIDATION_SUCCESS) + return; + + current_ctx->confirm_cb = confirm_cb; + current_ctx->id_loc_cb = id_loc_cb; + current_ctx->force_persistent = true; + + int key_index = find_matching_key_index(descriptor, 0); + if (key_index < 0) { + ESP_LOGE(TAG, "Wallet fingerprint not found in descriptor"); + wally_descriptor_free(descriptor); + complete_validation(VALIDATION_FINGERPRINT_NOT_FOUND); + return; + } + + descriptor_validation_result_t keys_result = verify_own_keys(descriptor); + if (keys_result != VALIDATION_SUCCESS) { + wally_descriptor_free(descriptor); + complete_validation(keys_result); + return; + } + + // One descriptor may be registered under several aliases + show_keyed_info(descriptor, key_index); +} + // Watch-only: extract info and show the "Load?" dialog, skipping the xpub // verification and PSB warning that the keyed path performs. static void watch_only_show_info(struct wally_descriptor *descriptor) { - bool have_info = extract_descriptor_info( + bool have_info = descriptor_info_extract( descriptor, current_ctx->descriptor_str, -1, ¤t_ctx->info); wally_descriptor_free(descriptor); if (!have_info) { diff --git a/main/core/descriptor_validator.h b/main/core/descriptor_validator.h index 14e60a58..8a728fed 100644 --- a/main/core/descriptor_validator.h +++ b/main/core/descriptor_validator.h @@ -87,6 +87,8 @@ typedef enum { #define DESCRIPTOR_INFO_MAX_KEYS MINISCRIPT_POLICY_MAX_KEYS typedef struct { bool is_multisig; + /* Multisig only: sortedmulti() rather than multi(). */ + bool is_sorted; bool is_miniscript; uint32_t threshold; uint32_t num_keys; @@ -106,11 +108,22 @@ typedef struct { const char *script_type; } descriptor_info_t; +// The confirmation info of `descriptor`, written as `descriptor_str`, whose +// key `our_key_index` is ours, -1 when none is known +bool descriptor_info_extract(struct wally_descriptor *descriptor, + const char *descriptor_str, int our_key_index, + descriptor_info_t *info); + +// The policy of `info` in a few words: "sortedmulti 2 of 3", "Single-sig"... +void descriptor_info_policy_name(const descriptor_info_t *info, char *out, + size_t out_len); + // UI-agnostic info confirmation callback: show descriptor info, call proceed() -// with result. +// with result. user_data is the one passed to descriptor_validate_and_load*. typedef void (*validation_info_confirm_cb)(const descriptor_info_t *info, void (*proceed)(bool confirmed, - void *user_data)); + void *user_data), + void *user_data); // Future persistent-registration hook, used to collect the registry ID and // storage location once descriptor registration is re-enabled with encrypted @@ -135,6 +148,14 @@ void descriptor_validate_and_load(const char *descriptor_str, validation_id_loc_cb id_loc_cb, void *user_data); +// Same, always registering through id_loc_cb, and without the session dedup: +// a descriptor already loaded may be registered again under another id. +void descriptor_validate_and_load_persistent( + const char *descriptor_str, validation_complete_cb callback, + validation_confirm_cb confirm_cb, + validation_info_confirm_cb info_confirm_cb, validation_id_loc_cb id_loc_cb, + void *user_data); + /* Infer a descriptor's network by trying to parse it as mainnet, then testnet. * Writes the network to *network_out and returns true on success; returns false * if the descriptor parses on neither (xpub keys parse only on mainnet, tpub diff --git a/main/core/key.c b/main/core/key.c index bf3c7f62..a5be8ae1 100644 --- a/main/core/key.c +++ b/main/core/key.c @@ -120,6 +120,40 @@ bool key_get_fingerprint_hex(char *hex_out) { return true; } +/* The version of the xpub at `path`: its BIP44-style hardened coin type when + * it is 0' or 1', else the loaded key's network. */ +static uint32_t xpub_version_for_path(const uint32_t *path, size_t path_depth) { + if (path && path_depth >= 2 && bip32_path_is_hardened(path[1])) { + uint32_t coin = bip32_path_unharden(path[1]); + if (coin == 0) + return BIP32_VER_MAIN_PUBLIC; + if (coin == 1) + return BIP32_VER_TEST_PUBLIC; + } + + return master_key && master_key->version == BIP32_VER_TEST_PRIVATE + ? BIP32_VER_TEST_PUBLIC + : BIP32_VER_MAIN_PUBLIC; +} + +static bool key_to_path_versioned_base58(struct ext_key *key, + const uint32_t *path, + size_t path_depth, char **xpub_out) { + uint8_t serialized[BIP32_SERIALIZED_LEN]; + if (bip32_key_serialize(key, BIP32_FLAG_KEY_PUBLIC, serialized, + sizeof(serialized)) != WALLY_OK) + return false; + + uint32_t version = xpub_version_for_path(path, path_depth); + serialized[0] = (uint8_t)(version >> 24); + serialized[1] = (uint8_t)(version >> 16); + serialized[2] = (uint8_t)(version >> 8); + serialized[3] = (uint8_t)version; + + return wally_base58_from_bytes(serialized, sizeof(serialized), + BASE58_FLAG_CHECKSUM, xpub_out) == WALLY_OK; +} + bool key_mnemonic_passphrase_fingerprint_hex(const char *mnemonic, const char *passphrase, char *hex_out) { @@ -181,10 +215,34 @@ bool key_get_xpub(const char *path, char **xpub_out) { return false; } - ret = bip32_key_to_base58(derived_key, BIP32_FLAG_KEY_PUBLIC, xpub_out); + bool ok = key_to_path_versioned_base58(derived_key, path_indices, path_depth, + xpub_out); bip32_key_free(derived_key); - return (ret == WALLY_OK); + return ok; +} + +bool key_get_xpub_components(const uint32_t *path, size_t path_depth, + char **xpub_out) { + if (!key_loaded || (!path && path_depth > 0) || + path_depth > KEY_MAX_DERIVATION_DEPTH || !xpub_out) { + return false; + } + if (path_depth == 0) + return key_to_path_versioned_base58(master_key, NULL, 0, xpub_out); + + struct ext_key *derived_key = NULL; + int ret = bip32_key_from_parent_path_alloc( + master_key, path, path_depth, BIP32_FLAG_KEY_PRIVATE, &derived_key); + if (ret != WALLY_OK) { + return false; + } + + bool ok = + key_to_path_versioned_base58(derived_key, path, path_depth, xpub_out); + bip32_key_free(derived_key); + + return ok; } bool key_get_master_xpub(char **xpub_out) { diff --git a/main/core/key.h b/main/core/key.h index a6f62d54..896004f1 100644 --- a/main/core/key.h +++ b/main/core/key.h @@ -34,6 +34,9 @@ key_mnemonic_passphrase_fingerprint_hex(const char *mnemonic, /* On success, *xpub_out is heap-allocated and must be freed by the caller * with wally_free_string(). Public-only -- safe to log. */ KERN_WARN_UNUSED_RESULT bool key_get_xpub(const char *path, char **xpub_out); +KERN_WARN_UNUSED_RESULT bool key_get_xpub_components(const uint32_t *path, + size_t path_depth, + char **xpub_out); KERN_WARN_UNUSED_RESULT bool key_get_master_xpub(char **xpub_out); /* On success, *mnemonic_out is a heap-allocated copy of the active mnemonic. diff --git a/main/core/registry.c b/main/core/registry.c index b1e31d7c..c9f5ce8c 100644 --- a/main/core/registry.c +++ b/main/core/registry.c @@ -8,6 +8,7 @@ #include "psbt_internal.h" #include "wallet.h" #include +#include #include #include #include @@ -77,10 +78,7 @@ bool registry_deregister_at(size_t idx) { if (idx >= registry_len || !registry_entries[idx].persisted) return false; registry_entry_t *entry = ®istry_entries[idx]; - char filename[64]; - storage_descriptor_filename(entry->loc, entry->id, STORAGE_DESCRIPTOR_BIP138, - filename, sizeof(filename)); - esp_err_t err = storage_delete_descriptor(entry->loc, filename); + esp_err_t err = storage_delete_descriptor(entry->loc, entry->filename); if (err != ESP_OK) { ESP_LOGE(TAG, "De-registering '%s' failed (%d)", entry->id, err); return false; @@ -128,6 +126,48 @@ static bool scan_validate(const char *descriptor_str, return result == VALIDATION_SUCCESS; } +/* The file id a registration is stored under: the hex of the first bytes of + * the alias's SHA-256, so any alias fits a SPIFFS name. */ +static bool alias_file_id(const char *alias, + char out[REGISTRY_ALIAS_FILE_ID_LEN + 1]) { + unsigned char hash[SHA256_LEN]; + if (wally_sha256((const unsigned char *)alias, strlen(alias), hash, + sizeof(hash)) != WALLY_OK) + return false; + for (size_t i = 0; i < REGISTRY_ALIAS_FILE_ID_LEN / 2; i++) + snprintf(out + 2 * i, 3, "%02x", hash[i]); + return true; +} + +/* A name whose file cannot be named counts as taken */ +bool registry_name_registered(const char *name) { + char file_id[REGISTRY_ALIAS_FILE_ID_LEN + 1]; + return !alias_file_id(name, file_id) || + storage_descriptor_exists(STORAGE_FLASH, file_id, + STORAGE_DESCRIPTOR_BIP138); +} + +bool registry_unregister(const char *alias) { + for (size_t i = 0; i < registry_len; i++) { + if (strncmp(registry_entries[i].id, alias, REGISTRY_ID_MAX_LEN) == 0) + return registry_entries[i].persisted ? registry_deregister_at(i) + : registry_remove_at(i); + } + return false; +} + +/* The id of a backup: the alias it holds, else its filename for a backup + * written before aliases were stored */ +static bool backup_id(const char *fname, const char *alias, char *id, + size_t id_size) { + if (!alias) + return descriptor_id_from_filename(fname, id, id_size); + if (strlen(alias) >= id_size) + return false; + strcpy(id, alias); + return true; +} + /* Registers every flash backup that this device wrote for the loaded key * (valid approval mark) and that still passes keyed validation. Backups * without a mark, plaintext and KEF files stay explicit imports. Each backup @@ -138,9 +178,10 @@ static void registry_init_scan(void) { if (storage_list_descriptors(STORAGE_FLASH, &files, &count) != ESP_OK) return; bip138_backup_hold_approval_key(); - for (int i = 0; i < count && registry_len < REGISTRY_MAX_ENTRIES; i++) { + for (int i = 0; i < count; i++) { const char *fname = files[i]; - if (storage_descriptor_format(fname) != STORAGE_DESCRIPTOR_BIP138) + if (storage_descriptor_format(fname) != STORAGE_DESCRIPTOR_BIP138 || + registry_len >= REGISTRY_MAX_ENTRIES) continue; uint8_t *data = NULL; size_t data_len = 0; @@ -150,35 +191,36 @@ static void registry_init_scan(void) { char *desc_str = NULL; struct wally_descriptor *desc = NULL; int key_index = -1; + char *alias = NULL; char id[REGISTRY_ID_MAX_LEN]; - char existing[REGISTRY_ID_MAX_LEN]; bool approved = false; - if (!bip138_backup_decrypt_any_hinted(data, data_len, &desc_str, + if (!bip138_backup_decrypt_any_hinted(data, data_len, &desc_str, &alias, &approved)) { ESP_LOGI(TAG, "Skipping '%s': not addressed to the loaded key", fname); } else if (!approved) { ESP_LOGI(TAG, "Skipping '%s': not registered on this device", fname); } else if (!scan_validate(desc_str, &desc, &key_index)) { ESP_LOGW(TAG, "Skipping '%s': failed validation", fname); - } else if (!descriptor_id_from_filename(fname, id, sizeof(id))) { - ESP_LOGW(TAG, "Skipping '%s': unexpected filename", fname); - } else if (registry_session_has_duplicate_scripts(desc, existing, - sizeof(existing))) { - ESP_LOGI(TAG, "Skipping '%s': same descriptor as '%s'", fname, existing); + } else if (!backup_id(fname, alias, id, sizeof(id))) { + ESP_LOGW(TAG, "Skipping '%s': unexpected filename or alias", fname); } else if (registry_find_by_id(id)) { ESP_LOGW(TAG, "Skipping '%s': id '%s' already registered", fname, id); } else { bool added = registry_add_parsed(id, desc, (size_t)key_index, STORAGE_FLASH, false); desc = NULL; /* owned by the registry, or freed on failure */ - if (added) - registry_entries[registry_len - 1].persisted = true; - else + if (added) { + registry_entry_t *e = ®istry_entries[registry_len - 1]; + e->persisted = true; + snprintf(e->filename, sizeof(e->filename), "%s", fname); + } else { ESP_LOGW(TAG, "Skipping stored descriptor '%s': failed to register", id); + } } wally_descriptor_free(desc); SECURE_FREE_STRING(desc_str); + free(alias); free(data); } bip138_backup_release_approval_key(); @@ -276,6 +318,19 @@ bool registry_session_has_duplicate_scripts(const struct wally_descriptor *desc, return false; } +bool registry_entry_is_descriptor(const registry_entry_t *entry, + const char *descriptor_str) { + struct wally_descriptor *desc = NULL; + uint8_t id[32]; + bool same = + entry->has_script_id && descriptor_str && + wallet_descriptor_parse(descriptor_str, NULL, wallet_wally_network(), + &desc) == WALLY_OK && + script_id(desc, id) && memcmp(id, entry->script_id, sizeof(id)) == 0; + wally_descriptor_free(desc); + return same; +} + bool registry_session_has_duplicate(const char *descriptor_str, char *out_id, size_t out_id_size) { if (out_id && out_id_size > 0) @@ -345,6 +400,40 @@ static bool own_key_matches(const registry_own_key_t *key, uint32_t multi_index, depth - key->origin_path_len, child_num); } +void registry_prefer(const char *id) { + for (size_t i = 0; i < registry_len; i++) { + if (strncmp(registry_entries[i].id, id, REGISTRY_ID_MAX_LEN) == 0) + registry_entries[i].preferred = true; + } +} + +void registry_clear_preferred(void) { + for (size_t i = 0; i < registry_len; i++) + registry_entries[i].preferred = false; +} + +static registry_entry_t *match_order_entry(size_t pos) { + size_t preferred = 0; + for (size_t i = 0; i < registry_len; i++) { + if (registry_entries[i].preferred) + preferred++; + } + bool want_preferred = pos < preferred; + size_t skip = want_preferred ? pos : pos - preferred; + for (size_t i = 0; i < registry_len; i++) { + if (registry_entries[i].preferred != want_preferred) + continue; + if (skip == 0) + return ®istry_entries[i]; + skip--; + } + return NULL; +} + +const registry_entry_t *registry_match_order_get(size_t pos) { + return match_order_entry(pos); +} + registry_entry_t *registry_match_keypath(const uint8_t *keypath, size_t keypath_len, registry_match_cursor_t *cursor, @@ -358,9 +447,8 @@ registry_entry_t *registry_match_keypath(const uint8_t *keypath, MAX_KEYPATH_TOTAL_DEPTH)) return NULL; - for (; cursor->entry < registry_len; - cursor->entry++, cursor->multi_index = 0) { - registry_entry_t *e = ®istry_entries[cursor->entry]; + for (registry_entry_t *e = match_order_entry(cursor->entry); e; + e = match_order_entry(++cursor->entry), cursor->multi_index = 0) { uint32_t groups = e->num_paths > 1 ? (uint32_t)e->num_paths : 1; for (; cursor->multi_index < groups; cursor->multi_index++) { for (size_t k = 0; k < e->num_own_keys; k++) { @@ -564,7 +652,8 @@ bool registry_persist(const char *id, const char *name) { if (strncmp(id, name, REGISTRY_ID_MAX_LEN) != 0 && registry_find_by_id(name)) return false; /* Another seed's backup may sit under this name without being loaded. */ - if (storage_descriptor_exists(loc, name, STORAGE_DESCRIPTOR_BIP138)) + char file_id[REGISTRY_ALIAS_FILE_ID_LEN + 1]; + if (registry_name_registered(name) || !alias_file_id(name, file_id)) return false; char *descriptor_str = NULL; @@ -572,8 +661,8 @@ bool registry_persist(const char *id, const char *name) { return false; uint8_t *blob = NULL; size_t blob_len = 0; - bool ok = bip138_backup_encrypt(descriptor_str, &blob, &blob_len) && - storage_save_descriptor(loc, name, blob, blob_len, + bool ok = bip138_backup_encrypt(descriptor_str, name, &blob, &blob_len) && + storage_save_descriptor(loc, file_id, blob, blob_len, STORAGE_DESCRIPTOR_BIP138) == ESP_OK; free(blob); wally_free_string(descriptor_str); @@ -587,9 +676,29 @@ bool registry_persist(const char *id, const char *name) { e->label[REGISTRY_LABEL_MAX_LEN - 1] = '\0'; e->loc = loc; e->persisted = true; + storage_descriptor_filename(loc, file_id, STORAGE_DESCRIPTOR_BIP138, + e->filename, sizeof(e->filename)); return true; } +bool registry_persist_or_add_parsed(const char *id, + struct wally_descriptor *desc, + size_t key_index, storage_location_t loc) { + if (!id || !desc) { + wally_descriptor_free(desc); + return false; + } + + const registry_entry_t *entry = registry_find_by_id(id); + if (!entry) + return registry_add_parsed(id, desc, key_index, loc, true); + uint8_t sid[32]; + bool same = entry->has_script_id && script_id(desc, sid) && + memcmp(sid, entry->script_id, sizeof(sid)) == 0; + wally_descriptor_free(desc); + return same && (entry->persisted || registry_persist(id, id)); +} + bool registry_add_watch_only(const char *id, const char *descriptor_str, wallet_network_t network) { if (!id || !descriptor_str) diff --git a/main/core/registry.h b/main/core/registry.h index 829d9a47..49b73b84 100644 --- a/main/core/registry.h +++ b/main/core/registry.h @@ -13,7 +13,8 @@ #include "wallet.h" #define REGISTRY_MAX_ENTRIES 16 -#define REGISTRY_ID_MAX_LEN 32 +/* A 32-byte bipqr DESCRIPTOR_ALIAS and its NUL */ +#define REGISTRY_ID_MAX_LEN 33 #define REGISTRY_LABEL_MAX_LEN 48 #define REGISTRY_MAX_OWN_KEYS 8 #define REGISTRY_CHILD_PATH_MAX_LEN 48 @@ -43,6 +44,9 @@ typedef struct { * key. */ char child_path[REGISTRY_CHILD_PATH_MAX_LEN]; } registry_own_key_t; +#define REGISTRY_FILENAME_MAX_LEN 48 +/* Hex digits of the file id a registration is stored under */ +#define REGISTRY_ALIAS_FILE_ID_LEN 16 typedef struct { char id[REGISTRY_ID_MAX_LEN]; @@ -63,6 +67,10 @@ typedef struct { uint8_t script_id[32]; bool has_script_id; bool persisted; + /* The backup file of a persisted entry */ + char filename[REGISTRY_FILENAME_MAX_LEN]; + /* Named by the current request: matched before the other entries */ + bool preferred; } registry_entry_t; /* Where registry_match_keypath resumes; zero-initialise before the first @@ -93,14 +101,35 @@ registry_add_from_string(const char *id, const char *descriptor_str, KERN_WARN_UNUSED_RESULT bool registry_add_parsed(const char *id, struct wally_descriptor *desc, size_t key_index, storage_location_t loc, bool persist); - -/* Register a session entry: writes its BIP138 backup to flash under `name`, - * then renames and labels the entry. Registered descriptors load automatically - * whenever a key of theirs is loaded. Fails when no such session entry - * exists, the name is taken on flash, or the backup cannot be written; the - * entry is left untouched on failure. */ +/* registry_add_parsed, persisting, unless an entry already holds `id`: then + * that entry, when it pays the same scripts as `desc`, is persisted if it is + * not yet. Takes ownership of `desc` either way. */ +KERN_WARN_UNUSED_RESULT bool +registry_persist_or_add_parsed(const char *id, struct wally_descriptor *desc, + size_t key_index, storage_location_t loc); + +/* Register a session entry: writes its BIP138 backup, `name` included, to a + * flash file named after `name`, then renames and labels the entry. + * Registered descriptors load automatically whenever a key of theirs is + * loaded. Fails when no such session entry exists, the name is taken on + * flash, or the backup cannot be written; the entry is left untouched on + * failure. */ KERN_WARN_UNUSED_RESULT bool registry_persist(const char *id, const char *name); +/* True when a registration on flash already uses `name`, loaded or not. */ +KERN_WARN_UNUSED_RESULT bool registry_name_registered(const char *name); + +/* Removes the registration `alias` names, and only it: its descriptor entry + * with its backup on flash when it has one. False for an unknown alias; + * failure leaves the registration intact. */ +KERN_WARN_UNUSED_RESULT bool registry_unregister(const char *alias); + +/* True when `entry` pays the same scripts as `descriptor_str` (see + * registry_session_has_duplicate_scripts). */ +KERN_WARN_UNUSED_RESULT bool +registry_entry_is_descriptor(const registry_entry_t *entry, + const char *descriptor_str); + /* Watch-only (keyless) session add: registers a descriptor for address viewing * without requiring the loaded key's fingerprint to be present. `my_key_index` * is set to SIZE_MAX and the origin path is left empty. Never persisted. */ @@ -128,11 +157,20 @@ void registry_init(bool is_testnet); /* Backups registered on this device that the last registry_init skipped * because they no longer pass keyed validation (other-network ones aside). */ KERN_WARN_UNUSED_RESULT size_t registry_rejected_count(void); -/* Next (entry, multipath group) under which `keypath` (fingerprint, then - * path) is one of the entry's own keys: some own key's origin followed by its - * child path expanded at that group and some child number. Writes the group - * as `multi_index` and the wildcard's value as `child_num`. Only the path is - * compared; the caller proves ownership by regenerating the script. */ +/* Marks the entry `id` names as preferred, so a script several entries + * generate is claimed by the entry a request names. No-op for an unknown id. */ +void registry_prefer(const char *id); +void registry_clear_preferred(void); +/* The entry at `pos` in match order: the preferred entries, then the others, + * both in registry order. NULL past the last entry. */ +KERN_WARN_UNUSED_RESULT const registry_entry_t * +registry_match_order_get(size_t pos); +/* Next (entry, multipath group), entries in match order, under which + * `keypath` (fingerprint, then path) is one of the entry's own keys: some own + * key's origin followed by its child path expanded at that group and some + * child number. Writes the group as `multi_index` and the wildcard's value as + * `child_num`. Only the path is compared; the caller proves ownership by + * regenerating the script. */ KERN_WARN_UNUSED_RESULT registry_entry_t * registry_match_keypath(const uint8_t *keypath, size_t keypath_len, registry_match_cursor_t *cursor, uint32_t *multi_index, diff --git a/main/core/test/.gitignore b/main/core/test/.gitignore index c5602c81..866bdd21 100644 --- a/main/core/test/.gitignore +++ b/main/core/test/.gitignore @@ -44,3 +44,4 @@ test_self_test fuzz_psbt fuzz_descriptor fuzz_text +kern_bipqr/ diff --git a/main/core/test/Makefile b/main/core/test/Makefile index 6720b878..5691edb3 100644 --- a/main/core/test/Makefile +++ b/main/core/test/Makefile @@ -93,6 +93,8 @@ SCRIPT_TEMPLATE_SRC = ../script_templates.c ../script_templates.h REGISTRY_STUB_SRC = stubs/registry_stub.c REGISTRY_PERSIST_STUB_SRC = stubs/registry_persist_stub.c VALIDATOR_KEYED_STUB_SRC = stubs/validator_keyed_stub.c +# debug_logf writes to device storage, never host-linkable +DEBUG_LOG_STUB_SRC = stubs/debug_log_stub.c SRCS_REG_PARSE = test_registry_parse.c TARGET_REG_PARSE = test_registry_parse @@ -283,7 +285,7 @@ $(TARGET_DESC_VALIDATOR): $(SRCS_DESC_VALIDATOR) $(DESC_VALIDATOR_SRC) $(KEY_SRC $(CC) $(CFLAGS) $(TEST_INCS) -Wno-format-truncation -o $@ $(SRCS_DESC_VALIDATOR) \ ../descriptor_validator.c ../wallet.c ../descriptor_parse.c ../key.c ../registry.c $(REGISTRY_PERSIST_STUB_SRC) \ ../descriptor_checksum.c ../bip32_path.c ../script_templates.c \ - ../ss_whitelist.c ../miniscript_policy.c $(LIBWALLY) -lmbedcrypto + ../ss_whitelist.c ../miniscript_policy.c $(DEBUG_LOG_STUB_SRC) $(LIBWALLY) -lmbedcrypto # storage.c is built unchanged with its POSIX file calls redirected (see # stubs/storage_host_hooks.h) so /spiffs and /sdcard resolve under a temp dir. @@ -326,7 +328,7 @@ $(TARGET_BIP138_BACKUP): $(SRCS_BIP138_BACKUP) ../bip138_backup.c ../bip138_back ../crypto_utils.c ../entropy_pool.c stubs/esp_hw_stub.c $(HOST_PBKDF2) \ ../wallet.c ../descriptor_parse.c ../key.c ../registry.c ../descriptor_validator.c ../descriptor_checksum.c ../bip32_path.c \ ../script_templates.c ../ss_whitelist.c ../miniscript_policy.c \ - $(BIP138_SRCS) $(LIBWALLY) -lmbedcrypto $(KEF_LIBS) + $(DEBUG_LOG_STUB_SRC) $(BIP138_SRCS) $(LIBWALLY) -lmbedcrypto $(KEF_LIBS) $(TARGET_ADDRESS_MATCH): $(SRCS_ADDRESS_MATCH) $(ADDRESS_MATCH_SRC) $(SS_SRC) $(KEY_SRC) $(LIBWALLY) $(CC) $(CFLAGS) $(TEST_INCS) -Wl,--wrap=wally_descriptor_to_script -o $@ $(SRCS_ADDRESS_MATCH) ../address_match.c ../descriptor_branch.c ../descriptor_parse.c ../ss_whitelist.c ../key.c ../bip32_path.c ../script_templates.c $(LIBWALLY) -lmbedcrypto @@ -383,7 +385,7 @@ fuzz_descriptor: $(FUZZ_DIR)/fuzz_descriptor.c $(FUZZ_DIR)/fuzz_stubs.c $(FUZZ_D $(CC) $(CFLAGS) $(TEST_INCS) -Wno-format-truncation -o $@ $(FUZZ_DIR)/fuzz_descriptor.c $(FUZZ_DIR)/fuzz_stubs.c $(FUZZ_MAIN) \ ../descriptor_validator.c ../wallet.c ../descriptor_parse.c ../key.c ../registry.c \ $(REGISTRY_PERSIST_STUB_SRC) ../descriptor_checksum.c ../bip32_path.c \ - ../script_templates.c ../ss_whitelist.c ../miniscript_policy.c $(LIBWALLY) -lmbedcrypto + ../script_templates.c ../ss_whitelist.c ../miniscript_policy.c $(DEBUG_LOG_STUB_SRC) $(LIBWALLY) -lmbedcrypto fuzz_text: $(FUZZ_DIR)/fuzz_text.c $(FUZZ_DEPS) ../message_sign.c $(KEY_SRC) $(MULTISIG_SETUP_SRC) $(DESCRIPTOR_TEXT_SRC) ../../utils/text_file.c $(CC) $(CFLAGS) $(TEST_INCS) -o $@ $(FUZZ_DIR)/fuzz_text.c $(FUZZ_MAIN) ../message_sign.c ../key.c \ diff --git a/main/core/test/stubs/debug_log_stub.c b/main/core/test/stubs/debug_log_stub.c new file mode 100644 index 00000000..e810bee0 --- /dev/null +++ b/main/core/test/stubs/debug_log_stub.c @@ -0,0 +1,4 @@ +/* The on-device debug log writes to storage, which does not link on the host, + * so every host test that pulls in descriptor_validator.c takes this. */ + +void debug_logf(const char *fmt, ...) { (void)fmt; } diff --git a/main/core/test/stubs/registry_persist_stub.c b/main/core/test/stubs/registry_persist_stub.c index 51341416..c2af4e05 100644 --- a/main/core/test/stubs/registry_persist_stub.c +++ b/main/core/test/stubs/registry_persist_stub.c @@ -8,8 +8,9 @@ #include #include -bool bip138_backup_encrypt(const char *descriptor, uint8_t **blob_out, - size_t *blob_len) { +bool bip138_backup_encrypt(const char *descriptor, const char *alias, + uint8_t **blob_out, size_t *blob_len) { + (void)alias; if (!descriptor || !blob_out || !blob_len) return false; size_t len = strlen(descriptor); @@ -23,9 +24,12 @@ bool bip138_backup_encrypt(const char *descriptor, uint8_t **blob_out, } bool bip138_backup_decrypt_any(const uint8_t *data, size_t len, - char **descriptor_out, bool *approved_out) { + char **descriptor_out, char **alias_out, + bool *approved_out) { if (approved_out) *approved_out = true; + if (alias_out) + *alias_out = NULL; if (!data || !descriptor_out) return false; char *descriptor = malloc(len + 1); @@ -38,9 +42,10 @@ bool bip138_backup_decrypt_any(const uint8_t *data, size_t len, } bool bip138_backup_decrypt_any_hinted(const uint8_t *data, size_t len, - char **descriptor_out, + char **descriptor_out, char **alias_out, bool *approved_out) { - return bip138_backup_decrypt_any(data, len, descriptor_out, approved_out); + return bip138_backup_decrypt_any(data, len, descriptor_out, alias_out, + approved_out); } void bip138_backup_forget_keys(void) {} diff --git a/main/core/test/test_bip138_backup.c b/main/core/test/test_bip138_backup.c index c74f38d6..942c795f 100644 --- a/main/core/test/test_bip138_backup.c +++ b/main/core/test/test_bip138_backup.c @@ -31,7 +31,7 @@ static void check(const char *name, bool ok) { printf("Testing: %s... %s\n", name, ok ? "PASS" : "FAIL"); } -/* ---------- storage stubs: one captured file per location ---------- */ +/* ---------- storage stubs: two flash files, one SD file ---------- */ typedef struct { bool present; @@ -41,14 +41,16 @@ typedef struct { size_t len; } stub_file_t; -static stub_file_t stub_files[2]; +/* Flash in slots 0 and 2, SD in slot 1 */ +static stub_file_t stub_files[3]; +#define STUB_SLOTS 3 static int stub_saves; static int stub_deletes; static bool stub_delete_fail; static char stub_last_deleted[64]; static void stub_storage_reset(void) { - for (int i = 0; i < 2; i++) { + for (int i = 0; i < STUB_SLOTS; i++) { free(stub_files[i].data); memset(&stub_files[i], 0, sizeof(stub_files[i])); } @@ -58,10 +60,39 @@ static void stub_storage_reset(void) { stub_last_deleted[0] = '\0'; } +static bool stub_slot_is_at(int slot, storage_location_t loc) { + return (slot == 1) == (loc == STORAGE_SD); +} + +/* The file of `loc` named `filename`, else NULL */ +static stub_file_t *stub_find(storage_location_t loc, const char *filename) { + for (int i = 0; i < STUB_SLOTS; i++) { + if (stub_slot_is_at(i, loc) && stub_files[i].present && + strcmp(stub_files[i].filename, filename) == 0) + return &stub_files[i]; + } + return NULL; +} + +/* The file of `loc` named `filename`, else its first free slot */ +static stub_file_t *stub_slot_for(storage_location_t loc, + const char *filename) { + stub_file_t *f = stub_find(loc, filename); + for (int i = 0; !f && i < STUB_SLOTS; i++) { + if (stub_slot_is_at(i, loc) && !stub_files[i].present) + f = &stub_files[i]; + } + return f; +} + esp_err_t storage_save_descriptor(storage_location_t loc, const char *id, const uint8_t *data, size_t len, storage_descriptor_format_t format) { - stub_file_t *f = &stub_files[loc == STORAGE_SD]; + char filename[64]; + storage_descriptor_filename(loc, id, format, filename, sizeof(filename)); + stub_file_t *f = stub_slot_for(loc, filename); + if (!f) + return ESP_FAIL; free(f->data); f->data = malloc(len); if (!f->data) @@ -70,18 +101,17 @@ esp_err_t storage_save_descriptor(storage_location_t loc, const char *id, f->len = len; f->format = format; f->present = true; - storage_descriptor_filename(loc, id, format, f->filename, - sizeof(f->filename)); + snprintf(f->filename, sizeof(f->filename), "%s", filename); stub_saves++; return ESP_OK; } esp_err_t storage_delete_descriptor(storage_location_t loc, const char *filename) { - stub_file_t *f = &stub_files[loc == STORAGE_SD]; + stub_file_t *f = stub_find(loc, filename); stub_deletes++; snprintf(stub_last_deleted, sizeof(stub_last_deleted), "%s", filename); - if (stub_delete_fail || !f->present || strcmp(f->filename, filename) != 0) + if (stub_delete_fail || !f) return ESP_FAIL; free(f->data); memset(f, 0, sizeof(*f)); @@ -90,25 +120,26 @@ esp_err_t storage_delete_descriptor(storage_location_t loc, esp_err_t storage_list_descriptors(storage_location_t loc, char ***filenames_out, int *count_out) { - stub_file_t *f = &stub_files[loc == STORAGE_SD]; *filenames_out = NULL; *count_out = 0; - if (!f->present) - return ESP_OK; - char **list = malloc(sizeof(char *)); + char **list = malloc(STUB_SLOTS * sizeof(char *)); if (!list) return ESP_ERR_NO_MEM; - list[0] = strdup(f->filename); + int count = 0; + for (int i = 0; i < STUB_SLOTS; i++) { + if (stub_slot_is_at(i, loc) && stub_files[i].present) + list[count++] = strdup(stub_files[i].filename); + } *filenames_out = list; - *count_out = 1; + *count_out = count; return ESP_OK; } esp_err_t storage_load_descriptor(storage_location_t loc, const char *filename, uint8_t **data_out, size_t *len_out, storage_descriptor_format_t *format_out) { - stub_file_t *f = &stub_files[loc == STORAGE_SD]; - if (!f->present || strcmp(f->filename, filename) != 0) + stub_file_t *f = stub_find(loc, filename); + if (!f) return ESP_FAIL; *data_out = malloc(f->len); if (!*data_out) @@ -128,19 +159,18 @@ void storage_free_file_list(char **files, int count) { bool storage_descriptor_exists(storage_location_t loc, const char *id, storage_descriptor_format_t format) { - stub_file_t *f = &stub_files[loc == STORAGE_SD]; char filename[64]; storage_descriptor_filename(loc, id, format, filename, sizeof(filename)); - return f->present && strcmp(f->filename, filename) == 0; + return stub_find(loc, filename) != NULL; } /* The real storage layer builds the same names; keep the stub honest. */ void storage_descriptor_filename(storage_location_t loc, const char *id, storage_descriptor_format_t format, char *out, size_t out_size) { - const char *ext = format == STORAGE_DESCRIPTOR_BIP138 - ? STORAGE_DESCRIPTOR_EXT_BIP138 - : STORAGE_DESCRIPTOR_EXT_TXT; + const char *ext = STORAGE_DESCRIPTOR_EXT_TXT; + if (format == STORAGE_DESCRIPTOR_BIP138) + ext = STORAGE_DESCRIPTOR_EXT_BIP138; snprintf(out, out_size, "%s%s%s", loc == STORAGE_FLASH ? STORAGE_DESCRIPTOR_PREFIX : "", id, ext); } @@ -200,35 +230,37 @@ static void test_common_account(void) { check("descriptor builds", build_wpkh("m/84'/0'/0'", descriptor, sizeof(descriptor))); - check("encrypt", bip138_backup_encrypt(descriptor, &blob, &blob_len)); + check("encrypt", bip138_backup_encrypt(descriptor, NULL, &blob, &blob_len)); check("is container", bip138_is_container(blob, blob_len)); check("parses", bip138_parse(blob, blob_len, &cont) == BIP138_OK); check("origin is stored as a recovery hint", cont.path_count == 1); check("one key padded to five secrets", cont.secret_count == 5); - check("decrypt", bip138_backup_decrypt(blob, blob_len, &recovered, NULL)); + check("decrypt", + bip138_backup_decrypt(blob, blob_len, &recovered, NULL, NULL)); check("descriptor round-trips", recovered && strcmp(recovered, descriptor) == 0); free(recovered); uint8_t *again = NULL; size_t again_len = 0; - check("encrypt again", bip138_backup_encrypt(descriptor, &again, &again_len)); + check("encrypt again", + bip138_backup_encrypt(descriptor, NULL, &again, &again_len)); check("fresh nonce each time", again_len == blob_len && memcmp(again, blob, blob_len) != 0); free(again); blob[blob_len - 1] ^= 0x01; check("tampered blob fails", - !bip138_backup_decrypt(blob, blob_len, &recovered, NULL)); + !bip138_backup_decrypt(blob, blob_len, &recovered, NULL, NULL)); check("truncated blob fails", - !bip138_backup_decrypt(blob, blob_len - 20, &recovered, NULL)); + !bip138_backup_decrypt(blob, blob_len - 20, &recovered, NULL, NULL)); size_t ct_off = (size_t)(cont.ciphertext - blob); blob[ct_off - 1] = 0; check("empty ciphertext parses but does not decrypt", cont.ciphertext_len < 0xfd && bip138_parse(blob, ct_off, &cont) == BIP138_OK && bip138_plaintext_max(&cont) == 0 && - !bip138_backup_decrypt(blob, ct_off, &recovered, NULL)); + !bip138_backup_decrypt(blob, ct_off, &recovered, NULL, NULL)); free(blob); } @@ -243,14 +275,14 @@ static void test_uncommon_account(void) { check("account 10' descriptor builds", build_wpkh("m/84'/0'/10'", descriptor, sizeof(descriptor))); - check("encrypt", bip138_backup_encrypt(descriptor, &blob, &blob_len)); + check("encrypt", bip138_backup_encrypt(descriptor, NULL, &blob, &blob_len)); check("parses", bip138_parse(blob, blob_len, &cont) == BIP138_OK); check("uncommon origin is stored", cont.path_count == 1); check("stored path is 84'/0'/10'", bip138_path_at(&cont, 0, child, 8, &depth) == BIP138_OK && depth == 3 && child[2] == (10 | 0x80000000u)); check("decrypt via stored path", - bip138_backup_decrypt(blob, blob_len, &recovered, NULL)); + bip138_backup_decrypt(blob, blob_len, &recovered, NULL, NULL)); check("descriptor round-trips", recovered && strcmp(recovered, descriptor) == 0); free(recovered); @@ -275,12 +307,12 @@ static void test_repeated_key_hint(void) { xpub, fp, xpub); wally_free_string(xpub); check("repeated key: encrypts", - bip138_backup_encrypt(descriptor, &blob, &blob_len)); + bip138_backup_encrypt(descriptor, NULL, &blob, &blob_len)); check("repeated key: the later occurrence's origin is a hint", blob && bip138_parse(blob, blob_len, &cont) == BIP138_OK && cont.path_count == 1); check("repeated key: reopens through that hint", - blob && bip138_backup_decrypt(blob, blob_len, &recovered, NULL) && + blob && bip138_backup_decrypt(blob, blob_len, &recovered, NULL, NULL) && strcmp(recovered, descriptor) == 0); free(recovered); free(blob); @@ -293,9 +325,9 @@ static void test_unload_forgets_common_keys(void) { size_t blob_len = 0; char *recovered = NULL; check("forget: foreign backup fills the cache", - bip138_backup_encrypt("wpkh(" FOREIGN_KEY "/<0;1>/*)", &blob, + bip138_backup_encrypt("wpkh(" FOREIGN_KEY "/<0;1>/*)", NULL, &blob, &blob_len) && - !bip138_backup_decrypt(blob, blob_len, &recovered, NULL) && + !bip138_backup_decrypt(blob, blob_len, &recovered, NULL, NULL) && !bip138_backup_cache_is_empty()); free(blob); wallet_unload(); @@ -313,22 +345,22 @@ static void test_hinted_skips_common_walk(void) { size_t blob_len = 0; char *recovered = NULL; bip138_backup_forget_keys(); - check( - "hinted: foreign backup is not opened", - bip138_backup_encrypt("wpkh(" FOREIGN_KEY "/<0;1>/*)", &blob, - &blob_len) && - !bip138_backup_decrypt_any_hinted(blob, blob_len, &recovered, NULL)); + check("hinted: foreign backup is not opened", + bip138_backup_encrypt("wpkh(" FOREIGN_KEY "/<0;1>/*)", NULL, &blob, + &blob_len) && + !bip138_backup_decrypt_any_hinted(blob, blob_len, &recovered, NULL, + NULL)); check("hinted: no common path was derived", bip138_backup_cache_is_empty()); free(blob); blob = NULL; char descriptor[256]; - check( - "hinted: own common-account backup opens", - build_wpkh("m/84'/0'/0'", descriptor, sizeof(descriptor)) && - bip138_backup_encrypt(descriptor, &blob, &blob_len) && - bip138_backup_decrypt_any_hinted(blob, blob_len, &recovered, NULL) && - strcmp(recovered, descriptor) == 0); + check("hinted: own common-account backup opens", + build_wpkh("m/84'/0'/0'", descriptor, sizeof(descriptor)) && + bip138_backup_encrypt(descriptor, NULL, &blob, &blob_len) && + bip138_backup_decrypt_any_hinted(blob, blob_len, &recovered, NULL, + NULL) && + strcmp(recovered, descriptor) == 0); free(recovered); free(blob); } @@ -339,9 +371,9 @@ static void test_foreign_key(void) { size_t blob_len = 0; char *recovered = NULL; check("foreign descriptor encrypts", - bip138_backup_encrypt(descriptor, &blob, &blob_len)); + bip138_backup_encrypt(descriptor, NULL, &blob, &blob_len)); check("foreign backup cannot be decrypted", - !bip138_backup_decrypt(blob, blob_len, &recovered, NULL)); + !bip138_backup_decrypt(blob, blob_len, &recovered, NULL, NULL)); free(blob); } @@ -354,7 +386,8 @@ static void test_text_form(void) { size_t blob_len = 0; check("descriptor builds", build_wpkh("m/86'/0'/1'", descriptor, sizeof(descriptor))); - check("encrypt binary", bip138_backup_encrypt(descriptor, &blob, &blob_len)); + check("encrypt binary", + bip138_backup_encrypt(descriptor, NULL, &blob, &blob_len)); text = blob ? malloc(BIP138_BASE64_LEN(blob_len)) : NULL; check("encode text", text && bip138_base64_encode(blob, blob_len, text, BIP138_BASE64_LEN(blob_len), @@ -366,31 +399,32 @@ static void test_text_form(void) { check("decrypt_any accepts text", text && bip138_backup_decrypt_any((const uint8_t *)text, strlen(text), - &recovered, NULL) && + &recovered, NULL, NULL) && strcmp(recovered, descriptor) == 0); free(recovered); recovered = NULL; check("decrypt_any accepts binary", - bip138_backup_decrypt_any(blob, blob_len, &recovered, NULL) && + bip138_backup_decrypt_any(blob, blob_len, &recovered, NULL, NULL) && strcmp(recovered, descriptor) == 0); free(recovered); free(blob); check("decrypt_any rejects garbage", !bip138_backup_decrypt_any((const uint8_t *)"not a backup", 12, - &recovered, NULL)); + &recovered, NULL, NULL)); free(text); } static void test_rejections(void) { uint8_t *blob = NULL; size_t blob_len = 0; - check("bare xpub descriptor is rejected", - !bip138_backup_encrypt("wpkh(" FOREIGN_KEY ")", &blob, &blob_len)); + check( + "bare xpub descriptor is rejected", + !bip138_backup_encrypt("wpkh(" FOREIGN_KEY ")", NULL, &blob, &blob_len)); check("garbage descriptor is rejected", - !bip138_backup_encrypt("wpkh(", &blob, &blob_len)); + !bip138_backup_encrypt("wpkh(", NULL, &blob, &blob_len)); check("NULL descriptor is rejected", - !bip138_backup_encrypt(NULL, &blob, &blob_len)); + !bip138_backup_encrypt(NULL, NULL, &blob, &blob_len)); } static void test_registry_persistence(void) { @@ -407,12 +441,12 @@ static void test_registry_persistence(void) { check("one file written as BIP138", stub_saves == 1 && stub_files[0].present && stub_files[0].format == STORAGE_DESCRIPTOR_BIP138 && - strcmp(stub_files[0].filename, "d_ColdVault.bip138") == 0); + strcmp(stub_files[0].filename, "d_758a687821d156d5.bip138") == 0); check("stored bytes are a container", bip138_is_container(stub_files[0].data, stub_files[0].len)); check("stored container opens with the loaded key", bip138_backup_decrypt(stub_files[0].data, stub_files[0].len, &recovered, - NULL) && + NULL, NULL) && registry_session_has_duplicate(recovered, NULL, 0)); free(recovered); @@ -446,7 +480,7 @@ static void test_registry_persistence(void) { check("de-registration deletes the file and the session entry", registry_deregister_at(0) && registry_count() == 0 && stub_deletes == 1 && - strcmp(stub_last_deleted, "d_ColdVault.bip138") == 0 && + strcmp(stub_last_deleted, "d_758a687821d156d5.bip138") == 0 && !stub_files[0].present); registry_init(false); check("nothing left to load", registry_count() == 0); @@ -462,7 +496,7 @@ static void test_registry_persistence(void) { !registry_persist("nope", "Named") && stub_saves == 0); check("persist promotes the entry", registry_persist("desc_abcdefgh", "NamedVault") && stub_saves == 1 && - strcmp(stub_files[0].filename, "d_NamedVault.bip138") == 0); + strcmp(stub_files[0].filename, "d_82562eaecce0d48e.bip138") == 0); entry = registry_find_by_id("NamedVault"); check("entry is renamed, labelled and persisted", entry && entry->persisted && entry->loc == STORAGE_FLASH && @@ -472,7 +506,7 @@ static void test_registry_persistence(void) { !registry_persist("NamedVault", "Other") && stub_saves == 1); check("promoted backup opens with the loaded key", bip138_backup_decrypt(stub_files[0].data, stub_files[0].len, &recovered, - NULL)); + NULL, NULL)); free(recovered); registry_init(false); check("promoted entry survives a boot scan", @@ -486,28 +520,26 @@ static void test_registry_persistence(void) { stub_storage_reset(); } -/* A container written by the library alone, without Kern's approval mark: - * what another wallet, or an attacker holding only our xpub, can produce. */ -static bool forge_backup(const char *descriptor, uint8_t **blob_out, - size_t *blob_len) { +/* A container of `items` written by the library alone, addressed to the keys + * of `descriptor` */ +static bool encrypt_items(const char *descriptor, const bip138_item *items, + size_t n_items, uint8_t **blob_out, + size_t *blob_len) { uint8_t keys[BIP138_KEYS_MAX * 32]; size_t count = 0; if (!bip138_keys_from_descriptor(descriptor, WALLY_NETWORK_BITCOIN_MAINNET, keys, NULL, BIP138_KEYS_MAX, &count)) return false; - bip138_item item = {{BIP138_CONTENT_BIP, BIP138_BIP_DESCRIPTOR, NULL, 0}, - (const uint8_t *)descriptor, - strlen(descriptor)}; - size_t pt_len = bip138_plaintext_size(&item, 1, 0); + size_t pt_len = bip138_plaintext_size(items, n_items, 0); size_t cap = bip138_encrypt_size(bip138_secret_bucket(count), NULL, 0, pt_len); uint8_t *pt = malloc(pt_len); uint8_t *blob = malloc(cap); - bool ok = - pt && blob && - bip138_plaintext_encode(&item, 1, 0, pt, pt_len, &pt_len) == BIP138_OK && - bip138_encrypt(kern_bip138_crypto(), keys, count, NULL, 0, pt, pt_len, - blob, cap, blob_len) == BIP138_OK; + bool ok = pt && blob && + bip138_plaintext_encode(items, n_items, 0, pt, pt_len, &pt_len) == + BIP138_OK && + bip138_encrypt(kern_bip138_crypto(), keys, count, NULL, 0, pt, + pt_len, blob, cap, blob_len) == BIP138_OK; free(pt); if (!ok) { free(blob); @@ -517,6 +549,53 @@ static bool forge_backup(const char *descriptor, uint8_t **blob_out, return true; } +/* A container written by the library alone, without Kern's approval mark: + * what another wallet, or an attacker holding only our xpub, can produce. */ +static bool forge_backup(const char *descriptor, uint8_t **blob_out, + size_t *blob_len) { + bip138_item item = {{BIP138_CONTENT_BIP, BIP138_BIP_DESCRIPTOR, NULL, 0}, + (const uint8_t *)descriptor, + strlen(descriptor)}; + return encrypt_items(descriptor, &item, 1, blob_out, blob_len); +} + +/* `blob`, opened with the wallet's key at `path`, written again with its + * "kern-alias" item holding `alias`: the approval mark stays the one Kern + * wrote for the old alias. */ +static bool swap_alias(const uint8_t *blob, size_t blob_len, + const char *descriptor, const char *path, + const char *alias, uint8_t **out, size_t *out_len) { + bip138_container cont; + char *xpub = NULL; + struct ext_key *key = NULL; + uint8_t pt[1024]; + size_t pt_len = 0; + bool ok = bip138_parse(blob, blob_len, &cont) == BIP138_OK && + key_get_xpub(path, &xpub) && + bip32_key_from_base58_alloc(xpub, &key) == WALLY_OK && + bip138_decrypt(kern_bip138_crypto(), &cont, key->pub_key + 1, 1, pt, + sizeof(pt), &pt_len, NULL) == BIP138_OK; + wally_free_string(xpub); + if (key) + bip32_key_free(key); + if (!ok) + return false; + bip138_item items[4]; + size_t n = 0; + bip138_item_iter it; + bip138_item_iter_init(&it, pt, pt_len); + while (n < 4 && bip138_item_next(&it, &items[n]) == 1) { + if (items[n].content.type == BIP138_CONTENT_PROPRIETARY && + items[n].content.tag_len == strlen("kern-alias") && + memcmp(items[n].content.tag, "kern-alias", strlen("kern-alias")) == 0) { + items[n].data = (const uint8_t *)alias; + items[n].data_len = strlen(alias); + } + n++; + } + return encrypt_items(descriptor, items, n, out, out_len); +} + static void test_approval_and_forgery(void) { char descriptor[256]; uint8_t *blob = NULL; @@ -527,17 +606,42 @@ static void test_approval_and_forgery(void) { check("descriptor builds", build_wpkh("m/84'/0'/3'", descriptor, sizeof(descriptor))); check("own backup encrypts", - bip138_backup_encrypt(descriptor, &blob, &blob_len)); + bip138_backup_encrypt(descriptor, NULL, &blob, &blob_len)); check("own backup is approved", - bip138_backup_decrypt(blob, blob_len, &recovered, &approved) && + bip138_backup_decrypt(blob, blob_len, &recovered, NULL, &approved) && approved && strcmp(recovered, descriptor) == 0); free(recovered); free(blob); + char *alias = NULL; + recovered = NULL; + check("own backup with alias encrypts", + bip138_backup_encrypt(descriptor, "Vault", &blob, &blob_len)); + check("own backup with alias is approved", + bip138_backup_decrypt(blob, blob_len, &recovered, &alias, &approved) && + approved && strcmp(alias, "Vault") == 0); + free(recovered); + free(alias); + uint8_t *swapped = NULL; + size_t swapped_len = 0; + recovered = NULL; + alias = NULL; + approved = true; + check("a backup whose alias was swapped is not approved", + swap_alias(blob, blob_len, descriptor, "m/84'/0'/3'", "Other", &swapped, + &swapped_len) && + bip138_backup_decrypt(swapped, swapped_len, &recovered, &alias, + &approved) && + !approved && strcmp(alias, "Other") == 0); + free(recovered); + free(alias); + free(swapped); + free(blob); + check("forged backup builds", forge_backup(descriptor, &blob, &blob_len)); approved = true; check("forged backup decrypts but is not approved", - bip138_backup_decrypt(blob, blob_len, &recovered, &approved) && + bip138_backup_decrypt(blob, blob_len, &recovered, NULL, &approved) && !approved); free(recovered); @@ -554,11 +658,11 @@ static void test_approval_and_forgery(void) { registry_count() == 0); recovered = NULL; check("an old unmarked backup still supports explicit import", - bip138_backup_decrypt(blob, blob_len, &recovered, &approved) && + bip138_backup_decrypt(blob, blob_len, &recovered, NULL, &approved) && !approved && descriptor_validate_keyed(recovered, NULL) == VALIDATION_SUCCESS); - /* Simulate the explicit confirmation and registration path. The fixture - * holds one flash file, so the unmarked one is replaced by the new one. */ + /* Simulate the explicit confirmation and registration path on an empty + * flash. */ stub_storage_reset(); blob = NULL; check( @@ -578,13 +682,13 @@ static void test_approval_and_forgery(void) { "", false) && wallet_init(WALLET_NETWORK_MAINNET)); check("another seed can still write a backup for this descriptor", - bip138_backup_encrypt(descriptor, &blob, &blob_len)); + bip138_backup_encrypt(descriptor, NULL, &blob, &blob_len)); check("original seed reloads", key_load_from_mnemonic(TEST_MNEMONIC, "", false) && wallet_init(WALLET_NETWORK_MAINNET)); approved = true; check("a backup marked by another seed decrypts but is not approved", - bip138_backup_decrypt(blob, blob_len, &recovered, &approved) && + bip138_backup_decrypt(blob, blob_len, &recovered, NULL, &approved) && !approved); free(recovered); free(blob); @@ -621,7 +725,7 @@ static void test_rejected_count(void) { registry_count() == 0 && registry_rejected_count() == 0); check("approved backup of it is staged", - bip138_backup_encrypt(descriptor, &blob, &blob_len) && + bip138_backup_encrypt(descriptor, NULL, &blob, &blob_len) && storage_save_descriptor(STORAGE_FLASH, "Forged", blob, blob_len, STORAGE_DESCRIPTOR_BIP138) == ESP_OK); free(blob); @@ -667,7 +771,7 @@ static void test_private_key_rejected(void) { xprv ? xprv : ""); wally_free_string(xprv); check("backup refuses a descriptor with a private key", - !bip138_backup_encrypt(descriptor, &blob, &blob_len)); + !bip138_backup_encrypt(descriptor, NULL, &blob, &blob_len)); check("keyed validation refuses it too", descriptor_validate_keyed(descriptor, NULL) == VALIDATION_PRIVATE_KEY); } @@ -683,14 +787,14 @@ static void test_overwrite_and_duplicates(void) { check("descriptors build", build_wpkh("m/84'/0'/4'", descriptor, sizeof(descriptor)) && build_wpkh("m/84'/0'/5'", other, sizeof(other))); - /* A file under this name already on flash, e.g. from another seed. */ + /* A file under this name's id already on flash, e.g. from another seed. */ check("foreign file staged", forge_backup(other, &blob, &blob_len)); stub_files[0].present = true; stub_files[0].data = blob; stub_files[0].len = blob_len; stub_files[0].format = STORAGE_DESCRIPTOR_BIP138; snprintf(stub_files[0].filename, sizeof(stub_files[0].filename), - "d_Shared.bip138"); + "d_e3c4b39d6d501347.bip138"); check("session entry adds", registry_add_from_string("desc_x", descriptor, STORAGE_FLASH, false)); check("persist refuses to overwrite an existing file", @@ -709,7 +813,7 @@ static void test_overwrite_and_duplicates(void) { check("flash registration", registry_add_from_string("Same", descriptor, STORAGE_FLASH, true)); check("SD backup of another descriptor saved under the same name", - bip138_backup_encrypt(other, &blob, &blob_len) && + bip138_backup_encrypt(other, NULL, &blob, &blob_len) && storage_save_descriptor(STORAGE_SD, "Same", blob, blob_len, STORAGE_DESCRIPTOR_BIP138) == ESP_OK); free(blob); @@ -720,7 +824,7 @@ static void test_overwrite_and_duplicates(void) { check("de-registration by index deletes the right file", registry_deregister_at(0) && registry_count() == 0 && stub_deletes == 1 && - strcmp(stub_last_deleted, "d_Same.bip138") == 0 && + strcmp(stub_last_deleted, "d_2a98b1deb68c7223.bip138") == 0 && stub_files[1].present); check("removal by bad index fails", !registry_remove_at(5)); registry_clear(); @@ -751,7 +855,7 @@ static void test_deregister(void) { check("de-registration removes the file and the session entry", registry_deregister_at(0) && registry_count() == 0 && !stub_files[0].present && - strcmp(stub_last_deleted, "d_Shared.bip138") == 0); + strcmp(stub_last_deleted, "d_e3c4b39d6d501347.bip138") == 0); registry_init(false); check("deleted registrations do not return on restart", registry_count() == 0); @@ -761,6 +865,107 @@ static void test_deregister(void) { stub_storage_reset(); } +/* 32 bytes that the filename sanitizer would rewrite: UTF-8, ' ', ':', '/' */ +#define LONG_ALIAS \ + "K\xc3\xbc" \ + "hl \xe2\x82\xac Wallet: \xc3\x9c" \ + "n\xc3\xaf/12345678" + +static void test_aliases(void) { + char descriptor[256]; + uint8_t *blob = NULL; + size_t blob_len = 0; + registry_clear(); + stub_storage_reset(); + check("alias fixture builds", + build_wpkh("m/84'/0'/2'", descriptor, sizeof(descriptor))); + check("a 32-byte alias registers", + strlen(LONG_ALIAS) == REGISTRY_ID_MAX_LEN - 1 && + registry_add_from_string(LONG_ALIAS, descriptor, STORAGE_FLASH, + true) && + strcmp(stub_files[0].filename, "d_925831f4d8fb8e1e.bip138") == 0); + check("the same descriptor registers under a second alias", + registry_add_from_string("Second", descriptor, STORAGE_FLASH, true) && + strcmp(stub_files[2].filename, "d_8b88a85089561b79.bip138") == 0); + registry_clear(); + registry_init(false); + check("both aliases of the descriptor load on restart", + registry_count() == 2 && registry_find_by_id("Second") && + registry_find_by_id("Second")->persisted); + const registry_entry_t *entry = registry_find_by_id(LONG_ALIAS); + check("the alias round-trips exactly", + entry && entry->persisted && strcmp(entry->id, LONG_ALIAS) == 0); + check("a registered alias is taken", registry_name_registered(LONG_ALIAS) && + !registry_name_registered("Other")); + check("de-registration deletes the alias's file", + registry_deregister_at(0) && + strcmp(stub_last_deleted, "d_925831f4d8fb8e1e.bip138") == 0); + + /* A backup written before aliases were stored keeps its filename id */ + registry_clear(); + stub_storage_reset(); + check("backup without alias saved", + bip138_backup_encrypt(descriptor, NULL, &blob, &blob_len) && + storage_save_descriptor(STORAGE_FLASH, "Legacy", blob, blob_len, + STORAGE_DESCRIPTOR_BIP138) == ESP_OK); + free(blob); + registry_init(false); + check("a backup without alias loads under its filename", + registry_count() == 1 && registry_find_by_id("Legacy") && + registry_find_by_id("Legacy")->persisted); + check("its de-registration deletes its file", + registry_deregister_at(0) && + strcmp(stub_last_deleted, "d_Legacy.bip138") == 0 && + !stub_files[0].present); + registry_clear(); + stub_storage_reset(); +} + +static void test_unregister(void) { + char descriptor[256]; + registry_clear(); + stub_storage_reset(); + check("unregister fixture builds", + build_wpkh("m/84'/0'/2'", descriptor, sizeof(descriptor))); + check("an unknown alias is not unregistered", + !registry_unregister("Nope") && stub_deletes == 0); + + check("session entry adds", + registry_add_from_string("Session", descriptor, STORAGE_FLASH, false)); + check("unregistering a session entry removes it without touching flash", + registry_unregister("Session") && registry_count() == 0 && + !registry_find_by_id("Session") && stub_deletes == 0); + + check( + "the descriptor registers under two aliases", + registry_add_from_string("ColdVault", descriptor, STORAGE_FLASH, true) && + registry_add_from_string("Second", descriptor, STORAGE_FLASH, true)); + stub_delete_fail = true; + check("a failed deletion keeps the registration", + !registry_unregister("ColdVault") && registry_find_by_id("ColdVault") && + stub_find(STORAGE_FLASH, "d_758a687821d156d5.bip138")); + stub_delete_fail = false; + check("unregistering one alias deletes only its backup", + registry_unregister("ColdVault") && + strcmp(stub_last_deleted, "d_758a687821d156d5.bip138") == 0 && + !stub_find(STORAGE_FLASH, "d_758a687821d156d5.bip138") && + stub_find(STORAGE_FLASH, "d_8b88a85089561b79.bip138")); + check("the other alias of the descriptor stays registered", + registry_count() == 1 && !registry_find_by_id("ColdVault") && + registry_find_by_id("Second") && + registry_find_by_id("Second")->persisted); + registry_init(false); + check("after a restart only the other alias loads", + registry_count() == 1 && !registry_find_by_id("ColdVault") && + registry_find_by_id("Second")); + check("the other alias unregisters too", + registry_unregister("Second") && + !stub_find(STORAGE_FLASH, "d_8b88a85089561b79.bip138")); + registry_init(false); + check("nothing returns after a restart", registry_count() == 0); + registry_clear(); + stub_storage_reset(); +} static void test_many_origins(void) { registry_clear(); stub_storage_reset(); @@ -806,13 +1011,13 @@ static void test_many_origins(void) { size_t many_len = 0; char *many_out = NULL; int validation = descriptor_validate_keyed(many, NULL); - int encrypted = bip138_backup_encrypt(many, &many_blob, &many_len); + int encrypted = bip138_backup_encrypt(many, NULL, &many_blob, &many_len); bip138_container many_cont; memset(&many_cont, 0, sizeof(many_cont)); if (encrypted) bip138_parse(many_blob, many_len, &many_cont); - int decrypted = - encrypted && bip138_backup_decrypt(many_blob, many_len, &many_out, NULL); + int decrypted = encrypted && bip138_backup_decrypt(many_blob, many_len, + &many_out, NULL, NULL); check("17-key miniscript is supported and recovers the 17th origin", validation == VALIDATION_SUCCESS && encrypted && many_cont.path_count == 17 && decrypted && @@ -854,6 +1059,8 @@ int main(void) { test_private_key_rejected(); test_overwrite_and_duplicates(); test_deregister(); + test_aliases(); + test_unregister(); test_many_origins(); key_unload(); printf("\n%d tests, %d failed\n", tests_run, tests_failed); diff --git a/main/core/test/test_descriptor_validator.c b/main/core/test/test_descriptor_validator.c index b0abfe30..08612471 100644 --- a/main/core/test/test_descriptor_validator.c +++ b/main/core/test/test_descriptor_validator.c @@ -36,8 +36,7 @@ static void check(const char *name, bool ok) { printf("Testing: %s... %s\n", name, ok ? "PASS" : "FAIL"); } -/* ---------- storage stubs (registry persistence is never reached) ---------- - */ +/* ---------- storage stubs (registry persistence writes nowhere) ---------- */ static int storage_saves; @@ -139,7 +138,8 @@ static void done_cb(descriptor_validation_result_t result, void *user_data) { } static void info_cb(const descriptor_info_t *info, - void (*proceed)(bool, void *)) { + void (*proceed)(bool, void *), void *user_data) { + (void)user_data; info_calls++; info_seen = *info; /* The validator frees its policy when the flow completes. */ @@ -161,6 +161,15 @@ static void warn_cb(const char *message, void (*proceed)(bool, void *)) { warn_proceed = proceed; } +static int id_loc_calls; + +static void id_loc_cb(void (*proceed)(const char *id, storage_location_t loc, + void *user_data), + void *user_data) { + id_loc_calls++; + proceed("persisted", STORAGE_FLASH, user_data); +} + static int marker; static descriptor_validation_result_t run(const char *desc) { @@ -848,7 +857,8 @@ static void test_multisig_and_miniscript(void) { check("2-of-3 sortedmulti accepted", run(ms2of3) == VALIDATION_SUCCESS); check("info: multisig 2 of 3", info_seen.is_multisig && !info_seen.is_miniscript && - info_seen.threshold == 2 && info_seen.num_keys == 3); + info_seen.threshold == 2 && info_seen.num_keys == 3 && + info_seen.is_sorted); check("info: cosigner fingerprint reported", strcmp(info_seen.keys[1].fingerprint_hex, "DEADBEEF") == 0 && strcmp(info_seen.keys[1].derivation, "m/48'/0'/1'/2'") == 0); @@ -856,14 +866,18 @@ static void test_multisig_and_miniscript(void) { strcmp(info_seen.keys[2].fingerprint_hex, "N/A") == 0 && strcmp(info_seen.keys[2].derivation, "N/A") == 0 && strcmp(info_seen.keys[2].xpub, c) == 0); - check("session label Multisig (2 of 3)", - registry_has_label("Multisig (2 of 3)")); + check("session label sortedmulti 2 of 3", + registry_has_label("sortedmulti 2 of 3")); const char *ms_ours_last = descf("wsh(multi(1,[deadbeef/48'/0'/1'/2']%s/0/*," "[" FP "/48'/0'/0'/2']%s/0/*))", b, a); check("our key found at a later index", run(ms_ours_last) == VALIDATION_SUCCESS); + check("info: multi is not sorted", info_seen.is_multisig && + !info_seen.is_sorted && + info_seen.threshold == 1); + check("session label multi 1 of 2", registry_has_label("multi 1 of 2")); const char *msc1 = descf("wsh(and_v(v:pk([" FP "/48'/0'/0'/2']%s/0/*)," "older(144)))", @@ -1117,6 +1131,25 @@ static void test_dedup(void) { registry_clear(); } +/* descriptor_validate_and_load_persistent() registers under the id it is + * given, so a descriptor already loaded gets a second id. */ +static void test_persistent_registration(void) { + registry_clear(); + check("seed descriptor loads", run(wpkh84()) == VALIDATION_SUCCESS); + + capture_reset(); + id_loc_calls = 0; + descriptor_validate_and_load_persistent(wpkh84(), done_cb, warn_cb, info_cb, + id_loc_cb, &marker); + check("persistent registration of a loaded descriptor is reviewed", + done_result == VALIDATION_SUCCESS && info_calls == 1); + check("persistent registration requests the storage id", id_loc_calls == 1); + check("persistent registration adds a second entry", + registry_count() == 2 && registry_find_by_id("persisted") && + registry_find_by_id("persisted")->persisted); + registry_clear(); +} + static void test_generation_guard(void) { registry_clear(); capture_reset(); @@ -1278,6 +1311,7 @@ int main(void) { test_long_policy(); test_network(); test_dedup(); + test_persistent_registration(); test_generation_guard(); test_watch_only(); diff --git a/main/core/test/test_key.c b/main/core/test/test_key.c index e5a49067..253e2433 100644 --- a/main/core/test/test_key.c +++ b/main/core/test/test_key.c @@ -190,6 +190,11 @@ static void test_fingerprint_and_xpubs(void) { check("root path yields the master xpub", key_get_xpub("m", &xpub) && xpub && strcmp(xpub, MASTER_XPUB) == 0); wally_free_string(xpub); + xpub = NULL; + check("components at depth zero yield the master xpub", + key_get_xpub_components(NULL, 0, &xpub) && xpub && + strcmp(xpub, MASTER_XPUB) == 0); + wally_free_string(xpub); check("malformed path rejected", !key_get_xpub("m/84'/x/0'", &xpub) && !key_get_xpub("m//0", &xpub)); diff --git a/main/core/test/test_registry_match.c b/main/core/test/test_registry_match.c index 011d65b9..e31ebf36 100644 --- a/main/core/test/test_registry_match.c +++ b/main/core/test/test_registry_match.c @@ -221,6 +221,55 @@ int main(void) { PASS(); } + printf("\n--- preferred entries first ---\n"); + seed_registry(); + if (!registry_add_from_string("e3", "tr([00000000/86'/0'/0']" XPUB_86 "/0/*)", + STORAGE_FLASH, false)) + FAIL("registry_add_from_string e3"); + n = keypath(kp, 5, H(86), H(0), H(0), 0u, 3u); + { + registry_match_cursor_t cursor = {0}; + uint32_t mi = 0, cn = 0; + TEST("registry order without a preference returns e2"); + registry_entry_t *r = registry_match_keypath(kp, n, &cursor, &mi, &cn); + if (!r || strcmp(r->id, "e2") != 0) + FAIL("expected e2"); + else + PASS(); + + registry_prefer("e3"); + cursor = (registry_match_cursor_t){0}; + TEST("preferred e3 comes first"); + r = registry_match_keypath(kp, n, &cursor, &mi, &cn); + if (!r || strcmp(r->id, "e3") != 0) + FAIL("expected e3"); + else + PASS(); + + TEST("e2 follows the preferred entry"); + r = registry_match_keypath(kp, n, &cursor, &mi, &cn); + if (!r || strcmp(r->id, "e2") != 0) + FAIL("expected e2"); + else + PASS(); + + TEST("match order ends after every entry"); + r = registry_match_keypath(kp, n, &cursor, &mi, &cn); + if (r != NULL || registry_match_order_get(4) != NULL) + FAIL("expected NULL"); + else + PASS(); + + registry_clear_preferred(); + cursor = (registry_match_cursor_t){0}; + TEST("cleared preference restores registry order"); + r = registry_match_keypath(kp, n, &cursor, &mi, &cn); + if (!r || strcmp(r->id, "e2") != 0) + FAIL("expected e2"); + else + PASS(); + } + registry_clear(); printf("\n=== Results: %d passed, %d failed ===\n", tests_passed, tests_failed); diff --git a/main/core/test/test_ss_whitelist_regen.c b/main/core/test/test_ss_whitelist_regen.c index 0a866bad..5e3ea682 100644 --- a/main/core/test/test_ss_whitelist_regen.c +++ b/main/core/test/test_ss_whitelist_regen.c @@ -5,6 +5,7 @@ #include "core/key.h" #include "core/ss_whitelist.h" +#include static int tests_passed = 0; static int tests_failed = 0; @@ -126,6 +127,23 @@ static void test_chain_matches_full_derivation(void) { } } +static void test_xpub_prefix(const char *name, const char *path, + const char *prefix) { + TEST(name); + char *xpub = NULL; + if (!key_get_xpub(path, &xpub) || !xpub) { + FAIL("key_get_xpub failed"); + return; + } + if (strncmp(xpub, prefix, strlen(prefix)) != 0) { + wally_free_string(xpub); + FAIL("wrong xpub prefix"); + return; + } + wally_free_string(xpub); + PASS(); +} + int main(void) { /* The host libwally hashes through PSA, as the device does, which needs * wally_init. */ @@ -178,6 +196,21 @@ int main(void) { test_chain_matches_full_derivation(); key_unload(); + printf("\n--- Group 4: xpub version follows requested coin type ---\n"); + { + TEST("key_load_from_mnemonic testnet"); + if (!key_load_from_mnemonic(TEST_MNEMONIC, "", true)) { + FAIL("failed to load testnet mnemonic"); + } else { + PASS(); + test_xpub_prefix("testnet seed exports xpub for coin 0'", + "m/48'/0'/0'/2'", "xpub"); + test_xpub_prefix("testnet seed exports tpub for coin 1'", + "m/48'/1'/0'/2'", "tpub"); + key_unload(); + } + } + printf("\n=== Results: %d passed, %d failed ===\n", tests_passed, tests_failed); return tests_failed > 0 ? 1 : 0; diff --git a/main/main.c b/main/main.c index cd7803ad..77e5ab79 100644 --- a/main/main.c +++ b/main/main.c @@ -1,5 +1,6 @@ #include "bus_timeout.h" #include "core/crypto_init.h" +#include "core/debug_log.h" #include "core/entropy_pool.h" #include "core/fw_update.h" #include "core/nvs_secure.h" @@ -38,6 +39,7 @@ void app_main(void) { // provisioned, plaintext otherwise (never stock nvs_flash_init(): its // keygen path would burn KEY4 without consent) ESP_ERROR_CHECK(nvs_secure_init()); + debug_log_event("boot"); // Not fatal: every getter falls back to its default when the namespace is // unavailable, and those defaults are the safe ones. esp_err_t settings_ret = settings_init(); diff --git a/main/pages/bip_flow/bip388.c b/main/pages/bip_flow/bip388.c new file mode 100644 index 00000000..f2f2b51d --- /dev/null +++ b/main/pages/bip_flow/bip388.c @@ -0,0 +1,75 @@ +#include "bip388.h" + +#include +#include +#include +#include + +#define BIP388_WILDCARD "/**" +#define BIP388_MULTIPATH "/<0;1>/*" + +static bool is_digit(char c) { return c >= '0' && c <= '9'; } + +// Reads the N of the @N at *p, moving *p past it. False when N names no key. +static bool read_key_index(const char **p, size_t key_count, size_t *index) { + const char *digits = *p + 1; + if (!is_digit(*digits)) + return false; + size_t n = 0; + for (; is_digit(*digits); digits++) { + n = n * 10 + (size_t)(*digits - '0'); + if (n >= key_count) + return false; + } + *p = digits; + *index = n; + return true; +} + +// The length of the descriptor, written to `out` when not NULL. SIZE_MAX when +// an @N names no key. +static size_t expand(const char *policy, const char *const *keys, + size_t key_count, char *out) { + size_t len = 0; + const char *p = policy; + while (*p) { + const char *piece = p; + size_t piece_len = 1; + size_t index; + if (strncmp(p, BIP388_WILDCARD, strlen(BIP388_WILDCARD)) == 0) { + piece = BIP388_MULTIPATH; + piece_len = strlen(BIP388_MULTIPATH); + p += strlen(BIP388_WILDCARD); + } else if (*p == '@') { + if (!read_key_index(&p, key_count, &index) || !keys[index]) + return SIZE_MAX; + piece = keys[index]; + piece_len = strlen(piece); + } else { + p++; + } + if (out) + memcpy(out + len, piece, piece_len); + len += piece_len; + } + return len; +} + +bool bip388_policy_is_valid(const char *policy, const char *const *keys, + size_t key_count) { + return policy && (keys || key_count == 0) && + expand(policy, keys, key_count, NULL) != SIZE_MAX; +} + +char *bip388_descriptor_alloc(const char *policy, const char *const *keys, + size_t key_count) { + if (!bip388_policy_is_valid(policy, keys, key_count)) + return NULL; + size_t len = expand(policy, keys, key_count, NULL); + char *out = malloc(len + 1); + if (!out) + return NULL; + expand(policy, keys, key_count, out); + out[len] = '\0'; + return out; +} diff --git a/main/pages/bip_flow/bip388.h b/main/pages/bip_flow/bip388.h new file mode 100644 index 00000000..964fd7cf --- /dev/null +++ b/main/pages/bip_flow/bip388.h @@ -0,0 +1,17 @@ +#ifndef BIP388_H +#define BIP388_H + +#include +#include + +// True when every @N of the BIP-388 wallet policy names one of its keys +bool bip388_policy_is_valid(const char *policy, const char *const *keys, + size_t key_count); + +// The BIP-380 descriptor of a BIP-388 wallet policy: each @N becomes keys[N] +// and each /** becomes /<0;1>/*. NULL when the policy is not valid or out of +// memory. +char *bip388_descriptor_alloc(const char *policy, const char *const *keys, + size_t key_count); + +#endif /* BIP388_H */ diff --git a/main/pages/bip_flow/bip_flow.c b/main/pages/bip_flow/bip_flow.c new file mode 100644 index 00000000..4e1bb562 --- /dev/null +++ b/main/pages/bip_flow/bip_flow.c @@ -0,0 +1,1298 @@ +#include "bip_flow.h" + +#include "../../components/bbqr/src/bbqr.h" +#include "../../core/bip32_path.h" +#include "../../core/debug_log.h" +#include "../../core/key.h" +#include "../../core/psbt.h" +#include "../../core/registry.h" +#include "../../core/settings.h" +#include "../../core/storage.h" +#include "../../core/wallet.h" +#include "../../qr/encoder.h" +#include "../../qr/parser.h" +#include "../../qr/viewer.h" +#include "../../ui/dialog.h" +#include "../../ui/theme.h" +#include "../../ui/theme_widgets.h" +#include "../../utils/secure_mem.h" +#include "../scan/scan.h" +#include "../shared/address_checker.h" +#include "../shared/descriptor_loader.h" +#include "bip388.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define KERN_CAPABILITIES \ + (BIPQR_CAPABILITY_BIP380_DESCRIPTORS | \ + BIPQR_CAPABILITY_BIP388_WALLET_POLICIES | \ + BIPQR_CAPABILITY_MINISCRIPT_SEGWIT_V0 | \ + BIPQR_CAPABILITY_MINISCRIPT_TAPROOT | \ + BIPQR_CAPABILITY_UNREGISTER_DESCRIPTOR) + +typedef struct { + lv_obj_t *parent; + void (*return_cb)(void); + bip_flow_header_t header; + const bipqr_request *request; +} bip_flow_ctx_t; + +static bip_flow_ctx_t ctx; +// The verified address and its BIP-321 URI, both from malloc() +static char *pending_verified_address = NULL; +static char *pending_verified_uri = NULL; +// What the verified address is, shown under the title +static char pending_verify_caption[REGISTRY_ID_MAX_LEN + 32]; +static lv_obj_t *verify_address_detail = NULL; +static lv_obj_t *verify_address_approve_btn = NULL; +static bool signing_response_return_pending = false; + +static void destroy_verify_address_detail(void) { + if (verify_address_detail) { + lv_obj_del(verify_address_detail); + verify_address_detail = NULL; + } + verify_address_approve_btn = NULL; +} + +static void clear_pending_verify(void) { + destroy_verify_address_detail(); + free(pending_verified_address); + pending_verified_address = NULL; + free(pending_verified_uri); + pending_verified_uri = NULL; + pending_verify_caption[0] = '\0'; +} + +bool bip_flow_can_handle(const uint8_t *data, size_t len) { + return data && len >= 6 && memcmp(data, "BIP", 3) == 0; +} + +static void cleanup_request(void) { + registry_clear_preferred(); + if (ctx.request) { + bipqr_request_free(ctx.request); + ctx.request = NULL; + } +} + +static void return_from_response(void) { + qr_viewer_page_destroy(); + clear_pending_verify(); + cleanup_request(); + if (ctx.return_cb) + ctx.return_cb(); +} + +static void signing_response_return_timer_cb(lv_timer_t *timer) { + (void)timer; + debug_log_event("bip_flow signing_response deferred_return"); + signing_response_return_pending = false; + qr_viewer_page_destroy(); + cleanup_request(); + if (ctx.return_cb) + ctx.return_cb(); +} + +static void return_from_signing_response(void) { + debug_log_event("bip_flow signing_response done"); + if (signing_response_return_pending) + return; + signing_response_return_pending = true; + lv_timer_t *timer = + lv_timer_create(signing_response_return_timer_cb, 1, NULL); + if (timer) { + lv_timer_set_repeat_count(timer, 1); + } else { + signing_response_return_pending = false; + signing_response_return_timer_cb(NULL); + } +} + +static void show_response_sized(bipqr_response *response, void (*done_cb)(void), + int max_chars) { + debug_logf("bip_flow show_response is_error=%d", response->is_error); + bipqr_buf encoded = {0}; + const char *err = NULL; + int32_t rc = bipqr_response_encode(response, &encoded, &err); + if (rc != BIPQR_OK || !encoded.ptr || encoded.len == 0) { + cleanup_request(); + dialog_show_error_timeout(err ? err : "Failed to encode response", + ctx.return_cb, 0); + return; + } + + BBQrParts *parts = + bbqr_encode_hex(encoded.ptr, encoded.len, BBQR_TYPE_BINARY, max_chars); + bipqr_buf_free(encoded); + if (!parts) { + cleanup_request(); + dialog_show_error_timeout("Failed to encode response QR", ctx.return_cb, 0); + return; + } + + if (!qr_viewer_page_create_with_bbqr_parts(ctx.parent, parts, "Response QR", + done_cb)) { + cleanup_request(); + dialog_show_error_timeout("Failed to display response", ctx.return_cb, 0); + return; + } + qr_viewer_page_show(); +} + +static void show_response_with_done(bipqr_response *response, + void (*done_cb)(void)) { + show_response_sized(response, done_cb, settings_get_qr_density()); +} + +static void show_response(bipqr_response *response) { + show_response_with_done(response, return_from_response); +} + +static void fill_response_header(bipqr_response *response) { + memset(response, 0, sizeof(*response)); + memcpy(response->id, ctx.header.id, BIPQR_REQUEST_ID_LEN); + response->message_type = ctx.header.message_type; +} + +static void fill_error_response(bipqr_response *response, uint8_t error, + const char *message) { + debug_logf("bip_flow error_response code=%u msg=%s", (unsigned)error, + message ? message : ""); + fill_response_header(response); + response->is_error = true; + response->body.error.error = error; + response->body.error.message = message ? message : "Error"; +} + +static void show_error_response(uint8_t error, const char *message) { + bipqr_response response; + fill_error_response(&response, error, message); + show_response(&response); +} + +// Kern keeps its registrations on the device and issues no proof of +// registration, so a proof it receives is not one of its own +static void show_foreign_proof_error(void) { + show_error_response(BIPQR_RESPONSE_ERROR_INVALID_PROOF, + "Kern issues no proof of registration"); +} + +static bool wallet_is_testnet(void) { + return wallet_get_network() == WALLET_NETWORK_TESTNET; +} + +static void fill_device_fields(const char **vendor, const char **model, + bipqr_firmware_version *version, + uint32_t *capabilities) { + *vendor = "Kern"; + *model = CONFIG_KERN_BOARD_NAME; + const esp_app_desc_t *desc = esp_app_get_description(); + unsigned major = 0, minor = 0, patch = 0; + if (desc) + sscanf(desc->version, "%u.%u.%u", &major, &minor, &patch); + version->major = (uint16_t)major; + version->minor = (uint16_t)minor; + version->patch = patch; + version->flag = BIPQR_RELEASE_STABLE; + *capabilities = KERN_CAPABILITIES; +} + +// Ready with a loaded seed, locked while an encrypted one waits on flash +static bool device_state(uint8_t *state_out) { + if (key_is_loaded()) { + *state_out = BIPQR_STATE_READY; + return true; + } + char **files = NULL; + int count = 0; + if (storage_list_mnemonics(STORAGE_FLASH, &files, &count) != ESP_OK) + return false; + storage_free_file_list(files, count); + *state_out = count > 0 ? BIPQR_STATE_LOCKED : BIPQR_STATE_UNINITIALIZED; + return true; +} + +static void handle_get_info(void) { + bipqr_response response; + fill_response_header(&response); + bipqr_info *info = &response.body.info; + fill_device_fields(&info->vendor, &info->model, &info->version, + &info->capabilities); + if (!device_state(&info->state)) { + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "Storage failed"); + return; + } + // Coin 1' covers testnet and signet; no regtest, Kern only encodes tb + // addresses + info->networks = + BIPQR_NETWORK_MAINNET | BIPQR_NETWORK_TESTNET | BIPQR_NETWORK_SIGNET; + info->max_message = QR_PARSER_MAX_STORED_BYTES; + info->max_alias = REGISTRY_ID_MAX_LEN - 1; + if (info->state == BIPQR_STATE_READY) { + if (!key_get_fingerprint(info->fingerprint)) { + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "Fingerprint failed"); + return; + } + info->has_fingerprint = 1; + } + show_response(&response); +} + +static bool xpub_base58_to_wire(const char *xpub, bipqr_extended_key *out) { + struct ext_key *key = NULL; + bool ok = false; + if (bip32_key_from_base58_alloc(xpub, &key) == WALLY_OK && key) { + uint8_t serialized[BIPQR_EXTENDED_KEY_LEN]; + if (bip32_key_serialize(key, BIP32_FLAG_KEY_PUBLIC, serialized, + sizeof(serialized)) == WALLY_OK) { + memcpy(out->bytes, serialized, sizeof(out->bytes)); + ok = true; + } + } + if (key) + bip32_key_free(key); + return ok; +} + +static bool public_key_to_wire(const bipqr_path *path, + bipqr_extended_key *out) { + char *xpub = NULL; + bool ok = key_get_xpub_components(path->ptr, path->len, &xpub) && xpub && + xpub_base58_to_wire(xpub, out); + if (xpub) + wally_free_string(xpub); + return ok; +} + +static void free_keys(bipqr_extended_key *keys, size_t n) { + secure_memzero(keys, n * sizeof(*keys)); + free(keys); +} + +static void get_keys_confirm_cb(bool confirmed, void *user_data) { + (void)user_data; + if (!confirmed) { + show_error_response(BIPQR_RESPONSE_ERROR_USER_DECLINED, "Declined"); + return; + } + + const bipqr_get_keys *req = &ctx.request->body.get_keys; + size_t n = req->keys.len; + bipqr_extended_key *keys = calloc(n, sizeof(*keys)); + // An empty KEYS vector is valid and gets an empty one back + if (!keys && n) { + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "Out of memory"); + return; + } + + for (size_t i = 0; i < n; i++) { + const bipqr_key_request *key = &req->keys.ptr[i]; + if (!public_key_to_wire(&key->derivation_path, &keys[i])) { + free_keys(keys, n); + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "Key failed"); + return; + } + } + + bipqr_response response; + fill_response_header(&response); + response.body.keys.keys.ptr = keys; + response.body.keys.keys.len = n; + if (!key_get_fingerprint(response.body.keys.fingerprint)) { + free_keys(keys, n); + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "Fingerprint failed"); + return; + } + fill_device_fields(&response.body.keys.vendor, &response.body.keys.model, + &response.body.keys.version, + &response.body.keys.capabilities); + // A quarter of the data per frame: half the modules per side, twice as big + int max_chars = settings_get_qr_density() / 4; + show_response_sized(&response, return_from_response, + max_chars < QR_DENSITY_MIN ? QR_DENSITY_MIN : max_chars); + free_keys(keys, n); +} + +static bool path_requested_network(const bipqr_path *path, + wallet_network_t *network_out) { + if (!path || !network_out || path->len < 2) + return false; + + uint32_t coin = bip32_path_unharden(path->ptr[1]); + if (coin == 0) { + *network_out = WALLET_NETWORK_MAINNET; + return true; + } + if (coin == 1) { + *network_out = WALLET_NETWORK_TESTNET; + return true; + } + return false; +} + +static bool get_keys_network_matches_wallet(const bipqr_key_request_list *keys, + char *message, + size_t message_size) { + if (!keys || !keys->ptr) + return true; + + bool have_network = false; + wallet_network_t requested = WALLET_NETWORK_MAINNET; + for (size_t i = 0; i < keys->len; i++) { + wallet_network_t path_network; + if (!path_requested_network(&keys->ptr[i].derivation_path, &path_network)) + continue; + if (!have_network) { + requested = path_network; + have_network = true; + continue; + } + if (requested != path_network) { + snprintf(message, message_size, + "Request mixes mainnet and testnet paths"); + return false; + } + } + + if (!have_network || requested == wallet_get_network()) + return true; + + snprintf(message, message_size, + "Request is for %s. Switch Kern network first.", + requested == WALLET_NETWORK_MAINNET ? "Mainnet" : "Testnet"); + return false; +} + +static size_t appendf(char *buf, size_t buf_size, size_t off, const char *fmt, + ...) { + if (off >= buf_size) + return off; + + va_list args; + va_start(args, fmt); + int written = vsnprintf(buf + off, buf_size - off, fmt, args); + va_end(args); + if (written < 0) + return off; + off += (size_t)written; + return off > buf_size ? buf_size : off; +} + +static size_t append_path_component(char *buf, size_t buf_size, size_t off, + uint32_t component) { + uint32_t child = bip32_path_unharden(component); + return bip32_path_is_hardened(component) + ? appendf(buf, buf_size, off, "/%u'", (unsigned)child) + : appendf(buf, buf_size, off, "/%u", (unsigned)child); +} + +static bool format_key_path_range(const bipqr_key_request_list *keys, char *buf, + size_t buf_size) { + if (!keys || keys->len < 2 || !keys->ptr || !buf || buf_size == 0) + return false; + + uint8_t depth = keys->ptr[0].derivation_path.len; + if (depth == 0) + return false; + + int varying_index = -1; + for (uint8_t i = 0; i < depth; i++) { + uint32_t first = keys->ptr[0].derivation_path.ptr[i]; + bool varies = false; + for (size_t j = 1; j < keys->len; j++) { + if (!keys->ptr[j].derivation_path.ptr || + keys->ptr[j].derivation_path.len != depth) + return false; + if (keys->ptr[j].derivation_path.ptr[i] != first) + varies = true; + } + if (!varies) + continue; + if (varying_index >= 0) + return false; + varying_index = i; + } + if (varying_index < 0) + return false; + + uint32_t first = keys->ptr[0].derivation_path.ptr[varying_index]; + bool hardened = bip32_path_is_hardened(first); + uint32_t first_child = bip32_path_unharden(first); + for (size_t i = 1; i < keys->len; i++) { + uint32_t component = keys->ptr[i].derivation_path.ptr[varying_index]; + if (bip32_path_is_hardened(component) != hardened) + return false; + if (bip32_path_unharden(component) != first_child + i) + return false; + } + + size_t off = appendf(buf, buf_size, 0, "m"); + for (uint8_t i = 0; i < depth; i++) { + if (i == (uint8_t)varying_index) { + uint32_t last_child = first_child + (uint32_t)keys->len - 1; + off = appendf(buf, buf_size, off, hardened ? "/{%u-%u}'" : "/{%u-%u}", + (unsigned)first_child, (unsigned)last_child); + } else { + off = append_path_component(buf, buf_size, off, + keys->ptr[0].derivation_path.ptr[i]); + } + } + + return off < buf_size; +} + +static size_t append_key_request_paths(char *msg, size_t msg_size, size_t off, + const bipqr_key_request_list *keys) { + char range_path[128]; + if (format_key_path_range(keys, range_path, sizeof(range_path))) + return appendf(msg, msg_size, off, "\n\n%s", range_path); + + size_t shown = keys->len < 6 ? keys->len : 6; + for (size_t i = 0; i < shown && off < msg_size; i++) { + char path[96]; + if (!bip32_path_format(keys->ptr[i].derivation_path.ptr, + keys->ptr[i].derivation_path.len, path, + sizeof(path))) { + snprintf(path, sizeof(path), ""); + } + off = appendf(msg, msg_size, off, "\n%s", path); + } + if (keys->len > shown) + off = appendf(msg, msg_size, off, "\n...and %zu more", keys->len - shown); + return off; +} + +static bool get_keys_has_private(const bipqr_key_request_list *keys) { + for (size_t i = 0; i < keys->len; i++) { + if (keys->ptr[i].kind == BIPQR_KEY_PRIVATE) + return true; + } + return false; +} + +static void handle_get_keys(void) { + const bipqr_get_keys *req = &ctx.request->body.get_keys; + char mismatch[80]; + if (!get_keys_network_matches_wallet(&req->keys, mismatch, + sizeof(mismatch))) { + debug_logf("bip_flow keys_network_mismatch msg=%s", mismatch); + show_error_response(BIPQR_RESPONSE_ERROR_NETWORK_MISMATCH, mismatch); + return; + } + // Kern exports no private key + if (get_keys_has_private(&req->keys)) { + show_error_response(BIPQR_RESPONSE_ERROR_PRIVATE_KEY_EXPORT_REFUSED, + "Private key export refused"); + return; + } + + char msg[512]; + size_t off = + snprintf(msg, sizeof(msg), "Export %zu key(s)?\n", req->keys.len); + append_key_request_paths(msg, sizeof(msg), off, &req->keys); + dialog_show_confirm(msg, get_keys_confirm_cb, NULL, DIALOG_STYLE_OVERLAY); +} + +static char *request_descriptor_alloc(const bipqr_descriptor_body *body) { + if (!body) + return NULL; + if (body->tag == BIPQR_DESCRIPTOR_BIP380) + return body->value.bip380 ? strdup(body->value.bip380) : NULL; + if (body->tag == BIPQR_DESCRIPTOR_BIP388) + return bip388_descriptor_alloc(body->value.bip388.policy, + body->value.bip388.keys.ptr, + body->value.bip388.keys.len); + return NULL; +} + +// The error a body request_descriptor_alloc() gives no descriptor for answers +// with: registration failed when it holds none, such as a wallet policy whose +// @N names no key, internal error when the descriptor could not be allocated +static uint8_t request_descriptor_error(const bipqr_descriptor_body *body) { + bool has_descriptor = + body && ((body->tag == BIPQR_DESCRIPTOR_BIP380 && body->value.bip380) || + (body->tag == BIPQR_DESCRIPTOR_BIP388 && + bip388_policy_is_valid(body->value.bip388.policy, + body->value.bip388.keys.ptr, + body->value.bip388.keys.len))); + return has_descriptor ? BIPQR_RESPONSE_ERROR_INTERNAL + : BIPQR_RESPONSE_ERROR_DESCRIPTOR_REGISTRATION_FAILED; +} + +static const char * +register_error_message(descriptor_validation_result_t result) { + switch (result) { + case VALIDATION_FINGERPRINT_NOT_FOUND: + return "Key not found in descriptor"; + case VALIDATION_XPUB_MISMATCH: + return "A key with your fingerprint is not yours"; + case VALIDATION_PARSE_ERROR: + return "Invalid descriptor format"; + case VALIDATION_INVALID_HARDENED_NOTATION: + return "Descriptor uses 'H'. Use ' or h for hardened."; + case VALIDATION_UNSUPPORTED_MINISCRIPT: + return "Only wsh() and tr() miniscript is supported"; + case VALIDATION_UNSUPPORTED_TOP_LEVEL: + return "Descriptor type not supported (use sh, wsh or tr)"; + case VALIDATION_UNSUPPORTED_SCRIPT: + return "Script too large (max 15 multisig keys)"; + case VALIDATION_PRIVATE_KEY: + return "Descriptor contains a private key"; + case VALIDATION_TOO_MANY_KEYS: + return "Too many keys in descriptor"; + case VALIDATION_UNSUPPORTED_KEY_ORIGIN: + return "Your key's derivation path is not supported"; + case VALIDATION_TR_INTERNAL_NOT_UNSPENDABLE: + return "Taproot internal key not provably unspendable"; + case VALIDATION_NETWORK_MISMATCH: + return "Descriptor network mismatch"; + case VALIDATION_DUPLICATE: + return "Descriptor already registered"; + case VALIDATION_INTERNAL_ERROR: + default: + return "Registration failed"; + } +} + +// The registration status of the request's alias: a descriptor, stored or +// for the session +static void answer_registration(void) { + const char *alias = ctx.request->body.register_descriptor.descriptor_alias; + const registry_entry_t *entry = registry_find_by_id(alias); + bipqr_response response; + fill_response_header(&response); + response.body.registration.descriptor_alias = alias; + response.body.registration.registered = entry != NULL; + response.body.registration.stored = entry && entry->persisted; + show_response(&response); +} + +static void show_alias_taken_error(void) { + show_error_response(BIPQR_RESPONSE_ERROR_ALREADY_REGISTERED, + "Alias already registered"); +} + +static void register_validation_cb(descriptor_validation_result_t result, + void *user_data) { + (void)user_data; + debug_logf("bip_flow register_validation result=%d", result); + if (result != VALIDATION_SUCCESS) { + show_error_response(bip_flow_register_error(result), + register_error_message(result)); + return; + } + answer_registration(); +} + +// Registers `descriptor` under the request's alias, which `entry` already +// holds when not NULL: a stored alias is taken, a session one may be +// registered again with its own descriptor +static void register_descriptor(const registry_entry_t *entry, + const char *descriptor) { + const char *alias = ctx.request->body.register_descriptor.descriptor_alias; + if (entry && + (entry->persisted || !registry_entry_is_descriptor(entry, descriptor))) { + show_alias_taken_error(); + return; + } + if (strlen(alias) >= REGISTRY_ID_MAX_LEN) { + show_error_response(BIPQR_RESPONSE_ERROR_DESCRIPTOR_REGISTRATION_FAILED, + "Alias too long"); + return; + } + debug_logf("bip_flow register descriptor_ok alias=%s", alias); + descriptor_loader_process_string_with_id(descriptor, alias, STORAGE_FLASH, + register_validation_cb, NULL); +} + +// Without a descriptor the request only asks whether the alias is registered +static void handle_register(void) { + debug_log_event("bip_flow handle_register"); + const bipqr_register_descriptor *req = &ctx.request->body.register_descriptor; + const registry_entry_t *entry = registry_find_by_id(req->descriptor_alias); + if (!req->descriptor) { + answer_registration(); + return; + } + char *descriptor = request_descriptor_alloc(req->descriptor); + if (!descriptor) { + uint8_t error = request_descriptor_error(req->descriptor); + show_error_response(error, error == BIPQR_RESPONSE_ERROR_INTERNAL + ? "Out of memory" + : "Invalid wallet policy"); + return; + } + register_descriptor(entry, descriptor); + free(descriptor); +} + +// The registry entry of `alias`, the session registering `body` under it +// when the alias is unknown. Returns 0 or the error code to answer with. +static uint8_t resolve_descriptor(const char *alias, + const bipqr_descriptor_body *body, + const registry_entry_t **entry_out) { + *entry_out = registry_find_by_id(alias); + if (*entry_out) + return 0; + if (!body) + return BIPQR_RESPONSE_ERROR_UNKNOWN_DESCRIPTOR_ALIAS; + char *descriptor = request_descriptor_alloc(body); + if (!descriptor) + return request_descriptor_error(body); + wallet_network_t network; + if (descriptor_infer_network(descriptor, &network) && + network != wallet_get_network()) { + free(descriptor); + return BIPQR_RESPONSE_ERROR_NETWORK_MISMATCH; + } + bool added = + registry_add_from_string(alias, descriptor, STORAGE_FLASH, false); + free(descriptor); + *entry_out = added ? registry_find_by_id(alias) : NULL; + return *entry_out ? 0 : BIPQR_RESPONSE_ERROR_DESCRIPTOR_REGISTRATION_FAILED; +} + +static void show_descriptor_error(uint8_t error) { + switch (error) { + case BIPQR_RESPONSE_ERROR_UNKNOWN_DESCRIPTOR_ALIAS: + show_error_response(error, "Unknown descriptor alias"); + break; + case BIPQR_RESPONSE_ERROR_NETWORK_MISMATCH: + show_error_response(error, "Descriptor network mismatch"); + break; + case BIPQR_RESPONSE_ERROR_UNSUPPORTED_DESCRIPTOR_FORM: + show_error_response(error, "Descriptor form not taken here"); + break; + case BIPQR_RESPONSE_ERROR_INTERNAL: + show_error_response(error, "Out of memory"); + break; + default: + show_error_response(error, "Descriptor registration failed"); + break; + } +} + +// The address at `path`, the path under the descriptor: the position in its +// tuple when it has several paths, then the index when it is ranged +static bool address_from_entry_path(const registry_entry_t *entry, + const bipqr_path *path, char **out) { + uint32_t features = 0; + if (wally_descriptor_get_features(entry->desc, &features) != WALLY_OK) + return false; + bool multipath = entry->num_paths > 1; + bool ranged = features & WALLY_MS_IS_RANGED; + size_t want = (multipath ? 1 : 0) + (ranged ? 1 : 0); + if (path->len != want) + return false; + for (size_t i = 0; i < want; i++) { + if (bip32_path_is_hardened(path->ptr[i])) + return false; + } + uint32_t multi_index = multipath ? path->ptr[0] : 0; + uint32_t child_num = ranged ? path->ptr[want - 1] : 0; + if (multi_index >= entry->num_paths) + return false; + return wally_descriptor_to_address(entry->desc, 0, multi_index, child_num, 0, + out) == WALLY_OK; +} + +static bool address_to_spk(const char *address, bool is_testnet, + unsigned char *script, size_t script_len, + size_t *written) { + return wally_addr_segwit_to_bytes(address, is_testnet ? "tb" : "bc", 0, + script, script_len, written) == WALLY_OK || + wally_address_to_scriptpubkey(address, + is_testnet + ? WALLY_NETWORK_BITCOIN_TESTNET + : WALLY_NETWORK_BITCOIN_MAINNET, + script, script_len, written) == WALLY_OK; +} + +// 0 when `given` pays the script of `derived` on the wallet network, else the +// error to answer: Kern signs for the other network on another setting and +// never for regtest +static uint8_t address_error(const char *given, const char *derived) { + bool testnet = wallet_is_testnet(); + unsigned char given_script[128]; + unsigned char derived_script[128]; + size_t given_len = 0; + size_t derived_len = 0; + if (!address_to_spk(given, testnet, given_script, sizeof(given_script), + &given_len)) + return address_to_spk(given, !testnet, given_script, sizeof(given_script), + &given_len) || + wally_addr_segwit_to_bytes(given, "bcrt", 0, given_script, + sizeof(given_script), + &given_len) == WALLY_OK + ? BIPQR_RESPONSE_ERROR_NETWORK_MISMATCH + : BIPQR_RESPONSE_ERROR_ADDRESS_MISMATCH; + bool same = address_to_spk(derived, testnet, derived_script, + sizeof(derived_script), &derived_len) && + given_len == derived_len && + memcmp(given_script, derived_script, given_len) == 0; + return same ? 0 : BIPQR_RESPONSE_ERROR_ADDRESS_MISMATCH; +} + +static void verify_address_approve_enable_cb(lv_timer_t *timer) { + (void)timer; + if (verify_address_approve_btn) + lv_obj_clear_state(verify_address_approve_btn, LV_STATE_DISABLED); +} + +static void verify_address_done_cb(lv_event_t *e) { + (void)e; + destroy_verify_address_detail(); + bipqr_response response; + fill_response_header(&response); + response.body.address_uri.uri = pending_verified_uri; + show_response(&response); +} + +static void show_verify_address_detail(void) { + destroy_verify_address_detail(); + + int32_t pad = theme_default_padding(); + int32_t scr_w = theme_screen_width(); + bool landscape = theme_is_landscape(); + int32_t square_size = theme_min_dim() * 55 / 100; + + verify_address_detail = lv_obj_create(lv_screen_active()); + lv_obj_set_size(verify_address_detail, LV_PCT(100), LV_PCT(100)); + theme_apply_screen(verify_address_detail); + lv_obj_set_style_pad_all(verify_address_detail, pad, 0); + lv_obj_set_flex_flow(verify_address_detail, LV_FLEX_FLOW_COLUMN); + lv_obj_set_flex_align(verify_address_detail, LV_FLEX_ALIGN_CENTER, + LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); + lv_obj_set_style_pad_gap(verify_address_detail, pad, 0); + + lv_obj_t *title = + theme_create_label(verify_address_detail, "Verify Address", false); + lv_obj_set_style_text_align(title, LV_TEXT_ALIGN_CENTER, 0); + + lv_obj_t *caption = + theme_create_label(verify_address_detail, pending_verify_caption, true); + lv_obj_set_width(caption, LV_PCT(95)); + lv_label_set_long_mode(caption, LV_LABEL_LONG_WRAP); + lv_obj_set_style_text_align(caption, LV_TEXT_ALIGN_CENTER, 0); + + lv_obj_t *content = lv_obj_create(verify_address_detail); + lv_obj_remove_style_all(content); + lv_obj_set_size(content, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_flow(content, + landscape ? LV_FLEX_FLOW_ROW : LV_FLEX_FLOW_COLUMN); + lv_obj_set_flex_align(content, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, + LV_FLEX_ALIGN_CENTER); + lv_obj_set_style_pad_gap(content, pad, 0); + lv_obj_clear_flag(content, LV_OBJ_FLAG_SCROLLABLE); + + char *upper = qr_bech32_to_upper(pending_verified_address); + const char *qr_payload = upper ? upper : pending_verified_address; + lv_obj_t *qr_container = theme_create_qr_container(content, square_size, 15); + qr_create_optimal(qr_container, square_size - 30, qr_payload); + qr_viewer_attach_fullscreen(qr_container, qr_payload, "Verify Address"); + free(upper); + + lv_obj_t *addr_label = + theme_create_label(content, pending_verified_address, false); + if (landscape) + lv_obj_set_width(addr_label, scr_w - 2 * pad - square_size - pad); + else + lv_obj_set_width(addr_label, LV_PCT(95)); + lv_label_set_long_mode(addr_label, LV_LABEL_LONG_WRAP); + lv_obj_set_style_text_align(addr_label, LV_TEXT_ALIGN_CENTER, 0); + lv_obj_set_style_text_font(addr_label, theme_font_medium(), 0); + + verify_address_approve_btn = lv_btn_create(verify_address_detail); + lv_obj_set_size(verify_address_approve_btn, LV_PCT(60), LV_SIZE_CONTENT); + theme_apply_touch_button(verify_address_approve_btn, true); + lv_obj_add_state(verify_address_approve_btn, LV_STATE_DISABLED); + lv_obj_t *approve_lbl = lv_label_create(verify_address_approve_btn); + lv_label_set_text(approve_lbl, "Done"); + lv_obj_center(approve_lbl); + theme_apply_button_label(approve_lbl, true); + lv_obj_add_event_cb(verify_address_approve_btn, verify_address_done_cb, + LV_EVENT_CLICKED, NULL); + lv_timer_t *enable_timer = + lv_timer_create(verify_address_approve_enable_cb, 500, NULL); + lv_timer_set_repeat_count(enable_timer, 1); +} + +// Shows `address` (malloc()ed, taken over) under `caption` for the user to +// check, then answers with `uri_prefix` and the address +static void show_verified_address(char *address, const char *uri_prefix, + const char *caption) { + size_t uri_len = strlen(uri_prefix) + strlen(address) + 1; + pending_verified_address = address; + snprintf(pending_verify_caption, sizeof(pending_verify_caption), "%s", + caption); + pending_verified_uri = malloc(uri_len); + if (!pending_verified_uri) { + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "Out of memory"); + return; + } + snprintf(pending_verified_uri, uri_len, "%s%s", uri_prefix, address); + debug_log_event("bip_flow verify show_detail"); + show_verify_address_detail(); +} + +// " receive #7", " change #3", " path 2/5": the address +// `path` names under the descriptor of `entry`, as address_from_entry_path +// reads it +static void descriptor_address_caption(const char *alias, + const registry_entry_t *entry, + const bipqr_path *path, char *out, + size_t out_len) { + bool multipath = entry->num_paths > 1; + bool ranged = path->len > (multipath ? 1 : 0); + uint32_t position = multipath ? path->ptr[0] : 0; + uint32_t index = ranged ? path->ptr[path->len - 1] : 0; + const char *branch = NULL; + if (multipath && position == 0) + branch = "receive"; + else if (multipath && position == 1) + branch = "change"; + + if (branch && ranged) + snprintf(out, out_len, "%s %s #%" PRIu32, alias, branch, index); + else if (branch) + snprintf(out, out_len, "%s %s", alias, branch); + else if (multipath && ranged) + snprintf(out, out_len, "%s path %" PRIu32 "/%" PRIu32, alias, position, + index); + else if (multipath) + snprintf(out, out_len, "%s path %" PRIu32, alias, position); + else if (ranged) + snprintf(out, out_len, "%s #%" PRIu32, alias, index); + else + snprintf(out, out_len, "%s", alias); +} + +static void verify_descriptor_address(const bipqr_verify_address *req) { + const registry_entry_t *entry = NULL; + uint8_t error = + resolve_descriptor(req->descriptor_alias, req->descriptor, &entry); + if (error) { + show_descriptor_error(error); + return; + } + char *derived = NULL; + if (!address_from_entry_path(entry, &req->derivation_path, &derived) || + !derived) { + show_error_response(BIPQR_RESPONSE_ERROR_MALFORMED_REQUEST, + "Path does not fit the descriptor"); + return; + } + char *address = strdup(derived); + wally_free_string(derived); + if (!address) { + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "Out of memory"); + return; + } + uint8_t mismatch = req->address ? address_error(req->address, address) : 0; + if (mismatch) { + free(address); + show_error_response(mismatch, + mismatch == BIPQR_RESPONSE_ERROR_NETWORK_MISMATCH + ? "Address is for another network" + : "Address mismatch"); + return; + } + char caption[sizeof(pending_verify_caption)]; + descriptor_address_caption(req->descriptor_alias, entry, + &req->derivation_path, caption, sizeof(caption)); + show_verified_address(address, "bitcoin:", caption); +} + +static void handle_verify(void) { + debug_log_event("bip_flow handle_verify"); + const bipqr_verify_address *req = &ctx.request->body.verify_address; + if (req->proof.ptr) { + show_foreign_proof_error(); + return; + } + verify_descriptor_address(req); +} + +static size_t signed_input_count(const struct wally_psbt *psbt) { + if (!psbt) + return 0; + + size_t count = 0; + for (size_t i = 0; i < psbt->num_inputs; i++) { + size_t n = 0; + if (wally_psbt_get_input_signatures_size(psbt, i, &n) == WALLY_OK && n > 0) + count++; + else if (wally_psbt_get_input_taproot_signature_len(psbt, i, &n) == + WALLY_OK && + n > 0) + count++; + else if (psbt->inputs[i].taproot_leaf_signatures.num_items > 0) + count++; + } + return count; +} + +static void free_signature_list(bipqr_signature *signatures, size_t len) { + if (!signatures) + return; + for (size_t i = 0; i < len; i++) { + switch (signatures[i].kind) { + case BIPQR_SIGNATURE_ECDSA: + free((void *)signatures[i].value.ecdsa.signature.ptr); + break; + case BIPQR_SIGNATURE_TAP_KEY: + free((void *)signatures[i].value.tap_key.signature.ptr); + break; + case BIPQR_SIGNATURE_TAP_SCRIPT: + free((void *)signatures[i].value.tap_script.signature.ptr); + break; + default: + break; + } + } + free(signatures); +} + +static bool copy_signature_bytes(const uint8_t *src, size_t len, + bipqr_bytes *out) { + uint8_t *copy = malloc(len); + if (!copy) + return false; + memcpy(copy, src, len); + out->ptr = copy; + out->len = len; + return true; +} + +static bool append_signature(bipqr_signature **signatures, size_t *len, + size_t *cap, const bipqr_signature *sig) { + if (*len == *cap) { + size_t new_cap = *cap ? *cap * 2 : 4; + bipqr_signature *new_signatures = + realloc(*signatures, new_cap * sizeof(*new_signatures)); + if (!new_signatures) + return false; + *signatures = new_signatures; + *cap = new_cap; + } + (*signatures)[(*len)++] = *sig; + return true; +} + +static bool collect_signatures(const struct wally_psbt *psbt, + bipqr_signature **signatures_out, + size_t *len_out) { + bipqr_signature *signatures = NULL; + size_t len = 0, cap = 0; + + for (size_t input_index = 0; input_index < psbt->num_inputs; input_index++) { + const struct wally_psbt_input *input = &psbt->inputs[input_index]; + for (size_t j = 0; j < input->signatures.num_items; j++) { + const struct wally_map_item *item = &input->signatures.items[j]; + if (item->key_len != BIPQR_PUBLIC_KEY_LEN || !item->key || !item->value) + continue; + bipqr_signature sig = {.input_index = (uint32_t)input_index, + .kind = BIPQR_SIGNATURE_ECDSA}; + memcpy(sig.value.ecdsa.public_key, item->key, BIPQR_PUBLIC_KEY_LEN); + if (!copy_signature_bytes(item->value, item->value_len, + &sig.value.ecdsa.signature) || + !append_signature(&signatures, &len, &cap, &sig)) { + free((void *)sig.value.ecdsa.signature.ptr); + free_signature_list(signatures, len); + return false; + } + } + + size_t tap_key_sig_len = 0; + if (wally_psbt_get_input_taproot_signature_len( + psbt, input_index, &tap_key_sig_len) == WALLY_OK && + tap_key_sig_len > 0) { + uint8_t *tap_key_sig = malloc(tap_key_sig_len); + size_t written = 0; + if (!tap_key_sig || + wally_psbt_get_input_taproot_signature(psbt, input_index, tap_key_sig, + tap_key_sig_len, + &written) != WALLY_OK || + written != tap_key_sig_len) { + free(tap_key_sig); + free_signature_list(signatures, len); + return false; + } + bipqr_signature sig = {.input_index = (uint32_t)input_index, + .kind = BIPQR_SIGNATURE_TAP_KEY}; + sig.value.tap_key.signature.ptr = tap_key_sig; + sig.value.tap_key.signature.len = tap_key_sig_len; + if (!append_signature(&signatures, &len, &cap, &sig)) { + free(tap_key_sig); + free_signature_list(signatures, len); + return false; + } + } + + for (size_t j = 0; j < input->taproot_leaf_signatures.num_items; j++) { + const struct wally_map_item *item = + &input->taproot_leaf_signatures.items[j]; + if (item->key_len != 64 || !item->key || !item->value) + continue; + bipqr_signature sig = {.input_index = (uint32_t)input_index, + .kind = BIPQR_SIGNATURE_TAP_SCRIPT}; + memcpy(sig.value.tap_script.xonly_public_key, item->key, 32); + memcpy(sig.value.tap_script.tap_leaf_hash, item->key + 32, 32); + if (!copy_signature_bytes(item->value, item->value_len, + &sig.value.tap_script.signature) || + !append_signature(&signatures, &len, &cap, &sig)) { + free((void *)sig.value.tap_script.signature.ptr); + free_signature_list(signatures, len); + return false; + } + } + } + + *signatures_out = signatures; + *len_out = len; + return true; +} + +static void answer_signatures(const struct wally_psbt *psbt) { + bipqr_signature *signatures = NULL; + size_t len = 0; + if (!collect_signatures(psbt, &signatures, &len)) { + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, + "Signature extraction failed"); + return; + } + if (len == 0) { + free_signature_list(signatures, len); + show_error_response(BIPQR_RESPONSE_ERROR_NOTHING_TO_SIGN, + "Nothing to sign"); + return; + } + bipqr_response response; + fill_response_header(&response); + response.body.signed_body.kind = BIPQR_SIGN_RESPONSE_SIGNATURES; + response.body.signed_body.value.signatures.ptr = signatures; + response.body.signed_body.value.signatures.len = len; + show_response_with_done(&response, return_from_signing_response); + free_signature_list(signatures, len); +} + +static void answer_psbt(const struct wally_psbt *psbt) { + struct wally_psbt *trimmed = + ctx.request->body.sign.accept_trimmed ? psbt_trim(psbt) : NULL; + const struct wally_psbt *export_psbt = trimmed ? trimmed : psbt; + size_t signed_len = 0; + debug_logf("bip_flow signed_psbt_cb inputs=%u signed_inputs=%u trimmed=%d", + (unsigned)export_psbt->num_inputs, + (unsigned)signed_input_count(export_psbt), trimmed != NULL); + uint8_t *signed_bytes = NULL; + bool encoded = + wally_psbt_get_length(export_psbt, 0, &signed_len) == WALLY_OK && + (signed_bytes = malloc(signed_len)) != NULL && + wally_psbt_to_bytes(export_psbt, 0, signed_bytes, signed_len, + &signed_len) == WALLY_OK; + if (trimmed) + wally_psbt_free(trimmed); + if (!encoded) { + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, "PSBT encode failed"); + return; + } + bipqr_response response; + fill_response_header(&response); + response.body.signed_body.kind = BIPQR_SIGN_RESPONSE_PSBT; + response.body.signed_body.value.psbt.ptr = signed_bytes; + response.body.signed_body.value.psbt.len = signed_len; + show_response_with_done(&response, return_from_signing_response); + free(signed_bytes); +} + +// An unknown WANT_KIND decodes as absent, so it gets the PSBT +static void signed_psbt_cb(struct wally_psbt *psbt, void *user_data) { + (void)user_data; + if (ctx.request->body.sign.want_kind == BIPQR_SIGN_RESPONSE_SIGNATURES) + answer_signatures(psbt); + else + answer_psbt(psbt); +} + +static uint8_t sign_failure_error(scan_psbt_failure_t failure) { + switch (failure) { + case SCAN_PSBT_DECLINED: + return BIPQR_RESPONSE_ERROR_USER_DECLINED; + case SCAN_PSBT_INVALID: + return BIPQR_RESPONSE_ERROR_INVALID_PSBT; + case SCAN_PSBT_NOTHING_TO_SIGN: + return BIPQR_RESPONSE_ERROR_NOTHING_TO_SIGN; + case SCAN_PSBT_REFUSED: + return BIPQR_RESPONSE_ERROR_VENDOR; + case SCAN_PSBT_NETWORK_MISMATCH: + return BIPQR_RESPONSE_ERROR_NETWORK_MISMATCH; + case SCAN_PSBT_INTERNAL: + default: + return BIPQR_RESPONSE_ERROR_INTERNAL; + } +} + +static void sign_failed_cb(scan_psbt_failure_t failure, const char *message, + void *user_data) { + (void)user_data; + bipqr_response response; + fill_error_response(&response, sign_failure_error(failure), message); + show_response_with_done(&response, return_from_signing_response); +} + +// True when the inputs spending from `descriptor` can be signed, else the +// error is answered +static bool sign_descriptor_ok(const bipqr_descriptor *descriptor) { + if (descriptor->proof.ptr) { + show_foreign_proof_error(); + return false; + } + const bipqr_descriptor_body *body = descriptor->body; + const registry_entry_t *entry = NULL; + uint8_t error = resolve_descriptor(descriptor->alias, body, &entry); + if (error) + show_descriptor_error(error); + return !error; +} + +// A PSBT needing a capability Kern does not advertise: a silent payment send +// or MuSig2 keys +static bool refuse_unsupported_psbt(const bipqr_sign *req) { + struct wally_psbt *psbt = NULL; + // Loose, as a silent payment output has no script until a signer derives it + bool unsupported = kern_psbt_from_bytes(req->psbt.ptr, req->psbt.len, + WALLY_PSBT_PARSE_FLAG_LOOSE | + WALLY_PSBT_PARSE_FLAG_COMPLETE, + &psbt) == WALLY_OK && + bip_flow_psbt_is_unsupported(psbt); + wally_psbt_free(psbt); + if (unsupported) + show_error_response(BIPQR_RESPONSE_ERROR_UNSUPPORTED_OPERATION, + "Silent payment sends and MuSig2 are not supported"); + return unsupported; +} + +static void handle_sign(void) { + const bipqr_sign *req = &ctx.request->body.sign; + for (size_t i = 0; i < req->descriptors.len; i++) { + if (!sign_descriptor_ok(&req->descriptors.ptr[i])) + return; + // A script several entries generate is reviewed under the named alias + registry_prefer(req->descriptors.ptr[i].alias); + } + if (refuse_unsupported_psbt(req)) + return; + scan_review_psbt(ctx.parent, req->psbt.ptr, req->psbt.len, ctx.return_cb, + return_from_signing_response, signed_psbt_cb, sign_failed_cb, + NULL); +} + +static void unregister_confirm_cb(bool confirmed, void *user_data) { + (void)user_data; + if (!confirmed) { + show_error_response(BIPQR_RESPONSE_ERROR_USER_DECLINED, "Declined"); + return; + } + const char *alias = ctx.request->body.unregister_descriptor.descriptor_alias; + if (!registry_unregister(alias)) { + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, + "Removing the registration failed"); + return; + } + debug_logf("bip_flow unregistered alias=%s", alias); + bipqr_response response; + fill_response_header(&response); + response.body.unregistered.descriptor_alias = alias; + show_response(&response); +} + +// The user confirms the alias and what it names before it is removed +static void handle_unregister(void) { + const char *alias = ctx.request->body.unregister_descriptor.descriptor_alias; + const registry_entry_t *entry = registry_find_by_id(alias); + if (entry) { + if (!descriptor_loader_confirm_unregister(entry, unregister_confirm_cb)) + show_error_response(BIPQR_RESPONSE_ERROR_INTERNAL, + "Descriptor review failed"); + } else { + show_descriptor_error(BIPQR_RESPONSE_ERROR_UNKNOWN_DESCRIPTOR_ALIAS); + } +} + +static void dispatch_request(void) { + debug_logf("bip_flow dispatch message_type=%d", ctx.request->message_type); + uint8_t unsupported = bip_flow_unsupported_error(ctx.request); + if (unsupported) { + show_error_response( + unsupported, unsupported == BIPQR_RESPONSE_ERROR_UNSUPPORTED_OPERATION + ? "Unsupported request" + : "Descriptor form not taken here"); + return; + } + switch (ctx.request->message_type) { + case BIPQR_MESSAGE_GET_INFO: + handle_get_info(); + break; + case BIPQR_MESSAGE_GET_KEYS: + handle_get_keys(); + break; + case BIPQR_MESSAGE_REGISTER_DESCRIPTOR: + handle_register(); + break; + case BIPQR_MESSAGE_ADDRESS_VERIFICATION: + handle_verify(); + break; + case BIPQR_MESSAGE_SIGNING: + handle_sign(); + break; + case BIPQR_MESSAGE_UNREGISTER_DESCRIPTOR: + handle_unregister(); + break; + default: + show_error_response(BIPQR_RESPONSE_ERROR_UNSUPPORTED_OPERATION, + "Unsupported request"); + break; + } +} + +void bip_flow_start(lv_obj_t *parent, const uint8_t *data, size_t len, + void (*return_cb)(void)) { + debug_log_hex_preview("bip_flow start", data, len, 16); + ctx.parent = parent; + ctx.return_cb = return_cb; + cleanup_request(); + clear_pending_verify(); + if (!bip_flow_read_request_header(data, len, &ctx.header)) { + debug_log_event("bip_flow unreadable_request"); + show_error_response(BIPQR_RESPONSE_ERROR_MALFORMED_REQUEST, + "Unreadable request"); + return; + } + const char *err = NULL; + int32_t rc = bipqr_request_decode(data, len, &ctx.request, &err); + if (rc != BIPQR_OK || !ctx.request) { + debug_logf("bip_flow decode_error rc=%d err=%s", (int)rc, err ? err : ""); + cleanup_request(); + show_error_response(bip_flow_decode_error(&ctx.header, rc), + err ? err : "Malformed request"); + return; + } + debug_log_event("bip_flow decode_ok"); + dispatch_request(); +} diff --git a/main/pages/bip_flow/bip_flow.h b/main/pages/bip_flow/bip_flow.h new file mode 100644 index 00000000..e516bab0 --- /dev/null +++ b/main/pages/bip_flow/bip_flow.h @@ -0,0 +1,154 @@ +#ifndef BIP_FLOW_H +#define BIP_FLOW_H + +#include +#include +#include +#include +#include + +#include "../../core/descriptor_validator.h" +#include +#include + +#define BIP_FLOW_MAGIC "BIPXXX" +#define BIP_FLOW_MAGIC_LEN 6 +#define BIP_FLOW_VERSION_OFFSET BIP_FLOW_MAGIC_LEN +#define BIP_FLOW_MSG_TYPE_OFFSET (BIP_FLOW_VERSION_OFFSET + 1) +#define BIP_FLOW_REQUEST_ID_OFFSET (BIP_FLOW_MSG_TYPE_OFFSET + 1) +#define BIP_FLOW_HEADER_LEN (BIP_FLOW_REQUEST_ID_OFFSET + BIPQR_REQUEST_ID_LEN) + +typedef struct { + uint8_t version; + uint8_t message_type; + uint8_t id[BIPQR_REQUEST_ID_LEN]; +} bip_flow_header_t; + +#define BIP_FLOW_STATUS_BIT 0x40 +#define BIP_FLOW_TYPE_MASK 0x3F + +// Reads the header of a request. It is unreadable without our MAGIC and the +// full REQUEST_ID, with an unknown, reserved or 0x00 TYPE, or with the error +// status: `out` then holds the header of the reply to an unreadable request, +// TYPE 0x00 and REQUEST_ID 0x0000. +static inline bool bip_flow_read_request_header(const uint8_t *data, size_t len, + bip_flow_header_t *out) { + memset(out, 0, sizeof(*out)); + out->message_type = BIPQR_MESSAGE_UNREADABLE_REQUEST; + if (!data || len < BIP_FLOW_HEADER_LEN || + memcmp(data, BIP_FLOW_MAGIC, BIP_FLOW_MAGIC_LEN) != 0) + return false; + uint8_t msg_type = data[BIP_FLOW_MSG_TYPE_OFFSET]; + uint8_t type = msg_type & BIP_FLOW_TYPE_MASK; + if ((msg_type & BIP_FLOW_STATUS_BIT) || type < BIPQR_MESSAGE_GET_INFO || + type > BIPQR_MESSAGE_UNREGISTER_DESCRIPTOR) + return false; + out->version = data[BIP_FLOW_VERSION_OFFSET]; + out->message_type = type; + memcpy(out->id, data + BIP_FLOW_REQUEST_ID_OFFSET, BIPQR_REQUEST_ID_LEN); + return true; +} + +// The error a request that fails to decode with `status` answers with: +// version 0 is reserved, any other one parses as the version Kern knows, where +// a FORM the codec does not know is one Kern cannot take +static inline uint8_t bip_flow_decode_error(const bip_flow_header_t *header, + int32_t status) { + if (header->version == 0) + return BIPQR_RESPONSE_ERROR_UNSUPPORTED_VERSION; + return status == BIPQR_ERR_UNKNOWN_DESCRIPTOR_FORM + ? BIPQR_RESPONSE_ERROR_UNSUPPORTED_DESCRIPTOR_FORM + : BIPQR_RESPONSE_ERROR_MALFORMED_REQUEST; +} + +bool bip_flow_can_handle(const uint8_t *data, size_t len); +// The error a failed registration answers with +static inline uint8_t +bip_flow_register_error(descriptor_validation_result_t result) { + switch (result) { + case VALIDATION_USER_DECLINED: + return BIPQR_RESPONSE_ERROR_USER_DECLINED; + case VALIDATION_NETWORK_MISMATCH: + return BIPQR_RESPONSE_ERROR_NETWORK_MISMATCH; + case VALIDATION_INTERNAL_ERROR: + return BIPQR_RESPONSE_ERROR_INTERNAL; + default: + return BIPQR_RESPONSE_ERROR_DESCRIPTOR_REGISTRATION_FAILED; + } +} +// PSBT_OUT_SP_V0_INFO (BIP-375): the output pays a silent payment address +#define BIP_FLOW_PSBT_OUT_SP_V0_INFO 0x09 + +// The error a descriptor body needing a capability Kern does not advertise +// answers with, 0 when Kern takes it: a silent payment FORM 0x03 gets 0x06, a +// musig() key 0x0F +static inline uint8_t +bip_flow_descriptor_body_error(const bipqr_descriptor_body *body) { + if (!body) + return 0; + if (body->tag == BIPQR_DESCRIPTOR_SP_KEYS) + return BIPQR_RESPONSE_ERROR_UNSUPPORTED_DESCRIPTOR_FORM; + // A wallet policy names its musig() keys in the policy, as musig(@0,@1) + const char *text = body->tag == BIPQR_DESCRIPTOR_BIP380 + ? body->value.bip380 + : body->value.bip388.policy; + return text && strstr(text, "musig(") + ? BIPQR_RESPONSE_ERROR_UNSUPPORTED_OPERATION + : 0; +} + +// The error a request needing a capability Kern does not advertise answers +// with, 0 when Kern takes it: Nonce Preparation, or a descriptor body +// bip_flow_descriptor_body_error refuses +static inline uint8_t bip_flow_unsupported_error(const bipqr_request *request) { + switch (request->message_type) { + case BIPQR_MESSAGE_NONCE_PREPARATION: + return BIPQR_RESPONSE_ERROR_UNSUPPORTED_OPERATION; + case BIPQR_MESSAGE_REGISTER_DESCRIPTOR: + return bip_flow_descriptor_body_error( + request->body.register_descriptor.descriptor); + case BIPQR_MESSAGE_ADDRESS_VERIFICATION: + return bip_flow_descriptor_body_error( + request->body.verify_address.descriptor); + case BIPQR_MESSAGE_SIGNING: + for (size_t i = 0; i < request->body.sign.descriptors.len; i++) { + uint8_t error = bip_flow_descriptor_body_error( + request->body.sign.descriptors.ptr[i].body); + if (error) + return error; + } + return 0; + default: + return 0; + } +} + +static inline bool bip_flow_map_has_key(const struct wally_map *map, + uint8_t key) { + for (size_t i = 0; i < map->num_items; i++) { + if (map->items[i].key_len == 1 && map->items[i].key[0] == key) + return true; + } + return false; +} + +// True for a PSBT needing a capability Kern does not advertise: a silent +// payment output, or the BIP-373 participant keys of a MuSig2 key +static inline bool bip_flow_psbt_is_unsupported(const struct wally_psbt *psbt) { + for (size_t i = 0; i < psbt->num_inputs; i++) { + if (psbt->inputs[i].musig2_pubkeys.num_items) + return true; + } + for (size_t i = 0; i < psbt->num_outputs; i++) { + if (psbt->outputs[i].musig2_pubkeys.num_items || + bip_flow_map_has_key(&psbt->outputs[i].unknowns, + BIP_FLOW_PSBT_OUT_SP_V0_INFO)) + return true; + } + return false; +} + +void bip_flow_start(lv_obj_t *parent, const uint8_t *data, size_t len, + void (*return_cb)(void)); + +#endif /* BIP_FLOW_H */ diff --git a/main/pages/bip_flow/test/Makefile b/main/pages/bip_flow/test/Makefile new file mode 100644 index 00000000..cce992e1 --- /dev/null +++ b/main/pages/bip_flow/test/Makefile @@ -0,0 +1,38 @@ +CC = gcc +CFLAGS = -Wall -Wextra -g + +ROOT = ../../../.. +TARGET_REGISTER = test_bip_flow_register +TARGET_HEADER = test_bip_flow_header +TARGET_BIP388 = test_bip388 +TEST_INCS = -Istubs -I$(ROOT)/main -I$(ROOT)/main/core/test/stubs \ + -I$(ROOT)/components/bipqr/upstream/bipqr-ll/include \ + -I$(ROOT)/components/libwally-core/upstream/include +# kern-bipqr built for the host, shared with the core tests +KERN_BIPQR_DIR = $(ROOT)/main/core/test/kern_bipqr +KERN_BIPQR = $(KERN_BIPQR_DIR)/release/libkern_bipqr.a + +all: $(TARGET_REGISTER) $(TARGET_HEADER) $(TARGET_BIP388) + +$(TARGET_REGISTER): test_bip_flow_register.c ../bip_flow.h + $(CC) $(CFLAGS) $(TEST_INCS) -o $@ test_bip_flow_register.c + +$(TARGET_HEADER): test_bip_flow_header.c ../bip_flow.h $(KERN_BIPQR) + $(CC) $(CFLAGS) $(TEST_INCS) -o $@ test_bip_flow_header.c $(KERN_BIPQR) -lpthread -ldl + +$(TARGET_BIP388): test_bip388.c ../bip388.c ../bip388.h + $(CC) $(CFLAGS) -o $@ test_bip388.c ../bip388.c + +# Always runs: cargo tracks the crate sources and only relinks on a change +$(KERN_BIPQR): + CARGO_TARGET_DIR=$(KERN_BIPQR_DIR) cargo build --release --manifest-path $(ROOT)/components/bipqr/Cargo.toml + +run: $(TARGET_REGISTER) $(TARGET_HEADER) $(TARGET_BIP388) + ./$(TARGET_REGISTER) + ./$(TARGET_HEADER) + ./$(TARGET_BIP388) + +clean: + rm -f $(TARGET_REGISTER) $(TARGET_HEADER) $(TARGET_BIP388) + +.PHONY: all run clean $(KERN_BIPQR) diff --git a/main/pages/bip_flow/test/stubs/lvgl.h b/main/pages/bip_flow/test/stubs/lvgl.h new file mode 100644 index 00000000..2f772d99 --- /dev/null +++ b/main/pages/bip_flow/test/stubs/lvgl.h @@ -0,0 +1,4 @@ +#ifndef LVGL_H +#define LVGL_H +typedef struct _lv_obj_t lv_obj_t; +#endif diff --git a/main/pages/bip_flow/test/test_bip388.c b/main/pages/bip_flow/test/test_bip388.c new file mode 100644 index 00000000..c91c7073 --- /dev/null +++ b/main/pages/bip_flow/test/test_bip388.c @@ -0,0 +1,91 @@ +#include "../bip388.h" + +#include +#include +#include + +static int tests_failed = 0; + +#define TEST(name) printf("Testing: %s... ", name) +#define PASS() printf("PASS\n") +#define FAIL(msg) \ + do { \ + printf("FAIL: %s\n", msg); \ + tests_failed++; \ + } while (0) + +#define KEY_A "[f5acc2fd/48'/1'/0'/2']tpubA" +#define KEY_B "[00000000/48'/1'/0'/2']tpubB" + +static const char *const KEYS[] = {KEY_A, KEY_B}; + +static void expect_descriptor(const char *name, const char *policy, + const char *const *keys, size_t key_count, + const char *expected) { + TEST(name); + char *got = bip388_descriptor_alloc(policy, keys, key_count); + if (!got) + FAIL("no descriptor"); + else if (!bip388_policy_is_valid(policy, keys, key_count)) + FAIL("policy not valid"); + else if (strcmp(got, expected) != 0) + FAIL(got); + else + PASS(); + free(got); +} + +static void expect_refused(const char *name, const char *policy, + const char *const *keys, size_t key_count) { + TEST(name); + char *got = bip388_descriptor_alloc(policy, keys, key_count); + if (got) + FAIL(got); + else if (bip388_policy_is_valid(policy, keys, key_count)) + FAIL("policy valid"); + else + PASS(); + free(got); +} + +static void test_expanded(void) { + expect_descriptor("/** becomes /<0;1>/*", "wpkh(@0/**)", KEYS, 1, + "wpkh(" KEY_A "/<0;1>/*)"); + expect_descriptor("an explicit multipath is kept", "wpkh(@0/<0;1>/*)", KEYS, + 1, "wpkh(" KEY_A "/<0;1>/*)"); + expect_descriptor("a key used twice is written twice", + "wsh(or_d(pk(@0/**),and_v(v:pk(@0/<2;3>/*),older(10))))", + KEYS, 1, + "wsh(or_d(pk(" KEY_A "/<0;1>/*),and_v(v:pk(" KEY_A + "/<2;3>/*),older(10))))"); + expect_descriptor("keys are taken by index", + "wsh(sortedmulti(1,@1/**,@0/**))", KEYS, 2, + "wsh(sortedmulti(1," KEY_B "/<0;1>/*," KEY_A "/<0;1>/*))"); + + const char *const eleven[] = {"k0", "k1", "k2", "k3", "k4", "k5", + "k6", "k7", "k8", "k9", "k10"}; + expect_descriptor("a two digit index", "pk(@10/**)", eleven, 11, + "pk(k10/<0;1>/*)"); +} + +static void test_refused(void) { + expect_refused("an index past the keys is refused", "wpkh(@1/**)", KEYS, 1); + expect_refused("an index far past the keys is refused", + "wpkh(@99999999999999999999/**)", KEYS, 2); + expect_refused("@ without an index is refused", "wpkh(@/**)", KEYS, 1); + expect_refused("a policy without keys is refused", "wpkh(@0/**)", NULL, 0); + const char *const missing[] = {NULL}; + expect_refused("a NULL key is refused", "wpkh(@0/**)", missing, 1); + expect_refused("a NULL policy is refused", NULL, KEYS, 1); +} + +int main(void) { + printf("BIP-388 wallet policy tests\n"); + printf("===========================\n\n"); + + test_expanded(); + test_refused(); + + printf("\nResults: %d failed\n", tests_failed); + return tests_failed == 0 ? 0 : 1; +} diff --git a/main/pages/bip_flow/test/test_bip_flow_header.c b/main/pages/bip_flow/test/test_bip_flow_header.c new file mode 100644 index 00000000..33d7f868 --- /dev/null +++ b/main/pages/bip_flow/test/test_bip_flow_header.c @@ -0,0 +1,339 @@ +#include "../bip_flow.h" + +#include + +static int tests_failed = 0; + +#define TEST(name) printf("Testing: %s... ", name) +#define PASS() printf("PASS\n") +#define FAIL(msg) \ + do { \ + printf("FAIL: %s\n", msg); \ + tests_failed++; \ + } while (0) + +/* ENCODING.md's get_keys_request_one_path vector: version 1, Get Keys, + * request id 0x0001 */ +static const uint8_t GET_KEYS_REQUEST[] = { + 0x42, 0x49, 0x50, 0x58, 0x58, 0x58, 0x01, 0x02, 0x00, 0x01, + 0x01, 0x04, 0x80, 0x00, 0x00, 0x30, 0x80, 0x00, 0x00, 0x00, + 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x02, 0x00}; + +static void expect_rejected(const char *name, size_t offset, uint8_t value, + size_t len) { + uint8_t message[sizeof(GET_KEYS_REQUEST)]; + bip_flow_header_t header; + memcpy(message, GET_KEYS_REQUEST, sizeof(message)); + message[offset] = value; + TEST(name); + if (bip_flow_read_request_header(message, len, &header)) + FAIL("header accepted"); + else if (header.message_type != 0x00 || header.id[0] != 0x00 || + header.id[1] != 0x00) + FAIL("reply header is not TYPE 0x00 and REQUEST_ID 0x0000"); + else + PASS(); +} + +static void test_read_header(void) { + bip_flow_header_t header; + TEST("a Get Keys request header is read"); + if (bip_flow_read_request_header(GET_KEYS_REQUEST, sizeof(GET_KEYS_REQUEST), + &header) && + header.version == 0x01 && header.message_type == 0x02 && + header.id[0] == 0x00 && header.id[1] == 0x01) + PASS(); + else + FAIL("header fields differ"); + + uint8_t response[sizeof(GET_KEYS_REQUEST)]; + memcpy(response, GET_KEYS_REQUEST, sizeof(response)); + response[7] = 0x82; + TEST("a response header is read with TYPE 0x02 and id 0x0001"); + if (bip_flow_read_request_header(response, sizeof(response), &header) && + header.message_type == 0x02 && header.id[0] == 0x00 && + header.id[1] == 0x01) + PASS(); + else + FAIL("header fields differ"); + + expect_rejected("a bad MAGIC is not a request", 3, 0x31, + sizeof(GET_KEYS_REQUEST)); + expect_rejected("the error status is not a request", 7, 0x42, + sizeof(GET_KEYS_REQUEST)); + expect_rejected("the reserved type 0x00 is not a request", 7, 0x00, + sizeof(GET_KEYS_REQUEST)); + expect_rejected("the unknown type 0x08 is not a request", 7, 0x08, + sizeof(GET_KEYS_REQUEST)); + expect_rejected("a message without its request id is not a request", 7, 0x02, + 9); +} + +/* bipqr test vectors (efccc5b): unregister_descriptor_request and + * unregister_descriptor_response for the alias "main", request id 0x0001 */ +static const uint8_t UNREGISTER_REQUEST[] = {0x42, 0x49, 0x50, 0x58, 0x58, + 0x58, 0x01, 0x07, 0x00, 0x01, + 0x04, 0x6d, 0x61, 0x69, 0x6e}; +static const uint8_t UNREGISTER_RESPONSE[] = {0x42, 0x49, 0x50, 0x58, 0x58, + 0x58, 0x01, 0x87, 0x00, 0x01, + 0x04, 0x6d, 0x61, 0x69, 0x6e}; + +static void test_unregister_request(void) { + bip_flow_header_t header; + const bipqr_request *request = NULL; + TEST("an Unregister Descriptor request header is read"); + if (bip_flow_read_request_header(UNREGISTER_REQUEST, + sizeof(UNREGISTER_REQUEST), &header) && + header.version == 0x01 && header.message_type == 0x07 && + header.id[0] == 0x00 && header.id[1] == 0x01) + PASS(); + else + FAIL("header fields differ"); + + TEST("an Unregister Descriptor request decodes to its alias"); + if (bipqr_request_decode(UNREGISTER_REQUEST, sizeof(UNREGISTER_REQUEST), + &request, NULL) == BIPQR_OK && + request->message_type == 0x07 && request->id[0] == 0x00 && + request->id[1] == 0x01 && + strcmp(request->body.unregister_descriptor.descriptor_alias, "main") == 0) + PASS(); + else + FAIL("request differs"); + bipqr_request_free(request); +} + +/* A request whose header reads but whose body does not decode, as + * bip_flow_start answers it */ +static void expect_malformed(const char *name, const uint8_t *message, + size_t len) { + bip_flow_header_t header; + const bipqr_request *request = NULL; + TEST(name); + int32_t status = bip_flow_read_request_header(message, len, &header) + ? bipqr_request_decode(message, len, &request, NULL) + : BIPQR_OK; + if (status != BIPQR_OK && !request && + bip_flow_decode_error(&header, status) == 0x03) + PASS(); + else + FAIL("not answered with malformed request"); + bipqr_request_free(request); +} + +static void test_unregister_malformed(void) { + uint8_t long_alias[BIP_FLOW_HEADER_LEN + 1 + 33]; + memcpy(long_alias, UNREGISTER_REQUEST, BIP_FLOW_HEADER_LEN); + long_alias[BIP_FLOW_HEADER_LEN] = 33; + memset(long_alias + BIP_FLOW_HEADER_LEN + 1, 'a', 33); + expect_malformed("an Unregister Descriptor request without its alias " + "answers malformed request", + UNREGISTER_REQUEST, BIP_FLOW_HEADER_LEN); + expect_malformed("an Unregister Descriptor request with a 33-byte alias " + "answers malformed request", + long_alias, sizeof(long_alias)); +} + +static void test_unregister_response(void) { + bipqr_response response; + bipqr_buf encoded = {0}; + memset(&response, 0, sizeof(response)); + response.id[1] = 0x01; + response.message_type = BIPQR_MESSAGE_UNREGISTER_DESCRIPTOR; + response.body.unregistered.descriptor_alias = "main"; + TEST("the Unregister Descriptor ok response echoes the alias"); + if (bipqr_response_encode(&response, &encoded, NULL) == BIPQR_OK && + encoded.len == sizeof(UNREGISTER_RESPONSE) && + memcmp(encoded.ptr, UNREGISTER_RESPONSE, encoded.len) == 0) + PASS(); + else + FAIL("encoding differs from the vector"); + bipqr_buf_free(encoded); +} + +static void expect_decode_error(const char *name, uint8_t version, + int32_t status, uint8_t expected) { + bip_flow_header_t header = {.version = version}; + TEST(name); + if (bip_flow_decode_error(&header, status) == expected) + PASS(); + else + FAIL("unexpected error code"); +} + +static void test_decode_error(void) { + expect_decode_error("version 0 answers unsupported protocol version", 0x00, + BIPQR_ERR_TRUNCATED, 0x02); + expect_decode_error("version 1 answers malformed request", 0x01, + BIPQR_ERR_TRUNCATED, 0x03); + expect_decode_error("a newer version answers malformed request", 0x02, + BIPQR_ERR_TRUNCATED, 0x03); + expect_decode_error("an unknown FORM answers unsupported descriptor form", + 0x01, BIPQR_ERR_UNKNOWN_DESCRIPTOR_FORM, 0x06); + expect_decode_error("an unknown FORM of version 0 answers unsupported " + "protocol version", + 0x00, BIPQR_ERR_UNKNOWN_DESCRIPTOR_FORM, 0x02); +} + +/* bipqr test vectors (d7363e0) of requests carrying a descriptor body */ +static const uint8_t REGISTER_BIP380_REQUEST[] = { + 0x42, 0x49, 0x50, 0x58, 0x58, 0x58, 0x01, 0x03, 0x00, 0x01, 0x04, + 0x6d, 0x61, 0x69, 0x6e, 0x01, 0x01, 0x22, 0x77, 0x70, 0x6b, 0x68, + 0x28, 0x5b, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x2f, + 0x38, 0x34, 0x68, 0x2f, 0x31, 0x68, 0x2f, 0x30, 0x68, 0x5d, 0x78, + 0x70, 0x75, 0x62, 0x2f, 0x30, 0x2f, 0x2a, 0x29}; +static const uint8_t REGISTER_SP_KEYS_REQUEST[] = { + 0x42, 0x49, 0x50, 0x58, 0x58, 0x58, 0x01, 0x03, 0x00, 0x01, 0x04, + 0x6d, 0x61, 0x69, 0x6e, 0x01, 0x03, 0x73, 0xc5, 0xda, 0x0a, 0x05, + 0x80, 0x00, 0x01, 0x60, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, + 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x05, + 0x80, 0x00, 0x01, 0x60, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, + 0x00, 0x80, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}; +static const uint8_t VERIFY_SP_KEYS_REQUEST[] = { + 0x42, 0x49, 0x50, 0x58, 0x58, 0x58, 0x01, 0x04, 0x00, 0x01, 0x04, + 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x01, 0x07, 0x73, 0x70, 0x31, 0x71, + 0x78, 0x79, 0x7a, 0x01, 0x03, 0x73, 0xc5, 0xda, 0x0a, 0x05, 0x80, + 0x00, 0x01, 0x60, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x00, + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x05, 0x80, + 0x00, 0x01, 0x60, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x00, + 0x80, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +static const uint8_t NONCE_PREPARATION_REQUEST[] = { + 0x42, 0x49, 0x50, 0x58, 0x58, 0x58, 0x01, 0x06, 0x00, 0x01, 0x01, + 0x51, 0x51, 0x51, 0x51, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x05, + 0x80, 0x00, 0x00, 0x56, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01}; + +/* A Register Descriptor request for the alias "main" with a FORM 0x01 + * descriptor, laid out as REGISTER_BIP380_REQUEST */ +static size_t register_bip380_request(const char *descriptor, uint8_t *out) { + size_t len = strlen(descriptor); + memcpy(out, REGISTER_BIP380_REQUEST, 17); + out[17] = (uint8_t)len; + memcpy(out + 18, descriptor, len); + return 18 + len; +} + +/* A Register Descriptor request for the alias "main" with a FORM 0x02 wallet + * policy of two keys */ +static size_t register_bip388_request(const char *key0, const char *key1, + const char *policy, uint8_t *out) { + const char *strings[] = {key0, key1, policy}; + size_t off = 16; + memcpy(out, REGISTER_BIP380_REQUEST, off); + out[off++] = 0x02; + out[off++] = 2; + for (size_t i = 0; i < 3; i++) { + size_t len = strlen(strings[i]); + out[off++] = (uint8_t)len; + memcpy(out + off, strings[i], len); + off += len; + } + return off; +} + +static void expect_unsupported(const char *name, const uint8_t *message, + size_t len, uint8_t expected) { + const bipqr_request *request = NULL; + TEST(name); + if (bipqr_request_decode(message, len, &request, NULL) != BIPQR_OK) + FAIL("request does not decode"); + else if (bip_flow_unsupported_error(request) != expected) + FAIL("unexpected error code"); + else + PASS(); + bipqr_request_free(request); +} + +static void test_unsupported_requests(void) { + uint8_t message[160]; + expect_unsupported("a FORM 0x01 descriptor is taken", REGISTER_BIP380_REQUEST, + sizeof(REGISTER_BIP380_REQUEST), 0x00); + expect_unsupported("registering FORM 0x03 silent payment keys answers " + "unsupported descriptor form", + REGISTER_SP_KEYS_REQUEST, sizeof(REGISTER_SP_KEYS_REQUEST), + 0x06); + expect_unsupported("verifying a FORM 0x03 silent payment address answers " + "unsupported descriptor form", + VERIFY_SP_KEYS_REQUEST, sizeof(VERIFY_SP_KEYS_REQUEST), + 0x06); + expect_unsupported("Nonce Preparation answers unsupported operation", + NONCE_PREPARATION_REQUEST, + sizeof(NONCE_PREPARATION_REQUEST), 0x0F); + expect_unsupported( + "a musig() key in a FORM 0x01 descriptor answers unsupported operation", + message, + register_bip380_request("tr(musig([00000000/86h/1h/0h]xpub," + "[11111111/86h/1h/0h]xpub)/<0;1>/*)", + message), + 0x0F); + expect_unsupported( + "a musig() key in a FORM 0x02 wallet policy answers unsupported " + "operation", + message, + register_bip388_request("[00000000/86h/1h/0h]xpub", + "[11111111/86h/1h/0h]xpub", "tr(musig(@0,@1)/**)", + message), + 0x0F); + expect_unsupported( + "a FORM 0x02 wallet policy without musig() is taken", message, + register_bip388_request("[00000000/48h/1h/0h/2h]xpub", + "[11111111/48h/1h/0h/2h]xpub", + "wsh(sortedmulti(2,@0/**,@1/**))", message), + 0x00); +} + +static void expect_psbt(const char *name, const struct wally_psbt *psbt, + bool unsupported) { + TEST(name); + if (bip_flow_psbt_is_unsupported(psbt) == unsupported) + PASS(); + else + FAIL(unsupported ? "PSBT taken" : "PSBT refused"); +} + +static void test_unsupported_psbts(void) { + struct wally_psbt_input input; + struct wally_psbt_output output; + struct wally_psbt psbt; + unsigned char sp_info_key = BIP_FLOW_PSBT_OUT_SP_V0_INFO; + unsigned char other_key = 0x08; + struct wally_map_item item = {.key = &other_key, .key_len = 1}; + memset(&input, 0, sizeof(input)); + memset(&output, 0, sizeof(output)); + memset(&psbt, 0, sizeof(psbt)); + psbt.inputs = &input; + psbt.num_inputs = 1; + psbt.outputs = &output; + psbt.num_outputs = 1; + + output.unknowns.items = &item; + output.unknowns.num_items = 1; + expect_psbt("a PSBT with another unknown output field is taken", &psbt, + false); + item.key = &sp_info_key; + expect_psbt("a silent payment send answers unsupported operation", &psbt, + true); + output.unknowns.num_items = 0; + input.musig2_pubkeys.num_items = 1; + expect_psbt("an input MuSig2 key answers unsupported operation", &psbt, true); + input.musig2_pubkeys.num_items = 0; + output.musig2_pubkeys.num_items = 1; + expect_psbt("an output MuSig2 key answers unsupported operation", &psbt, + true); +} + +int main(void) { + printf("BIP flow request header tests\n"); + printf("=============================\n\n"); + + test_read_header(); + test_decode_error(); + test_unregister_request(); + test_unregister_malformed(); + test_unregister_response(); + test_unsupported_requests(); + test_unsupported_psbts(); + + printf("\nResults: %d failed\n", tests_failed); + return tests_failed == 0 ? 0 : 1; +} diff --git a/main/pages/bip_flow/test/test_bip_flow_register.c b/main/pages/bip_flow/test/test_bip_flow_register.c new file mode 100644 index 00000000..9ae630dd --- /dev/null +++ b/main/pages/bip_flow/test/test_bip_flow_register.c @@ -0,0 +1,46 @@ +#include "../bip_flow.h" + +#include + +static int tests_failed = 0; + +#define TEST(name) printf("Testing: %s... ", name) +#define PASS() printf("PASS\n") +#define FAIL(msg) \ + do { \ + printf("FAIL: %s\n", msg); \ + tests_failed++; \ + } while (0) + +static void expect_error(descriptor_validation_result_t result, + uint8_t expected, const char *name) { + TEST(name); + if (bip_flow_register_error(result) == expected) { + PASS(); + } else { + FAIL("unexpected error code"); + } +} + +int main(void) { + printf("BIP flow register error tests\n"); + printf("=============================\n\n"); + + expect_error(VALIDATION_USER_DECLINED, 0x01, + "declined registration answers user declined"); + expect_error(VALIDATION_PARSE_ERROR, 0x05, + "parse error answers registration failed"); + expect_error(VALIDATION_FINGERPRINT_NOT_FOUND, 0x05, + "fingerprint error answers registration failed"); + expect_error(VALIDATION_DUPLICATE, 0x05, + "duplicate descriptor answers registration failed"); + expect_error(VALIDATION_XPUB_MISMATCH, 0x05, + "xpub mismatch answers registration failed"); + expect_error(VALIDATION_NETWORK_MISMATCH, 0x10, + "network mismatch answers network mismatch"); + expect_error(VALIDATION_INTERNAL_ERROR, 0x0B, + "internal error answers internal device error"); + + printf("\nResults: %d failed\n", tests_failed); + return tests_failed == 0 ? 0 : 1; +} diff --git a/main/pages/home/home.c b/main/pages/home/home.c index 4f480693..3cfd72d7 100644 --- a/main/pages/home/home.c +++ b/main/pages/home/home.c @@ -1,4 +1,5 @@ #include "home.h" +#include "../../core/debug_log.h" #include "../../core/key.h" #include "../../core/wallet.h" #include "../../ui/assets/icons.h" @@ -127,21 +128,23 @@ static void return_from_addresses_cb(void) { } static void return_from_scan_cb(void) { + debug_log_event("home return_from_scan_cb enter"); scan_page_destroy(); - if (key_snapshot_changed() || wallet_settings_were_applied()) { - home_page_destroy(); - home_page_create(lv_screen_active()); - } + debug_log_event("home return_from_scan_cb recreate_home"); + home_page_destroy(); + home_page_create(lv_screen_active()); home_page_show(); + debug_log_event("home return_from_scan_cb show_home"); } static void return_from_load_cb(void) { + debug_log_event("home return_from_load_cb enter"); load_page_destroy(); - if (key_snapshot_changed() || wallet_settings_were_applied()) { - home_page_destroy(); - home_page_create(lv_screen_active()); - } + debug_log_event("home return_from_load_cb recreate_home"); + home_page_destroy(); + home_page_create(lv_screen_active()); home_page_show(); + debug_log_event("home return_from_load_cb show_home"); } static void return_from_advanced_tools_cb(void) { diff --git a/main/pages/load_descriptor_storage.c b/main/pages/load_descriptor_storage.c index 7ceabd14..65409e34 100644 --- a/main/pages/load_descriptor_storage.c +++ b/main/pages/load_descriptor_storage.c @@ -128,7 +128,7 @@ static void deferred_bip138_cb(lv_timer_t *timer) { (void)timer; char *descriptor_str = NULL; bool opened = bip138_backup_decrypt_any(pending_bip138, pending_bip138_len, - &descriptor_str, NULL); + &descriptor_str, NULL, NULL); free(pending_bip138); pending_bip138 = NULL; pending_bip138_len = 0; @@ -231,21 +231,15 @@ static void sd_desc_on_file_selected(const char *full_path, const char *dir, * Descriptors, so the flash list leaves it out. Other BIP138 files stay * listed: they belong to another key or lack this device's approval mark. */ static bool is_registered_backup(storage_location_t loc, const char *filename) { - if (loc != STORAGE_FLASH || - storage_descriptor_format(filename) != STORAGE_DESCRIPTOR_BIP138) + if (loc != STORAGE_FLASH) return false; - const char *start = filename; - size_t prefix_len = strlen(STORAGE_DESCRIPTOR_PREFIX); - if (strncmp(start, STORAGE_DESCRIPTOR_PREFIX, prefix_len) == 0) - start += prefix_len; - size_t id_len = strlen(start) - strlen(STORAGE_DESCRIPTOR_EXT_BIP138); - char id[REGISTRY_ID_MAX_LEN]; - if (id_len >= sizeof(id)) - id_len = sizeof(id) - 1; - memcpy(id, start, id_len); - id[id_len] = '\0'; - const registry_entry_t *entry = registry_find_by_id(id); - return entry && entry->persisted && entry->loc == STORAGE_FLASH; + for (size_t i = 0; i < registry_count(); i++) { + const registry_entry_t *entry = registry_get(i); + if (entry->persisted && entry->loc == STORAGE_FLASH && + strcmp(entry->filename, filename) == 0) + return true; + } + return false; } static esp_err_t list_loadable_descriptors(storage_location_t loc, diff --git a/main/pages/login/login_scan.c b/main/pages/login/login_scan.c index 0d9333fc..61f6981c 100644 --- a/main/pages/login/login_scan.c +++ b/main/pages/login/login_scan.c @@ -10,11 +10,13 @@ #include "../../ui/dialog.h" #include "../../utils/secure_mem.h" #include "../../utils/session_cleanup.h" +#include "../bip_flow/bip_flow.h" #include "../home/addresses.h" #include "../home/home.h" #include "../shared/descriptor_loader.h" #include "../shared/kef_decrypt_page.h" #include "../shared/key_confirmation.h" +#include #include #include #include @@ -93,6 +95,36 @@ static void show_psbt_needs_key(void) { unidentified_dismissed_cb, NULL, DIALOG_STYLE_OVERLAY); } +// The request's message type, 0 when it does not decode +static uint8_t bip_request_type(const uint8_t *content, size_t len) { + const bipqr_request *request = NULL; + const char *err = NULL; + uint8_t type = 0; + if (bipqr_request_decode(content, len, &request, &err) == BIPQR_OK && request) + type = request->message_type; + if (request) + bipqr_request_free(request); + return type; +} + +static void show_bip_request_needs_key(uint8_t type) { + dialog_show_info(type == BIPQR_MESSAGE_GET_KEYS ? "Key request detected" + : "Wallet request detected", + "Load a seed first to export xpubs or respond to wallet " + "requests.", + unidentified_dismissed_cb, NULL, DIALOG_STYLE_OVERLAY); +} + +// Get Info and a request that does not decode are answered without a seed; +// every other request needs one +static void handle_bip_request(const uint8_t *content, size_t len) { + uint8_t type = bip_request_type(content, len); + if (type == 0 || type == BIPQR_MESSAGE_GET_INFO) + bip_flow_start(lv_screen_active(), content, len, finish_to_login); + else + show_bip_request_needs_key(type); +} + static bool is_psbt_content(const char *content, size_t len) { if (!content) return false; @@ -166,6 +198,7 @@ static void on_scan_done(void) { bool psbt_scanned = (has_ur && ur_type && strcmp(ur_type, "crypto-psbt") == 0) || is_psbt_content(content, len); + bool bip_request_scanned = bip_flow_can_handle((const uint8_t *)content, len); char *desc_candidate = descriptor_extract_from_scanner(); qr_scanner_page_hide(); @@ -180,6 +213,12 @@ static void on_scan_done(void) { return; } + if (bip_request_scanned) { + free(desc_candidate); + handle_bip_request((const uint8_t *)content, len); + return; + } + if (!content && !desc_candidate) { finish_to_login(); return; diff --git a/main/pages/scan/psbt_sign_policy.c b/main/pages/scan/psbt_sign_policy.c index 9b5f1c2f..c022446b 100644 --- a/main/pages/scan/psbt_sign_policy.c +++ b/main/pages/scan/psbt_sign_policy.c @@ -91,11 +91,26 @@ static void format_external_inputs(const psbt_gate_report_t *report, char *body, report->external_count == 1 ? "is" : "are"); } +// What a scan_review_psbt() caller is told of the gate that fired +static scan_psbt_failure_t refusal_of(psbt_gate_t gate) { + switch (gate) { + case PSBT_GATE_NOTHING_SIGNABLE: + return SCAN_PSBT_NOTHING_TO_SIGN; + case PSBT_GATE_EXPECTED_OWNED: + case PSBT_GATE_PERMISSIVE: + case PSBT_GATE_PARTIAL: + return SCAN_PSBT_REFUSED; + default: + return SCAN_PSBT_INVALID; + } +} + bool psbt_sign_policy_allows_review(struct wally_psbt *psbt, const input_ownership_t *inputs, const output_ownership_t *outputs, dialog_callback_t dismissed_cb, - void (*load_descriptor_cb)(void)) { + void (*load_descriptor_cb)(void), + scan_psbt_failure_t *refusal_out) { psbt_gate_settings_t settings = { .expected_owned = settings_get_expected_owned_signing(), .permissive = settings_get_permissive_signing(), @@ -103,6 +118,7 @@ bool psbt_sign_policy_allows_review(struct wally_psbt *psbt, }; psbt_gate_report_t report; psbt_gate_t gate = psbt_gate_check(psbt, inputs, outputs, &settings, &report); + *refusal_out = refusal_of(gate); char body[384]; switch (gate) { diff --git a/main/pages/scan/psbt_sign_policy.h b/main/pages/scan/psbt_sign_policy.h index 7286a075..79f2c753 100644 --- a/main/pages/scan/psbt_sign_policy.h +++ b/main/pages/scan/psbt_sign_policy.h @@ -3,17 +3,20 @@ #include "../../core/psbt.h" #include "../../ui/dialog.h" +#include "scan.h" #include /* `inputs` and `outputs` hold the PSBT's classification, one entry per input * and per output, shared with the review screen. * load_descriptor_cb, when non-NULL, turns the expected-owned rejection into a * confirm offering to load a wallet descriptor on the fly; declining falls - * back to the plain rejection dialog. NULL keeps the old behavior. */ + * back to the plain rejection dialog. NULL keeps the old behavior. On a + * rejection *refusal_out says why. */ bool psbt_sign_policy_allows_review(struct wally_psbt *psbt, const input_ownership_t *inputs, const output_ownership_t *outputs, dialog_callback_t dismissed_cb, - void (*load_descriptor_cb)(void)); + void (*load_descriptor_cb)(void), + scan_psbt_failure_t *refusal_out); #endif diff --git a/main/pages/scan/scan.c b/main/pages/scan/scan.c index bcc9f100..92e00326 100644 --- a/main/pages/scan/scan.c +++ b/main/pages/scan/scan.c @@ -25,6 +25,7 @@ #include "../../utils/secure_mem.h" #include "../../utils/session_cleanup.h" #include "../../utils/text_file.h" +#include "../bip_flow/bip_flow.h" #include "../load_descriptor_storage.h" #include "../shared/address_checker.h" #include "../shared/descriptor_loader.h" @@ -124,6 +125,14 @@ static void finish_dispatch(char *qr_content, size_t qr_content_len, bool parse_success, int detected_format) { scan_ctx.is_message_sign = false; + if (!parse_success && qr_content && + bip_flow_can_handle((const uint8_t *)qr_content, qr_content_len)) { + bip_flow_start(lv_screen_active(), (const uint8_t *)qr_content, + qr_content_len, scan_ctx.return_cb); + free(qr_content); + return; + } + // Layer 2: plaintext/binary heuristics — try each parser in priority order if (!parse_success && qr_content) { // 1. Message @@ -216,8 +225,8 @@ static void finish_dispatch(char *qr_content, size_t qr_content_len, if (bip322_detect(scan_ctx.psbt)) { if (!bip322_parse(scan_ctx.psbt, scan_ctx.is_testnet, &scan_ctx.bip322)) { - dialog_show_error_timeout("Invalid BIP322 message request", - scan_ctx.return_cb, 0); + scan_psbt_fail(SCAN_PSBT_INVALID, "Invalid BIP322 message request", + scan_ctx.return_cb, 0); return; } scan_ctx.is_bip322 = true; @@ -228,10 +237,26 @@ static void finish_dispatch(char *qr_content, size_t qr_content_len, scan_psbt_resume_review(true); } } else { - dialog_show_error_timeout("Unrecognized format", scan_ctx.return_cb, 0); + scan_psbt_fail(SCAN_PSBT_INVALID, "Unrecognized format", scan_ctx.return_cb, + 0); } } +void scan_psbt_fail(scan_psbt_failure_t failure, const char *message, + void (*local_cb)(void), uint32_t timeout_ms) { + scan_psbt_failed_cb_t cb = scan_ctx.psbt_failed_cb; + if (!cb) { + dialog_show_error_timeout(message, local_cb, timeout_ms); + return; + } + void *user_data = scan_ctx.psbt_user_data; + scan_ctx.psbt_signed_cb = NULL; + scan_ctx.psbt_failed_cb = NULL; + scan_ctx.psbt_user_data = NULL; + scan_page_hide(); + cb(failure, message, user_data); +} + // Camera teardown plus payload parsing — for large PSBTs this can take over a // second, so it runs behind the progress dialog from a one-shot timer. static void process_scan_result(void) { @@ -300,6 +325,15 @@ static void process_scan_result(void) { char bbqr_file_type = qr_scanner_get_bbqr_file_type(); qr_content = qr_scanner_get_completed_content_with_len(&qr_content_len); if (qr_content && qr_content_len > 0) { + if (bbqr_file_type == 'B' && + bip_flow_can_handle((const uint8_t *)qr_content, qr_content_len)) { + qr_scanner_page_hide(); + qr_scanner_page_destroy(); + bip_flow_start(lv_screen_active(), (const uint8_t *)qr_content, + qr_content_len, scan_ctx.return_cb); + free(qr_content); + return; + } scan_psbt_cleanup(); parse_success = psbt_parse_payload((const uint8_t *)qr_content, qr_content_len, &scan_ctx.psbt); @@ -388,7 +422,7 @@ static void deferred_bip138_cb(lv_timer_t *timer) { (void)timer; char *descriptor = NULL; bool opened = bip138_backup_decrypt_any(pending_bip138, pending_bip138_len, - &descriptor, NULL); + &descriptor, NULL, NULL); free(pending_bip138); pending_bip138 = NULL; pending_bip138_len = 0; @@ -426,6 +460,9 @@ void scan_load_content(lv_obj_t *parent, const uint8_t *data, size_t len, reset_export_context(save_dir, source_name); scan_ctx.return_cb = return_cb; scan_ctx.complete_cb = complete_cb; + scan_ctx.psbt_signed_cb = NULL; + scan_ctx.psbt_failed_cb = NULL; + scan_ctx.psbt_user_data = NULL; scan_ctx.screen = theme_create_page_container(parent); // A file may hold a serialized binary PSBT — try that first (mirroring the @@ -452,6 +489,27 @@ void scan_load_content(lv_obj_t *parent, const uint8_t *data, size_t len, FORMAT_NONE); } +void scan_review_psbt(lv_obj_t *parent, const uint8_t *data, size_t len, + void (*return_cb)(void), void (*complete_cb)(void), + scan_psbt_signed_cb_t signed_cb, + scan_psbt_failed_cb_t failed_cb, void *user_data) { + session_cleanup_register(scan_page_destroy); + if (!parent || !data || len == 0) + return; + + reset_export_context(NULL, NULL); + scan_ctx.return_cb = return_cb; + scan_ctx.complete_cb = complete_cb; + scan_ctx.psbt_signed_cb = signed_cb; + scan_ctx.psbt_failed_cb = failed_cb; + scan_ctx.psbt_user_data = user_data; + scan_ctx.screen = theme_create_page_container(parent); + + scan_psbt_cleanup(); + bool parsed = psbt_parse_payload(data, len, &scan_ctx.psbt); + finish_dispatch(NULL, len, parsed, FORMAT_NONE); +} + void scan_page_create(lv_obj_t *parent, void (*return_cb)(void)) { session_cleanup_register(scan_page_destroy); if (!parent || !key_is_loaded()) { @@ -460,6 +518,9 @@ void scan_page_create(lv_obj_t *parent, void (*return_cb)(void)) { scan_ctx.return_cb = return_cb; scan_ctx.complete_cb = NULL; + scan_ctx.psbt_signed_cb = NULL; + scan_ctx.psbt_failed_cb = NULL; + scan_ctx.psbt_user_data = NULL; reset_export_context(NULL, NULL); scan_ctx.screen = theme_create_page_container(parent); @@ -510,4 +571,7 @@ void scan_page_destroy(void) { scan_ctx.return_cb = NULL; scan_ctx.complete_cb = NULL; + scan_ctx.psbt_signed_cb = NULL; + scan_ctx.psbt_failed_cb = NULL; + scan_ctx.psbt_user_data = NULL; } diff --git a/main/pages/scan/scan.h b/main/pages/scan/scan.h index 7580c098..6d429cb0 100644 --- a/main/pages/scan/scan.h +++ b/main/pages/scan/scan.h @@ -2,6 +2,26 @@ #define SCAN_H #include +#include +#include + +struct wally_psbt; + +typedef void (*scan_psbt_signed_cb_t)(struct wally_psbt *signed_psbt, + void *user_data); + +// Why a PSBT handed to scan_review_psbt() was not signed +typedef enum { + SCAN_PSBT_DECLINED, // the user backed out of the review + SCAN_PSBT_INVALID, // unparsable, inconsistent or unsafe to sign + SCAN_PSBT_NOTHING_TO_SIGN, // no input this wallet can sign + SCAN_PSBT_REFUSED, // a signing setting or a device limit refuses it + SCAN_PSBT_NETWORK_MISMATCH, // the PSBT is for another network + SCAN_PSBT_INTERNAL, // the device failed +} scan_psbt_failure_t; + +typedef void (*scan_psbt_failed_cb_t)(scan_psbt_failure_t failure, + const char *message, void *user_data); /** * Create the scan page — universal QR content detection @@ -36,6 +56,17 @@ void scan_load_content(lv_obj_t *parent, const uint8_t *data, size_t len, const char *save_dir, const char *source_name, void (*return_cb)(void), void (*complete_cb)(void)); +/** + * Review and sign a binary PSBT using the normal scan/sign review flow. On + * successful signing, signed_cb is called with the still-owned signed PSBT; + * the callback must copy anything it needs before returning. Every refusal, + * failure or back-out of the PSBT review calls failed_cb instead. + */ +void scan_review_psbt(lv_obj_t *parent, const uint8_t *data, size_t len, + void (*return_cb)(void), void (*complete_cb)(void), + scan_psbt_signed_cb_t signed_cb, + scan_psbt_failed_cb_t failed_cb, void *user_data); + /** * Show the scan page */ diff --git a/main/pages/scan/scan_internal.h b/main/pages/scan/scan_internal.h index 46f47122..75509f23 100644 --- a/main/pages/scan/scan_internal.h +++ b/main/pages/scan/scan_internal.h @@ -10,6 +10,7 @@ #include "../../core/message_sign.h" #include "../../ui/menu.h" #include "../../ui/sankey.h" +#include "scan.h" #include #include #include @@ -49,6 +50,12 @@ typedef struct { bool is_bip322; char *scanned_mnemonic; + + /* Set by scan_review_psbt(): the signed PSBT, or why there is none, goes + * back to the caller instead of the export menu or an error dialog. */ + scan_psbt_signed_cb_t psbt_signed_cb; + scan_psbt_failed_cb_t psbt_failed_cb; + void *psbt_user_data; } scan_ctx_t; extern scan_ctx_t scan_ctx; @@ -57,6 +64,10 @@ extern scan_ctx_t scan_ctx; void scan_dismiss_progress(void); void scan_defer_with_progress(const char *title, const char *text, lv_timer_cb_t cb); +// Hands `failure` to the scan_review_psbt() caller, else shows `message` and +// then calls local_cb (NULL stays on the current screen) +void scan_psbt_fail(scan_psbt_failure_t failure, const char *message, + void (*local_cb)(void), uint32_t timeout_ms); /* scan_review_widgets.c */ void scan_create_sign_action_row(lv_obj_t *parent, lv_event_cb_t sign_cb); diff --git a/main/pages/scan/scan_psbt_review.c b/main/pages/scan/scan_psbt_review.c index 26c919b3..3a8f414b 100644 --- a/main/pages/scan/scan_psbt_review.c +++ b/main/pages/scan/scan_psbt_review.c @@ -172,8 +172,27 @@ static void classify_output(const classified_input_t *inputs, size_t num_inputs, } } +// Why the policy gate last refused the PSBT +static scan_psbt_failure_t policy_refusal; + +static const char *policy_refusal_message(scan_psbt_failure_t refusal) { + switch (refusal) { + case SCAN_PSBT_NOTHING_TO_SIGN: + return "No input matches this wallet's signing policy"; + case SCAN_PSBT_REFUSED: + return "Refused by a signing setting"; + default: + return "PSBT cannot be signed safely"; + } +} + static void policy_reject_dismissed_cb(void *user_data) { (void)user_data; + if (scan_ctx.psbt_failed_cb) { + scan_psbt_fail(policy_refusal, policy_refusal_message(policy_refusal), NULL, + 0); + return; + } if (scan_ctx.return_cb) scan_ctx.return_cb(); } @@ -210,15 +229,18 @@ static bool owners_classify(psbt_owners_t *o) { void scan_psbt_resume_review(bool offer_descriptor) { psbt_owners_t owners; if (!owners_classify(&owners)) { - dialog_show_error_timeout("Invalid PSBT data", scan_ctx.return_cb, 0); + scan_psbt_fail(SCAN_PSBT_INVALID, "Invalid PSBT data", scan_ctx.return_cb, + 0); return; } if (psbt_sign_policy_allows_review(scan_ctx.psbt, owners.inputs, owners.outputs, policy_reject_dismissed_cb, offer_descriptor ? psbt_offer_descriptor_cb - : NULL) && + : NULL, + &policy_refusal) && !create_psbt_info_display(&owners)) - dialog_show_error_timeout("Invalid PSBT data", scan_ctx.return_cb, 0); + scan_psbt_fail(SCAN_PSBT_INVALID, "Invalid PSBT data", scan_ctx.return_cb, + 0); owners_free(&owners); } @@ -302,6 +324,11 @@ bool scan_psbt_parse_base64(const char *base64_data) { static void mismatch_dialog_cb(void *user_data) { scan_psbt_cleanup(); + if (scan_ctx.psbt_failed_cb) { + scan_psbt_fail(SCAN_PSBT_NETWORK_MISMATCH, "PSBT is for another network", + NULL, 0); + return; + } if (scan_ctx.return_cb) { scan_ctx.return_cb(); } diff --git a/main/pages/scan/scan_psbt_sign.c b/main/pages/scan/scan_psbt_sign.c index 3f66b9e0..d5f3ea4f 100644 --- a/main/pages/scan/scan_psbt_sign.c +++ b/main/pages/scan/scan_psbt_sign.c @@ -21,6 +21,22 @@ static void show_export_choice(void); +/* A caller that opened the flow through scan_review_psbt() takes the signed + * PSBT itself; everyone else picks an export from the menu. */ +static void finish_signed_psbt(void) { + if (scan_ctx.psbt_signed_cb) { + scan_psbt_signed_cb_t cb = scan_ctx.psbt_signed_cb; + void *user_data = scan_ctx.psbt_user_data; + scan_ctx.psbt_signed_cb = NULL; + scan_ctx.psbt_failed_cb = NULL; + scan_ctx.psbt_user_data = NULL; + scan_page_hide(); + cb(scan_ctx.psbt, user_data); + return; + } + show_export_choice(); +} + void scan_export_destroy_menu(void) { if (scan_ctx.export_menu) { ui_menu_destroy(scan_ctx.export_menu); @@ -30,7 +46,7 @@ void scan_export_destroy_menu(void) { static void partial_sign_ack_cb(void *user_data) { (void)user_data; - show_export_choice(); + finish_signed_psbt(); } static void deferred_sign_cb(lv_timer_t *timer) { @@ -38,7 +54,7 @@ static void deferred_sign_cb(lv_timer_t *timer) { if (!scan_ctx.psbt) { scan_dismiss_progress(); - dialog_show_error_timeout("No PSBT loaded", NULL, 2000); + scan_psbt_fail(SCAN_PSBT_INTERNAL, "No PSBT loaded", NULL, 2000); return; } @@ -53,7 +69,8 @@ static void deferred_sign_cb(lv_timer_t *timer) { if (signatures_added == 0) { scan_dismiss_progress(); - dialog_show_error_timeout("Failed to sign PSBT", NULL, 2000); + scan_psbt_fail(SCAN_PSBT_NOTHING_TO_SIGN, "Failed to sign PSBT", NULL, + 2000); return; } @@ -77,12 +94,13 @@ static void deferred_sign_cb(lv_timer_t *timer) { scan_dismiss_progress(); if (ret != WALLY_OK) { - dialog_show_error_timeout("Failed to encode PSBT", NULL, 2000); + scan_psbt_fail(SCAN_PSBT_INTERNAL, "Failed to encode PSBT", NULL, 2000); return; } - scan_ctx.saved_return_cb = - scan_ctx.complete_cb ? scan_ctx.complete_cb : scan_ctx.return_cb; + if (!scan_ctx.psbt_signed_cb) + scan_ctx.saved_return_cb = + scan_ctx.complete_cb ? scan_ctx.complete_cb : scan_ctx.return_cb; // A PSBT built so that refused inputs pick up a signature from a key used // elsewhere in the same transaction is not an accident. The signatures were @@ -146,7 +164,7 @@ static void deferred_sign_cb(lv_timer_t *timer) { return; } - show_export_choice(); + finish_signed_psbt(); } // Tears down the chooser, then returns to the caller that opened the diff --git a/main/pages/scan/scan_review_widgets.c b/main/pages/scan/scan_review_widgets.c index fb86ca3f..94c61250 100644 --- a/main/pages/scan/scan_review_widgets.c +++ b/main/pages/scan/scan_review_widgets.c @@ -142,6 +142,10 @@ void scan_create_review_note(lv_obj_t *parent, const char *text, } static void back_button_cb(lv_event_t *e) { + if (scan_ctx.psbt_failed_cb) { + scan_psbt_fail(SCAN_PSBT_DECLINED, "Declined", NULL, 0); + return; + } if (scan_ctx.return_cb) { scan_ctx.return_cb(); } diff --git a/main/pages/shared/descriptor_loader.c b/main/pages/shared/descriptor_loader.c index 275b44cb..32063521 100644 --- a/main/pages/shared/descriptor_loader.c +++ b/main/pages/shared/descriptor_loader.c @@ -1,6 +1,8 @@ #include "descriptor_loader.h" #include "../../../components/cUR/src/types/bytes_type.h" #include "../../../components/cUR/src/types/output.h" +#include "../../core/debug_log.h" +#include "../../core/descriptor_checksum.h" #include "../../core/descriptor_text.h" #include "../../core/key.h" #include "../../core/miniscript_policy.h" @@ -22,6 +24,9 @@ #include #include +static void debug_log_descriptor_shape(const char *label, + const char *descriptor); + bool descriptor_loader_show_error(descriptor_validation_result_t result) { switch (result) { case VALIDATION_SUCCESS: @@ -150,6 +155,26 @@ static void id_prompt_cleanup(void) { g_id_prompt_ctx = NULL; } +typedef struct { + char id[REGISTRY_ID_MAX_LEN]; + storage_location_t loc; + validation_complete_cb validation_cb; + void *user_data; +} fixed_id_loc_context_t; + +static void fixed_id_validation_cb(descriptor_validation_result_t result, + void *user_data) { + debug_logf("descriptor_loader fixed_id_validation result=%d", result); + fixed_id_loc_context_t *ctx = (fixed_id_loc_context_t *)user_data; + if (!ctx) + return; + validation_complete_cb cb = ctx->validation_cb; + void *cb_user_data = ctx->user_data; + free(ctx); + if (cb) + cb(result, cb_user_data); +} + static void id_prompt_ready_cb(lv_event_t *e) { (void)e; if (!g_id_prompt_ctx) @@ -246,8 +271,7 @@ static void loaded_register_named_cb(const char *name, storage_location_t loc, loaded_finish(); return; } - if (storage_descriptor_exists(STORAGE_FLASH, name, - STORAGE_DESCRIPTOR_BIP138)) { + if (registry_name_registered(name)) { dialog_show_error_timeout("A registered descriptor already uses this name", loaded_name_taken_cb, 0); return; @@ -301,6 +325,18 @@ static void descriptor_confirm_wrapper(const char *message, dialog_show_danger_confirm(message, proceed, NULL, DIALOG_STYLE_OVERLAY); } +static void fixed_id_loc_wrapper(void (*proceed)(const char *id, + storage_location_t loc, + void *user_data), + void *user_data) { + fixed_id_loc_context_t *ctx = (fixed_id_loc_context_t *)user_data; + debug_logf("descriptor_loader fixed_id_loc ctx=%d proceed=%d", ctx != NULL, + proceed != NULL); + if (!ctx || !proceed) + return; + proceed(ctx->id, ctx->loc, NULL); +} + // Context for descriptor info confirmation dialog typedef struct { void (*proceed)(bool confirmed, void *user_data); @@ -494,10 +530,12 @@ lv_obj_t *descriptor_policy_view_create(lv_obj_t *parent, const char *policy, return cont; } -// UI wrapper for descriptor info confirmation -static void descriptor_info_confirm_wrapper(const descriptor_info_t *info, - void (*proceed)(bool confirmed, - void *user_data)) { +// Descriptor info confirmation titled with `prompt`, with its alias when not +// NULL +static void show_descriptor_info(const descriptor_info_t *info, + const char *alias, const char *prompt, + void (*proceed)(bool confirmed, + void *user_data)) { info_confirm_context_t *ctx = malloc(sizeof(info_confirm_context_t)); if (!ctx) { proceed(false, NULL); @@ -513,20 +551,10 @@ static void descriptor_info_confirm_wrapper(const descriptor_info_t *info, ctx->root = root; lv_obj_add_event_cb(root, info_confirm_deleted, LV_EVENT_DELETE, ctx); - // Title with "Load?" prompt - char title[48]; - if (info->is_miniscript) { - snprintf(title, sizeof(title), "Miniscript (%u key%s) - Load?", - info->num_keys, info->num_keys == 1 ? "" : "s"); - } else if (info->is_multisig) { - snprintf(title, sizeof(title), "Multisig (%u of %u) - Load?", - info->threshold, info->num_keys); - } else if (info->script_type) { - snprintf(title, sizeof(title), "Single-sig (%s) - Load?", - info->script_type); - } else { - snprintf(title, sizeof(title), "Single-sig - Load?"); - } + char policy[REGISTRY_LABEL_MAX_LEN]; + descriptor_info_policy_name(info, policy, sizeof(policy)); + char title[REGISTRY_LABEL_MAX_LEN + 16]; + snprintf(title, sizeof(title), "%s - %s", policy, prompt); lv_obj_t *title_label = theme_create_label(root, title, false); lv_obj_set_style_text_font(title_label, theme_font_medium(), 0); lv_obj_set_style_text_color(title_label, highlight_color(), 0); @@ -564,6 +592,15 @@ static void descriptor_info_confirm_wrapper(const descriptor_info_t *info, if (!key_get_fingerprint_hex(my_fp)) my_fp[0] = '\0'; // matches no key, so nothing is highlighted + if (alias) { + char alias_text[REGISTRY_ID_MAX_LEN + 8]; + snprintf(alias_text, sizeof(alias_text), "Alias: %s", alias); + lv_obj_t *alias_label = theme_create_label(scroll, alias_text, false); + lv_obj_set_width(alias_label, scroll_w); + lv_label_set_long_mode(alias_label, LV_LABEL_LONG_WRAP); + lv_obj_set_style_pad_bottom(alias_label, 12, 0); + } + // Key entries for (uint32_t i = 0; i < info->num_keys; i++) { // Identifier letter at line start, then fingerprint icon + hex @@ -666,6 +703,41 @@ static void descriptor_info_confirm_wrapper(const descriptor_info_t *info, } } +static void descriptor_info_confirm_wrapper(const descriptor_info_t *info, + void (*proceed)(bool confirmed, + void *user_data), + void *user_data) { + (void)user_data; + show_descriptor_info(info, NULL, "Load?", proceed); +} + +static void fixed_id_info_confirm_wrapper(const descriptor_info_t *info, + void (*proceed)(bool confirmed, + void *user_data), + void *user_data) { + const fixed_id_loc_context_t *ctx = user_data; + show_descriptor_info(info, ctx->id, "Load?", proceed); +} + +bool descriptor_loader_confirm_unregister(const registry_entry_t *entry, + void (*proceed)(bool confirmed, + void *user_data)) { + char *descriptor_str = NULL; + descriptor_info_t *info = calloc(1, sizeof(*info)); + int our_key_index = + entry->my_key_index == SIZE_MAX ? -1 : (int)entry->my_key_index; + bool ok = + info && descriptor_string_from_descriptor(entry->desc, &descriptor_str) && + descriptor_info_extract(entry->desc, descriptor_str, our_key_index, info); + if (ok) + show_descriptor_info(info, entry->id, "Unregister?", proceed); + free(descriptor_str); + if (info) + free(info->policy); + free(info); + return ok; +} + void descriptor_loader_process_scanner(validation_complete_cb validation_cb, void *user_data, void (*error_cb)(void)) { @@ -715,6 +787,34 @@ void descriptor_loader_process_string(const char *descriptor_str, free(converted); } +void descriptor_loader_process_string_with_id( + const char *descriptor_str, const char *id, storage_location_t loc, + validation_complete_cb validation_cb, void *user_data) { + if (!descriptor_str || !id || id[0] == '\0') { + if (validation_cb) + validation_cb(VALIDATION_PARSE_ERROR, user_data); + return; + } + + fixed_id_loc_context_t *fixed = malloc(sizeof(*fixed)); + if (!fixed) { + if (validation_cb) + validation_cb(VALIDATION_INTERNAL_ERROR, user_data); + return; + } + memset(fixed, 0, sizeof(*fixed)); + snprintf(fixed->id, sizeof(fixed->id), "%s", id); + fixed->loc = loc; + fixed->validation_cb = validation_cb; + fixed->user_data = user_data; + + debug_log_descriptor_shape("descriptor_loader fixed_id", descriptor_str); + session_cleanup_register(descriptor_validation_cancel); + descriptor_validate_and_load_persistent( + descriptor_str, fixed_id_validation_cb, descriptor_confirm_wrapper, + fixed_id_info_confirm_wrapper, fixed_id_loc_wrapper, fixed); +} + void descriptor_loader_process_string_watch_only( const char *descriptor_str, validation_complete_cb validation_cb, void *user_data) { @@ -811,3 +911,46 @@ char *descriptor_extract_from_scanner(void) { return qr_scanner_get_completed_content(); } + +static bool is_base58_char(char c) { + return (c >= '1' && c <= '9') || (c >= 'A' && c <= 'H') || + (c >= 'J' && c <= 'N') || (c >= 'P' && c <= 'Z') || + (c >= 'a' && c <= 'k') || (c >= 'm' && c <= 'z'); +} + +static void debug_log_descriptor_shape(const char *label, + const char *descriptor) { + if (!label || !descriptor) { + debug_logf("%s len=0", label ? label : "descriptor"); + return; + } + + char redacted[512]; + size_t out = 0; + bool truncated = false; + size_t len = strlen(descriptor); + for (size_t i = 0; descriptor[i] != '\0' && out + 1 < sizeof(redacted);) { + if ((descriptor[i] == 'x' || descriptor[i] == 't') && + strncmp(descriptor + i + 1, "pub", 3) == 0) { + const char *token = descriptor[i] == 'x' ? "" : ""; + size_t token_len = strlen(token); + if (out + token_len >= sizeof(redacted)) { + truncated = true; + break; + } + memcpy(redacted + out, token, token_len); + out += token_len; + i += 4; + while (is_base58_char(descriptor[i])) + i++; + continue; + } + + redacted[out++] = descriptor[i++]; + } + if (out + 1 >= sizeof(redacted)) + truncated = true; + redacted[out] = '\0'; + debug_logf("%s len=%u shape=%s%s", label, (unsigned)len, redacted, + truncated ? "..." : ""); +} diff --git a/main/pages/shared/descriptor_loader.h b/main/pages/shared/descriptor_loader.h index a62b5984..f90d8927 100644 --- a/main/pages/shared/descriptor_loader.h +++ b/main/pages/shared/descriptor_loader.h @@ -2,6 +2,7 @@ #define DESCRIPTOR_LOADER_H #include "../../core/descriptor_validator.h" +#include "../../core/registry.h" #include #include @@ -39,6 +40,16 @@ void descriptor_loader_process_string(const char *descriptor_str, validation_complete_cb validation_cb, void *user_data); +/** + * Process a descriptor with the normal warning and descriptor-info review UI, + * but register it under a caller-supplied id/location instead of prompting. + * The exact text is registered: no BlueWallet conversion and no derivation + * suffix appended. + */ +void descriptor_loader_process_string_with_id( + const char *descriptor_str, const char *id, storage_location_t loc, + validation_complete_cb validation_cb, void *user_data); + /** * Watch-only (keyless) variant of process_string: normalize, infer the network * from the descriptor, enter watch-only mode, and validate/load without a key. @@ -57,6 +68,15 @@ void descriptor_loader_process_string_watch_only( */ void descriptor_loader_show_loaded_menu(void (*done_cb)(void)); +/** + * Ask whether to unregister `entry`: its alias with the review of its + * descriptor it was loaded with. False when the review cannot be built; + * proceed is then never called. + */ +KERN_WARN_UNUSED_RESULT bool descriptor_loader_confirm_unregister( + const registry_entry_t *entry, + void (*proceed)(bool confirmed, void *user_data)); + /** * Show a source selection menu for loading descriptors. * Presents QR / Flash / SD Card options. diff --git a/main/pages/store_descriptor.c b/main/pages/store_descriptor.c index 6cef0c34..f3c17ccd 100644 --- a/main/pages/store_descriptor.c +++ b/main/pages/store_descriptor.c @@ -90,7 +90,7 @@ static void do_save_named(const char *id) { if (target_format == STORAGE_DESCRIPTOR_BIP138) { uint8_t *blob = NULL; size_t blob_len = 0; - if (bip138_backup_encrypt(descriptor_text, &blob, &blob_len)) { + if (bip138_backup_encrypt(descriptor_text, NULL, &blob, &blob_len)) { ret = storage_save_descriptor(target_location, id, blob, blob_len, STORAGE_DESCRIPTOR_BIP138); free(blob); diff --git a/main/qr/export.c b/main/qr/export.c index d4b45dd5..c66981cf 100644 --- a/main/qr/export.c +++ b/main/qr/export.c @@ -116,6 +116,21 @@ qr_export_t *qr_export_create(int format, const char *content, size_t density) { return NULL; } +qr_export_t *qr_export_from_bbqr(BBQrParts *parts) { + if (!parts || parts->count <= 0 || !parts->parts) { + bbqr_parts_free(parts); + return NULL; + } + qr_export_t *export = calloc(1, sizeof(*export)); + if (!export) { + bbqr_parts_free(parts); + return NULL; + } + export->bbqr = parts; + export->count = (size_t)parts->count; + return export; +} + size_t qr_export_part_count(const qr_export_t *export) { return export->count; } bool qr_export_is_fountain(const qr_export_t *export) { diff --git a/main/qr/export.h b/main/qr/export.h index 155c362d..8ebfa75e 100644 --- a/main/qr/export.h +++ b/main/qr/export.h @@ -1,6 +1,7 @@ #ifndef QR_EXPORT_H #define QR_EXPORT_H +#include "../../components/bbqr/src/bbqr.h" #include #include #include @@ -8,6 +9,8 @@ // Content is borrowed and must remain valid until qr_export_free(). typedef struct qr_export qr_export_t; qr_export_t *qr_export_create(int format, const char *content, size_t density); +// Takes ownership of parts, on failure too. +qr_export_t *qr_export_from_bbqr(BBQrParts *parts); void qr_export_free(qr_export_t *export); size_t qr_export_part_count(const qr_export_t *export); bool qr_export_is_fountain(const qr_export_t *export); diff --git a/main/qr/parser.c b/main/qr/parser.c index 9b3e7735..9c3c4e30 100644 --- a/main/qr/parser.c +++ b/main/qr/parser.c @@ -370,7 +370,8 @@ static int detect_format(const char *data, size_t data_len, BBQrCode **bbqr) { } } else if (data_len >= 3 && starts_with_case_insensitive(data, "ur:")) { return FORMAT_UR; - } else if (data_len >= BBQR_HEADER_LEN && data[0] == 'B' && data[1] == '$') { + } else if (data_len >= BBQR_HEADER_LEN && + toupper((unsigned char)data[0]) == 'B' && data[1] == '$') { // Validate BBQr header (convert to uppercase for validation) char encoding = toupper((unsigned char)data[2]); char file_type = toupper((unsigned char)data[3]); diff --git a/main/qr/test/test_parser.c b/main/qr/test/test_parser.c index 118e609b..5583bc2a 100644 --- a/main/qr/test/test_parser.c +++ b/main/qr/test/test_parser.c @@ -427,6 +427,43 @@ static void test_valid_ur_still_processes(void) { qr_parser_destroy(parser); } +/* A single-part BBQr frame carrying a 195 byte binary payload, as a Liana + * airgap request arrives. */ +#define BIP_REQUEST_BODY \ + "42495058585801010E151E957222A2B72C605E0A16E9F5740A" \ + "048000003080000000800000008000000204800000308000000080000001800000020" \ + "480000030800000008000000280000002048000003080000000800000038000000204" \ + "800000308000000080000004800000020480000030800000008000000580000002048" \ + "000003080000000800000068000000204800000308000000080000007800000020480" \ + "0000308000000080000008800000020480000030800000008000000980000002" + +static const unsigned char BIP_REQUEST_PREFIX[] = { + 0x42, 0x49, 0x50, 0x58, 0x58, 0x58, 0x01, 0x01, 0x0e, + 0x15, 0x1e, 0x95, 0x72, 0x22, 0xa2, 0xb7, 0x2c, 0x60, + 0x5e, 0x0a, 0x16, 0xe9, 0xf5, 0x74, 0x0a}; + +static void check_bip_request_payload(QRPartParser *parser) { + CHECK(qr_parser_is_complete(parser)); + CHECK(!qr_parser_is_failed(parser)); + CHECK(qr_parser_get_format(parser) == FORMAT_BBQR); + CHECK(qr_parser_get_bbqr_file_type(parser) == 'B'); + size_t result_len = 0; + char *result = qr_parser_result(parser, &result_len); + CHECK(result != NULL); + CHECK(result_len == 195); + CHECK(memcmp(result, BIP_REQUEST_PREFIX, sizeof(BIP_REQUEST_PREFIX)) == 0); + free(result); +} + +static void test_bbqr_accepts_lowercase_prefix(void) { + const char *frame = "b$hb0100" BIP_REQUEST_BODY; + QRPartParser *parser = qr_parser_create(); + CHECK(parser != NULL); + CHECK(qr_parser_parse_with_len(parser, frame, strlen(frame)) == 0); + check_bip_request_payload(parser); + qr_parser_destroy(parser); +} + int main(void) { test_format_none_still_completes(); test_incomplete_pmofn_like_text_remains_plain(); @@ -449,6 +486,7 @@ int main(void) { test_bbqr_result_failure_clears_length(); test_valid_bbqr_still_assembles(); test_valid_ur_still_processes(); + test_bbqr_accepts_lowercase_prefix(); if (failures != 0) { fprintf(stderr, "%d QR parser test(s) failed\n", failures); diff --git a/main/qr/viewer.c b/main/qr/viewer.c index 30af7e1b..caa34302 100644 --- a/main/qr/viewer.c +++ b/main/qr/viewer.c @@ -41,6 +41,7 @@ static lv_timer_t *message_timer; static lv_timer_t *animation_timer; static void (*return_callback)(void); static char *qr_content_copy; +static BBQrParts *pending_bbqr; // pre-encoded parts the first view takes over static int qr_source_format; static bool paused; static uint16_t qr_density = QR_DENSITY_DEFAULT; @@ -219,7 +220,11 @@ static export_view_t *prepare_view(uint16_t density) { export_view_t *v = calloc(1, sizeof(*v)); if (!v) return NULL; - v->source = qr_export_create(qr_source_format, qr_content_copy, density); + if (pending_bbqr) { + v->source = qr_export_from_bbqr(pending_bbqr); + pending_bbqr = NULL; + } else + v->source = qr_export_create(qr_source_format, qr_content_copy, density); if (!v->source) goto fail; const char *first = qr_export_frame(v->source, 0); @@ -611,6 +616,28 @@ bool qr_viewer_page_create_with_format(lv_obj_t *parent, int qr_format, return true; } +bool qr_viewer_page_create_with_bbqr_parts(lv_obj_t *parent, BBQrParts *parts, + const char *title, + void (*return_cb)(void)) { + if (!parent || !parts) { + bbqr_parts_free(parts); + return false; + } + qr_viewer_page_destroy(); + session_cleanup_register(qr_viewer_page_destroy); + pending_bbqr = parts; + qr_source_format = FORMAT_BBQR; + qr_density = settings_get_qr_density(); + qr_shade = settings_get_qr_shade(); + qr_fps = settings_get_qr_fps(); + return_callback = return_cb; + if (!setup_qr_viewer_ui(parent, title)) { + qr_viewer_page_destroy(); + return false; + } + return true; +} + void qr_viewer_page_create(lv_obj_t *parent, const char *content, const char *title, void (*return_cb)(void)) { if (!qr_viewer_page_create_with_format(parent, FORMAT_NONE, content, title, @@ -686,6 +713,8 @@ void qr_viewer_page_destroy(void) { view = NULL; free(qr_content_copy); qr_content_copy = NULL; + bbqr_parts_free(pending_bbqr); + pending_bbqr = NULL; if (qr_viewer_screen) lv_obj_del(qr_viewer_screen); qr_viewer_screen = NULL; diff --git a/main/qr/viewer.h b/main/qr/viewer.h index 0bc72b8c..888928ff 100644 --- a/main/qr/viewer.h +++ b/main/qr/viewer.h @@ -1,6 +1,7 @@ #ifndef QR_VIEWER_H #define QR_VIEWER_H +#include "../components/bbqr/src/bbqr.h" #include "../utils/attributes.h" #include @@ -28,6 +29,16 @@ qr_viewer_page_create_with_format(lv_obj_t *parent, int qr_format, const char *content, const char *title, void (*return_cb)(void)); +/** + * Create the QR viewer page from pre-generated BBQr parts. + * + * Takes ownership of parts, on failure too. + */ +KERN_WARN_UNUSED_RESULT bool +qr_viewer_page_create_with_bbqr_parts(lv_obj_t *parent, BBQrParts *parts, + const char *title, + void (*return_cb)(void)); + /** * Make a widget open the QR viewer fullscreen when tapped (tap again to * return). Copies content/title; frees them when the widget is deleted. diff --git a/scripts/test.sh b/scripts/test.sh index 3f27726f..9c3ca4df 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -22,6 +22,9 @@ make -C "$REPO_ROOT/main/qr/test" run echo "Running bip138 tests..." make -C "$REPO_ROOT/components/bip138" run +echo "Running BIP flow tests..." +make -C "$REPO_ROOT/main/pages/bip_flow/test" run + echo "Running core tests..." make -C "$REPO_ROOT/main/core/test" run diff --git a/simulator/CMakeLists.txt b/simulator/CMakeLists.txt index b0d36d45..199d77bb 100644 --- a/simulator/CMakeLists.txt +++ b/simulator/CMakeLists.txt @@ -156,6 +156,7 @@ set(APP_UTIL_SOURCES # --- Core application modules --- set(APP_CORE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/settings.c + ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/debug_log.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/nvs_secure.c ${CMAKE_CURRENT_SOURCE_DIR}/platform/esp_idf_stubs/storage_sim.c ${CMAKE_CURRENT_SOURCE_DIR}/../main/core/pin.c @@ -303,6 +304,8 @@ set(APP_PAGE_SOURCES ${APP_PAGES_DIR}/settings/firmware_update.c ${APP_PAGES_DIR}/settings/self_test_page.c # Shared pages + ${APP_PAGES_DIR}/bip_flow/bip388.c + ${APP_PAGES_DIR}/bip_flow/bip_flow.c ${APP_PAGES_DIR}/shared/address_checker.c ${APP_PAGES_DIR}/shared/descriptor_loader.c ${APP_PAGES_DIR}/shared/kef_decrypt_page.c @@ -373,6 +376,24 @@ target_link_libraries(lvgl PUBLIC ${SDL2_LIBRARIES} ) +# --- kern-bipqr: the firmware's Rust staticlib, built for the host. The bipqr +# flow decodes its requests and encodes its responses through it. --- +set(KERN_BIPQR_TARGET_DIR ${CMAKE_CURRENT_BINARY_DIR}/kern_bipqr) +set(KERN_BIPQR_LIB ${KERN_BIPQR_TARGET_DIR}/release/${CMAKE_STATIC_LIBRARY_PREFIX}kern_bipqr${CMAKE_STATIC_LIBRARY_SUFFIX}) +find_program(CARGO_EXECUTABLE cargo REQUIRED) +# Always runs: cargo tracks the crate sources and only relinks on a change +add_custom_target(kern_bipqr_rust + COMMAND ${CMAKE_COMMAND} -E env CARGO_TARGET_DIR=${KERN_BIPQR_TARGET_DIR} + ${CARGO_EXECUTABLE} build --release + --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/../components/bipqr/Cargo.toml + BYPRODUCTS ${KERN_BIPQR_LIB} + COMMENT "Building kern-bipqr for the host" + VERBATIM +) +add_library(kern_bipqr STATIC IMPORTED GLOBAL) +set_target_properties(kern_bipqr PROPERTIES IMPORTED_LOCATION ${KERN_BIPQR_LIB}) +add_dependencies(kern_bipqr kern_bipqr_rust) + add_executable(kern_simulator ${SIM_SOURCES} ${STUB_SOURCES} @@ -409,6 +430,8 @@ target_include_directories(kern_simulator PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../components/k_quirc/src ${CMAKE_CURRENT_SOURCE_DIR}/../components/cUR/src ${CMAKE_CURRENT_SOURCE_DIR}/../components/video + # kern-bipqr C headers: the bipqr submodule + ${CMAKE_CURRENT_SOURCE_DIR}/../components/bipqr/upstream/bipqr-ll/include # LVGL ${LVGL_DIR} ${LVGL_DIR}/src @@ -432,6 +455,7 @@ target_compile_definitions(kern_simulator PRIVATE $<$:CONFIG_KERN_BOARD_CROWPANEL=1> $<$:CONFIG_KERN_BOARD_WAVE_7B=1> $<$:CONFIG_KERN_BOARD_P4_PICO=1> + "CONFIG_KERN_BOARD_NAME=\"${SIM_BOARD}\"" ) target_compile_options(kern_simulator PRIVATE @@ -472,6 +496,8 @@ target_link_libraries(kern_simulator PRIVATE Threads::Threads m wally + kern_bipqr + ${CMAKE_DL_LIBS} ${MBEDTLS_LIB} ${MBEDCRYPTO_LIB} ${MBEDX509_LIB} diff --git a/simulator/tests/scan_registry.c b/simulator/tests/scan_registry.c index 3c31f435..0869f1a9 100644 --- a/simulator/tests/scan_registry.c +++ b/simulator/tests/scan_registry.c @@ -142,10 +142,8 @@ static void test_network(wallet_network_t network) { replace_key(2, true); assert(wallet_is_initialized() && wallet_get_network() == network); assert(registry_count() == 0); - assert( - storage_descriptor_exists(STORAGE_FLASH, a, STORAGE_DESCRIPTOR_BIP138)); - assert( - storage_descriptor_exists(STORAGE_FLASH, b, STORAGE_DESCRIPTOR_BIP138)); + assert(registry_name_registered(a)); + assert(registry_name_registered(b)); puts("PASS: a key without backups loads with an empty registry; backups " "remain"); }